text
stringlengths 184
4.48M
|
---|
<div class="container-fruid mt-5">
<% if flash[:success].present? %>
<div class="alert alert-success" role="alert">
<%= flash[:success] %>
</div>
<% end %>
<% if flash[:error].present? %>
<div class="alert alert-danger" role="alert">
<%= flash[:error] %>
<ul>
<% flash[:error_messages].each do |_column, messages| %>
<% messages.each do |message| %>
<li><%= message %></li>
<% end %>
<% end %>
</ul>
</div>
<% end %>
<h1 class="text-center">
<% age_slider %>
</h1>
<div class="row">
<div class="col-xs-12 col-xl-8 offset-xl-1">
<canvas id="myChart" width="250" height="150"></canvas>
<script>draw_graph();</script>
</div>
<div class="col-xl-3 growth-record-modal">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#growth-record-modal">
記録する
</button>
<a href="<%= growth_curve_sample_edit_path %>">
<button type="button" class="btn btn-secondary">編集する</button>
</a>
</div>
</div>
<div id="growth-record-modal" class="modal fade bs-example-modal-new growth-record-modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<!-- Modal Content: begins -->
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<div class="modal-title">成長記録</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<div class="body-message">
<%# form-horizontal...表示領域の幅に応じて、ラベルとフォーム部品を水平に並べる %>
<%# form要素のclass属性にform-horizontalを指定する。 %>
<%= form_for :growth_record, url: '/growth_curve_sample/create', class: 'form-horizontal' do |f| %>
<div class="form-group">
<label class="control-label col-lg-3">月齢</label>
<div class="col-lg-6">
<%= f.text_field :age %><input id="unit-display__age" type="text" disabled="true" value="才">
<%= f.text_field :age_of_the_moon %><input id="unit-display__age_of_the_moon" type="text" disabled="true" value="ヶ月">
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-3">体重</label>
<div class="col-lg-6">
<%= f.text_field :weight %>
<input id="unit-display__weight" type="text" disabled="true" value="kg">
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-3">身長</label>
<div class="col-lg-6">
<%= f.text_field :height %>
<input id="unit-display__height" type="text" disabled="true" value="cm">
</div>
</div>
<div class="form-group">
<div class="col-lg-4">
<button type="submit" class="btn btn-warning btn-lg mt-3">記録する</button>
</div>
</div>
<% end %>
</div>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">閉じる</button>
</div>
</div>
<!-- Modal Content: ends -->
</div>
</div>
|
using DataStructures
using TimeZones
"""
create_tuples(input_data::InputData)
Create all tuples used in the model, and save them in the tuplebook dict.
# Arguments
- `input_data::InputData`: Struct containing data used to build the model.
"""
function create_tuples(input_data::InputData) # unused, should be debricated
tuplebook = OrderedDict()
tuplebook["res_nodes_tuple"] = reserve_nodes(input_data)
tuplebook["res_tuple"] = reserve_market_directional_tuples(input_data)
tuplebook["process_tuple"] = process_topology_tuples(input_data)
tuplebook["proc_online_tuple"] = online_process_tuples(input_data)
tuplebook["reserve_groups"] = reserve_groups(input_data)
tuplebook["res_potential_tuple"] = reserve_process_tuples(input_data)
tuplebook["nodegroup_reserves"] = nodegroup_reserves(input_data)
tuplebook["node_reserves"] = node_reserves(input_data)
tuplebook["res_pot_prod_tuple"] = producer_reserve_process_tuples(input_data)
tuplebook["res_pot_cons_tuple"] = consumer_reserve_process_tuples(input_data)
tuplebook["node_state_tuple"] = state_node_tuples(input_data)
tuplebook["node_balance_tuple"] = balance_node_tuples(input_data)
tuplebook["proc_balance_tuple"] = balance_process_tuples(input_data)
tuplebook["proc_op_balance_tuple"] = operative_slot_process_tuples(input_data)
tuplebook["proc_op_tuple"] = piecewise_efficiency_process_tuples(input_data)
tuplebook["cf_balance_tuple"] = cf_process_topology_tuples(input_data)
tuplebook["lim_tuple"] = fixed_limit_process_topology_tuples(input_data)
tuplebook["trans_tuple"] = transport_process_topology_tuples(input_data)
tuplebook["res_eq_tuple"] = reserve_nodegroup_tuples(input_data)
tuplebook["res_eq_updn_tuple"] = up_down_reserve_market_tuples(input_data)
tuplebook["res_final_tuple"] = reserve_market_tuples(input_data)
tuplebook["fixed_value_tuple"] = fixed_market_tuples(input_data)
tuplebook["ramp_tuple"] = process_topology_ramp_times_tuples(input_data)
tuplebook["risk_tuple"] = scenarios(input_data)
tuplebook["balance_market_tuple"] = create_balance_market_tuple(input_data)
tuplebook["market_tuple"] = create_market_tuple(input_data)
tuplebook["state_reserves"] = state_reserves(input_data)
tuplebook["reserve_limits"] = create_reserve_limits(input_data)
tuplebook["setpoint_tuples"] = setpoint_tuples(input_data)
tuplebook["block_tuples"] = block_tuples(input_data)
tuplebook["group_tuples"] = create_group_tuples(input_data)
tuplebook["node_diffusion_tuple"] = node_diffusion_tuple(input_data)
tuplebook["diffusion_nodes"] = diffusion_nodes(input_data)
tuplebook["node_delay_tuple"] = node_delay_tuple(input_data)
tuplebook["bid_slot_tuple"] = bid_slot_tuples(input_data)
tuplebook["bid_scen_tuple"] = bid_scenario_tuples(input_data)
return tuplebook
end
"""
validate_tuple(mc::OrderedDict, tuple::NTuple{N, String} where N, s_index::Int)
Helper function used to correct generated index tuples in cases when the start of the optimization horizon is the same for all scenarios.
"""
function validate_tuple(mc::OrderedDict, tuple::NTuple{N, String} where N, s_index::Int)
if !isempty(mc["validation_dict"])
if s_index + 1 < length(tuple)
return (tuple[1:s_index-1]..., mc["validation_dict"][tuple[s_index:s_index+1]]..., tuple[s_index+2:end]...)
else
return (tuple[1:s_index-1]..., mc["validation_dict"][tuple[s_index:s_index+1]]...)
end
else
return tuple
end
end
"""
validate_tuple(mc::OrderedDict, tuple::Vector{T} where T, s_index::Int)
Helper function used to correct generated index tuples in cases when the start of the optimization horizon is the same for all scenarios.
"""
function validate_tuple(mc::OrderedDict, tuple::Vector{T} where T, s_index::Int)
if !isempty(mc["validation_dict"])
return map(x -> Predicer.validate_tuple(mc, x, s_index), tuple)
else
return tuple
end
end
"""
reserve_nodes(input_data::InputData)
Return nodes which have a reserve. Form: (n).
"""
function reserve_nodes(input_data::InputData) # original name: create_res_nodes_tuple()
reserve_nodes = String[]
if input_data.setup.contains_reserves
markets = input_data.markets
for m in collect(keys(markets))
if markets[m].type == "reserve"
for n in unique(map(y -> y[3], filter(x -> x[2] == markets[m].node, create_group_tuples(input_data))))
if input_data.nodes[n].is_res
push!(reserve_nodes, n)
end
end
end
end
end
return unique(reserve_nodes)
end
"""
reserve_market_directional_tuples(input_data::InputData)
Return tuples identifying each reserve market with its node and directions in each time step and scenario. Form: (r, ng, d, s, t).
!!! note
This function assumes that reserve markets' market type is formatted "reserve" and that the up and down reserve market directions are "res_up" and "res_down".
"""
function reserve_market_directional_tuples(input_data::InputData) # original name: create_res_tuple()
if !input_data.setup.contains_reserves
return NTuple{5, String}[]
else
reserve_market_directional_tuples = NTuple{5, String}[]
markets = input_data.markets
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
input_data_dirs = unique(map(m -> m.direction, collect(values(input_data.markets))))
res_dir = []
for d in input_data_dirs
if d == "up" || d == "res_up"
push!(res_dir, "res_up")
elseif d == "dw" || d == "res_dw" || d == "dn" || d == "res_dn" || d == "down" || d == "res_down"
push!(res_dir, "res_down")
elseif d == "up/down" || d == "up/dw" || d == "up/dn" ||d == "up_down" || d == "up_dw" || d == "up_dn"
push!(res_dir, "res_up")
push!(res_dir, "res_down")
elseif d != "none"
msg = "Invalid reserve direction given: " * d
throw(ErrorException(msg))
end
end
unique!(res_dir)
for m in values(markets)
if m.type == "reserve"
if m.direction in res_dir
for s in scenarios, t in temporals.t
push!(reserve_market_directional_tuples, (m.name, m.node, m.direction, s, t))
end
else
for d in res_dir, s in scenarios, t in temporals.t
push!(reserve_market_directional_tuples, (m.name, m.node, d, s, t))
end
end
end
end
return reserve_market_directional_tuples
end
end
"""
process_topology_tuples(input_data::InputData)
Return tuples identifying each process topology (flow) for each time step and scenario. Form: (p, so, si, s, t).
"""
function process_topology_tuples(input_data::InputData) # original name: create_process_tuple()
process_topology_tuples = NTuple{5, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for p in values(processes)
for s in scenarios
for topo in p.topos
for t in temporals.t
push!(process_topology_tuples, (p.name, topo.source, topo.sink, s, t))
end
end
end
end
return process_topology_tuples
end
"""
previous_process_topology_tuples(input_data::InputData)
Return dict of tuples containing the previous process tuple, used in building ramp constraints.
"""
function previous_process_topology_tuples(input_data::InputData)
pptt = OrderedDict()
process_tuples = process_topology_tuples(input_data)
temporals = input_data.temporals.t
for (i, tup) in enumerate(process_tuples)
if tup[5] != temporals[1]
pptt[tup] = process_tuples[i-1]
end
end
return pptt
end
"""
online_process_tuples(input_data::InputData)
Return tuples for each process with online variables for every time step and scenario. Form: (p, s, t).
"""
function online_process_tuples(input_data::InputData) # original name: create_proc_online_tuple()
if !input_data.setup.contains_online
return NTuple{3, String}[]
else
online_process_tuples = NTuple{3, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for p in values(processes)
if p.is_online
for s in scenarios, t in temporals.t
push!(online_process_tuples, (p.name, s, t))
end
end
end
return online_process_tuples
end
end
"""
function reserve_groups(input_data::InputData)
Build tuples containing the mapping of processes - nodes over each reserve. Form: (dir, res_type, reserve, node, process)
"""
function reserve_groups(input_data::InputData)
if !input_data.setup.contains_reserves
return NTuple{5, String}[]
else
markets = input_data.markets
groups = input_data.groups
reserve_groups = NTuple{5, String}[]
for m in collect(keys(markets))
if markets[m].type == "reserve"
d = markets[m].direction
for p in groups[markets[m].processgroup].members, n in groups[markets[m].node].members
if d == "up/down" || d == "up/dw" || d == "up/dn" ||d == "up_down" || d == "up_dw" || d == "up_dn"
push!(reserve_groups, ("res_up", markets[m].reserve_type, m, n, p))
push!(reserve_groups, ("res_down", markets[m].reserve_type, m, n, p))
elseif d == "dw" || d == "res_dw" || d == "dn" || d == "res_dn" || d == "down" || d == "res_down"
push!(reserve_groups, ("res_down", markets[m].reserve_type, m, n, p))
elseif d == "up" || d == "res_up"
push!(reserve_groups, ("res_up", markets[m].reserve_type, m, n, p))
end
end
end
end
return reserve_groups
end
end
"""
nodegroup_reserves(input_data::InputData)
Return tuples for each nodegroup, scenario and timestep'. Form: (ng, s, t).
"""
function nodegroup_reserves(input_data::InputData)
if !input_data.setup.contains_reserves
return NTuple{3, String}[]
else
res_nodegroups = NTuple{3, String}[]
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
markets = input_data.markets
for res_m in unique(map(x -> x[3], reserve_groups(input_data)))
for s in scenarios, t in temporals.t
push!(res_nodegroups, (markets[res_m].node, s, t))
end
end
return unique(res_nodegroups)
end
end
"""
node_reserves(input_data::InputData)
Return tuples for each node, scenario and timestep'. Form: (n, s, t).
"""
function node_reserves(input_data::InputData)
if !input_data.setup.contains_reserves
return NTuple{3, String}[]
else
res_nodes = NTuple{3, String}[]
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for n in reserve_nodes(input_data)
for s in scenarios, t in temporals.t
push!(res_nodes, (n, s, t))
end
end
return unique(res_nodes)
end
end
"""
producer_reserve_process_tuples(input_data::InputData)
Return tuples containing information on 'producer' process topologies with reserve potential for every time step and scenario. Form: (d, rt, p, so, si, s, t).
"""
function producer_reserve_process_tuples(input_data::InputData) # original name: create_res_pot_prod_tuple()
if !input_data.setup.contains_reserves
return NTuple{7, String}[]
else
res_nodes = reserve_nodes(input_data)
res_process_tuples = reserve_process_tuples(input_data)
producer_reserve_process_tuples = filter(x -> x[5] in res_nodes, res_process_tuples)
return producer_reserve_process_tuples
end
end
"""
consumer_reserve_process_tuples(input_data::InputData)
Return tuples containing information on 'consumer' process topologies with reserve potential for every time step and scenario. Form: (d, rt, p, so, si, s, t).
"""
function consumer_reserve_process_tuples(input_data::InputData) # original name: create_res_pot_cons_tuple()
if !input_data.setup.contains_reserves
return NTuple{7, String}[]
else
res_nodes = reserve_nodes(input_data)
res_process_tuples = reserve_process_tuples(input_data)
consumer_reserve_process_tuples = filter(x -> x[4] in res_nodes, res_process_tuples)
return consumer_reserve_process_tuples
end
end
"""
reserve_process_tuples(input_data::InputData)
Return tuples containing information on process topologies with reserve potential for every time step and scenario. Form: (d, rt, p, so, si, s, t).
!!! note
This function assumes that the up and down reserve market directions are "res_up" and "res_down".
"""
function reserve_process_tuples(input_data::InputData) # original name: create_res_potential_tuple(), duplicate existed: create_proc_potential_tuple()
if !input_data.setup.contains_reserves
return NTuple{7, String}[]
else
reserve_process_tuples = NTuple{7, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
res_groups = reserve_groups(input_data)
for p in collect(keys(processes))
if processes[p].is_res
res_cons = filter(x -> x[5] == p, res_groups)
for rc in res_cons
for topo in processes[p].topos
if (topo.source == rc[4]|| topo.sink == rc[4])
for s in scenarios, t in temporals.t
push!(reserve_process_tuples, (rc[1], rc[2], p, topo.source, topo.sink, s, t))
end
end
end
end
end
end
return unique(reserve_process_tuples)
end
end
"""
state_node_tuples(input_data::InputData)
Return tuples for each node with a state (storage) for every time step and scenario. Form: (n, s, t).
"""
function state_node_tuples(input_data::InputData) # original name: create_node_state_tuple()
state_node_tuples = NTuple{3, String}[]
if input_data.setup.contains_states
nodes = input_data.nodes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for n in values(nodes)
if n.is_state
for s in scenarios, t in temporals.t
push!(state_node_tuples, (n.name, s, t))
end
end
end
end
return state_node_tuples
end
"""
balance_node_tuples(input_data::InputData)
Return tuples for each node over which balance should be maintained for every time step and scenario. Form: (n s, t).
"""
function balance_node_tuples(input_data::InputData) # original name: create_node_balance_tuple()
balance_node_tuples = NTuple{3, String}[]
nodes = input_data.nodes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for n in values(nodes)
if !(n.is_commodity) & !(n.is_market)
for s in scenarios, t in temporals.t
push!(balance_node_tuples, (n.name, s, t))
end
end
end
return balance_node_tuples
end
"""
previous_balance_node_tuples(input_data::InputData)
Function to gather the node balance tuple for the previous timestep. Returns a Dict() with the node_bal_tup as key and the previous tup as value.
"""
function previous_balance_node_tuples(input_data::InputData)
pbnt = OrderedDict()
node_bal_tups = balance_node_tuples(input_data)
for (i, n) in enumerate(node_bal_tups)
if n[3] != input_data.temporals.t[1]
pbnt[n] = node_bal_tups[i-1]
end
end
return pbnt
end
"""
balance_process_tuples(input_data::InputData)
Return tuples for each process over which balance is to be maintained for every time step and scenario. Form: (p, s, t).
"""
function balance_process_tuples(input_data::InputData) # orignal name: create_proc_balance_tuple()
balance_process_tuples = NTuple{3, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for p in values(processes)
if p.conversion == 1 && !p.is_cf
if isempty(p.eff_fun)
for s in scenarios, t in temporals.t
push!(balance_process_tuples, (p.name, s, t))
end
end
end
end
return balance_process_tuples
end
"""
operative_slot_process_tuples(input_data::InputData)
Return tuples identifying processes with piecewise efficiency for each of their operative slots (o), and every time step and scenario. Form: (p, s, t, o).
"""
function operative_slot_process_tuples(input_data::InputData) # original name: create_proc_op_balance_tuple()
if !input_data.setup.contains_piecewise_eff
return NTuple{4, String}[]
else
operative_slot_process_tuples = NTuple{4, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for p in values(processes)
if p.conversion == 1 && !p.is_cf
if !isempty(p.eff_fun)
for s in scenarios, t in temporals.t, o in p.eff_ops
push!(operative_slot_process_tuples, (p.name, s, t, o))
end
end
end
end
return operative_slot_process_tuples
end
end
"""
piecewise_efficiency_process_tuples(input_data::InputData)
Return tuples identifying processes with piecewise efficiency for each time step and scenario. Form: (p, s, t).
"""
function piecewise_efficiency_process_tuples(input_data::InputData) # original name: create_proc_op_tuple()
if !input_data.setup.contains_piecewise_eff
return NTuple{3, String}[]
else
piecewise_efficiency_process_tuples = NTuple{3, String}[]
processes = input_data.processes
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for p in values(processes)
if p.conversion == 1 && !p.is_cf
if !isempty(p.eff_fun)
for s in scenarios, t in temporals.t
push!(piecewise_efficiency_process_tuples, (p.name, s, t))
end
end
end
end
return piecewise_efficiency_process_tuples
end
end
"""
cf_process_topology_tuples(input_data::InputData)
Return tuples identifying process topologies with a capacity factor for every time step and scenario. Form: (p, so, si, s, t).
"""
function cf_process_topology_tuples(input_data::InputData) # original name: create_cf_balance_tuple()
cf_process_topology_tuples = NTuple{5, String}[]
processes = input_data.processes
process_tuples = process_topology_tuples(input_data)
for p in values(processes)
if p.is_cf
push!(cf_process_topology_tuples, filter(x -> (x[1] == p.name), process_tuples)...)
end
end
return cf_process_topology_tuples
end
"""
fixed_limit_process_topology_tuples(input_data::InputData)
Return tuples containing information on process topologies with fixed limit on flow capacity. Form: (p, so, si, s, t).
"""
function fixed_limit_process_topology_tuples( input_data::InputData) # original name: create_lim_tuple()
fixed_limit_process_topology_tuples = NTuple{5, String}[]
processes = input_data.processes
process_tuples = process_topology_tuples(input_data)
res_nodes = reserve_nodes(input_data)
for p in values(processes)
if !p.is_cf && (p.conversion == 1)
push!(fixed_limit_process_topology_tuples, filter(x -> x[1] == p.name, process_tuples)...)
end
end
return fixed_limit_process_topology_tuples
end
"""
transport_process_topology_tuples(input_data::InputData)
Return tuples identifying transport process topologies for each time step and scenario. Form: (p, so, si, s, t).
"""
function transport_process_topology_tuples(input_data::InputData) # original name. create_trans_tuple()
transport_process_topology_tuples = NTuple{5, String}[]
processes = input_data.processes
process_tuples = process_topology_tuples(input_data)
for p in values(processes)
if !p.is_cf && p.conversion == 2
push!(transport_process_topology_tuples, filter(x -> x[1] == p.name, process_tuples)...)
end
end
return transport_process_topology_tuples
end
"""
reserve_nodegroup_tuples(input_data::InputData)
Return tuples for each nodegroup with reserves for each relevant reserve type, all time steps and scenarios. Form: (ng, rt, s, t).
"""
function reserve_nodegroup_tuples(input_data::InputData) # original name: create_res_eq_tuple()
if !input_data.setup.contains_reserves
return NTuple{4, String}[]
else
reserve_node_tuples = NTuple{4, String}[]
res_nodegroup = nodegroup_reserves(input_data)
res_typ = collect(keys(input_data.reserve_type))
for ng_tup in res_nodegroup, rt in res_typ
push!(reserve_node_tuples, (ng_tup[1], rt, ng_tup[2], ng_tup[3]))
end
return reserve_node_tuples
end
end
"""
up_down_reserve_market_tuples(input_data::InputData)
Return tuples for each reserve market with an 'up_down' direction for all time steps and scenarios. Form: (r, s, t).
!!! note
This function assumes that reserve markets with up and down reserve have market direction "up_down".
"""
function up_down_reserve_market_tuples(input_data::InputData) # original name: create_res_eq_updn_tuple()
if !input_data.setup.contains_reserves
return NTuple{3, String}[]
else
up_down_reserve_market_tuples = NTuple{3, String}[]
markets = input_data.markets
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
res_ms = unique(map(x -> x[1], reserve_market_tuples(input_data)))
for rm in res_ms
d = markets[rm].direction
if d == "up/down" || d == "up/dw" || d == "up/dn" ||d == "up_down" || d == "up_dw" || d == "up_dn"
for s in scenarios, t in temporals.t
push!(up_down_reserve_market_tuples, (rm, s, t))
end
end
end
return up_down_reserve_market_tuples
end
end
"""
reserve_market_tuples(input_data::InputData)
Return tuples for each reserve market for every time step and scenario. Form: (r, s, t).
!!! note
This function assumes that reserve markets' market type is formatted "reserve".
"""
function reserve_market_tuples(input_data::InputData) # orignal name: create_res_final_tuple()
if !input_data.setup.contains_reserves
return NTuple{3, String}[]
else
reserve_market_tuples = NTuple{3, String}[]
markets = input_data.markets
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for m in values(markets)
if m.type == "reserve"
for s in scenarios, t in temporals.t
push!(reserve_market_tuples, (m.name, s, t))
end
end
end
return reserve_market_tuples
end
end
"""
fixed_market_tuples(input_data::InputData)
Return tuples containing time steps for energy markets when the market state is fixed in each scenario. Form: (m, s, t).
!!! note
This function assumes that energy markets' market type is formatted "energy".
"""
function fixed_market_tuples(input_data::InputData) # original name: create_fixed_value_tuple()
fixed_market_tuples = NTuple{3, String}[]
markets = input_data.markets
scenarios = collect(keys(input_data.scenarios))
for m in values(markets)
if !isempty(m.fixed) && m.type == "energy"
temps = map(x->x[1], m.fixed)
for s in scenarios, t in temps
push!(fixed_market_tuples, (m.name, s, t))
end
end
end
return fixed_market_tuples
end
"""
process_topology_ramp_times_tuples(input_data::InputData)
Return tuples containing time steps with ramp possibility for each process topology and scenario. Form: (p, so, si, s, t).
"""
function process_topology_ramp_times_tuples(input_data::InputData) # orignal name: create_ramp_tuple()
ramp_times_process_topology_tuple = NTuple{5, String}[]
processes = input_data.processes
process_tuples = process_topology_tuples(input_data)
for (name, source, sink, s, t) in process_tuples
if processes[name].conversion == 1 && !processes[name].is_cf
push!(ramp_times_process_topology_tuple, (name, source, sink, s, t))
end
end
return ramp_times_process_topology_tuple
end
"""
scenarios(input_data::InputData)
Return scenarios. Form: (s).
"""
function scenarios(input_data::InputData) # original name: create_risk_tuple()
scenarios = collect(keys(input_data.scenarios))
return scenarios
end
"""
create_balance_market_tuple((input_data::Predicer.InputData)
Returns array of tuples containing balance market. Form: (m, dir, s, t).
"""
function create_balance_market_tuple(input_data::Predicer.InputData)
bal_tuples = NTuple{4, String}[]
markets = input_data.markets
dir = ["up","dw"]
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for m in keys(markets)
if markets[m].type == "energy" && markets[m].is_bid == true
for d in dir, s in scenarios, t in temporals.t
push!(bal_tuples, (markets[m].name, d, s, t))
end
end
end
return bal_tuples
end
"""
create_market_tuple(input_data::Predicer.InputData)
Returns array containing information on the defined markets. Form (market, type, node/nodegroup, processgroup)
"""
function create_market_tuple(input_data::Predicer.InputData)
mnt = []
for k in collect(keys(input_data.markets))
m = input_data.markets[k]
push!(mnt, (k, m.type, m.node, m.processgroup))
end
return mnt
end
"""
state_reserves(input_data::InputData)
Returns reserve potentials of processes connected to states with a reserve.
form: (sto_node, res_dir, res_type, p, so, si, s, t)
"""
function state_reserves(input_data::InputData)
state_reserves = NTuple{8, String}[]
if input_data.setup.contains_reserves && input_data.setup.contains_states
processes = input_data.processes
nodes = input_data.nodes
res_nodes_tuple = reserve_nodes(input_data)
res_potential_tuple = reserve_process_tuples(input_data)
process_tuple = process_topology_tuples(input_data)
for n in res_nodes_tuple
res_node_in_processes = unique(map(x -> (x[3], x[4], x[5]), filter(tup -> tup[5] == n, res_potential_tuple)))
res_node_out_processes = unique(map(x -> (x[3], x[4], x[5]), filter(tup -> tup[4] == n, res_potential_tuple)))
for p_in in res_node_in_processes, p_out in res_node_out_processes
# Get topos for p_in and p_out. Create tuple from the values
p_in_topos = map(topo -> (p_in[1], topo.source, topo.sink), processes[p_in[1]].topos)
p_out_topos = map(topo -> (p_out[1], topo.source, topo.sink), processes[p_out[1]].topos)
# Get the TOPOS not going into the reserve node
not_res_topos_p_in = filter(x -> !(x in res_node_in_processes), p_in_topos)
not_res_topos_p_out = filter(x -> !(x in res_node_out_processes), p_out_topos)
# The length of these topos should be 1.
if length(not_res_topos_p_in)==1 && length(not_res_topos_p_out)==1
# Check that one of their source/sink is the same.
if (not_res_topos_p_in[1][2] == not_res_topos_p_out[1][3])
s_node = not_res_topos_p_in[1][2]
if nodes[s_node].is_state
s_node_ps = unique(map(x -> x[1], filter(tup -> (tup[3] == s_node || tup[2] == s_node), process_tuple)))
if length(s_node_ps) == 2# if extra node only has 2 processes
append!(state_reserves, map(x -> (s_node, x...), filter(tup -> tup[3] == p_in[1], res_potential_tuple)))
append!(state_reserves, map(x -> (s_node, x...), filter(tup -> tup[3] == p_out[1], res_potential_tuple)))
end
end
end
end
end
end
end
return state_reserves
end
"""
create_reserve_limits(input_data::InputData)
Returns limited reserve markets.
form: (market, s, t)
"""
function create_reserve_limits(input_data::InputData)
reserve_limits = NTuple{3, String}[]
if input_data.setup.contains_reserves
markets = input_data.markets
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals
for m in keys(markets)
if markets[m].type == "reserve" && markets[m].is_limited
for s in scenarios, t in temporals.t
push!(reserve_limits,(markets[m].name,s,t))
end
end
end
end
return reserve_limits
end
"""
setpoint_tuples(input_data::InputData)
Function to create tuples for general constraints with setpoints. Form (c, s, t), where
c is the name of the general constraint.
"""
function setpoint_tuples(input_data::InputData)
setpoint_tuples = NTuple{3, String}[]
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals.t
for c in collect(keys(input_data.gen_constraints))
if input_data.gen_constraints[c].is_setpoint
for s in scenarios, t in temporals
push!(setpoint_tuples, (c, s, t))
end
end
end
return setpoint_tuples
end
"""
block_tuples(input_data::InputData)
Function to create tuples for inflow blocks. Form (blockname, node, s, t).
"""
function block_tuples(input_data::InputData)
blocks = input_data.inflow_blocks
block_tuples = NTuple{4, String}[]
for b in collect(keys(blocks))
for t_series in blocks[b].data.ts_data
for t in t_series.series
push!(block_tuples, (b, blocks[b].node, t_series.scenario, t[1]))
end
end
end
return block_tuples
end
"""
create_group_tuples(input_data::InputData)
Function to create tuples for groups and their members. Form (group_type, groupname, member_name)
"""
function create_group_tuples(input_data::InputData)
groups = input_data.groups
group_tuples = NTuple{3, String}[]
for gn in collect(keys(groups))
for gm in groups[gn].members
push!(group_tuples, (groups[gn].type, gn, gm))
end
end
return group_tuples
end
"""
node_diffusion_tuple(input_data::InputData)
Function to create tuples for "source" nodes with a diffusion functionality. Form (n, s, t)
"""
function node_diffusion_tuple(input_data::InputData)
node_diffusion_tup = NTuple{3, String}[]
if input_data.setup.contains_diffusion
scenarios = collect(keys(input_data.scenarios))
temporals = input_data.temporals.t
nodes = diffusion_nodes(input_data)
for n in nodes, s in scenarios, t in temporals
push!(node_diffusion_tup, (n, s, t))
end
end
return node_diffusion_tup
end
"""
node_delay_tuple(input_data::InputData)
Function to create tuples for node delay functionality. Form (node1, node2, scenario, t_at_node1, t_at_node2)
"""
function node_delay_tuple(input_data::InputData)
node_delay_tup = NTuple{5, String}[]
if input_data.setup.contains_delay && !input_data.temporals.is_variable_dt # ensure the dt length is constant. Need to change in the future if it isn't...
for tup in input_data.node_delay
n1 = tup[1]
n2 = tup[2]
delay = tup[3]
l_t = length(input_data.temporals.t)
for (i, t) in enumerate(input_data.temporals.t[begin:end])
if (l_t - i) <= delay
t2 = ZonedDateTime(t, input_data.temporals.ts_format) + TimeZones.Hour(delay) * input_data.temporals.dtf
else
t2 = input_data.temporals.t[i+delay]
end
for s in scenarios(input_data)
push!(node_delay_tup, (n1, n2, s, string(t), string(t2)))
end
end
end
end
return node_delay_tup
end
"""
diffusion_nodes(input_data::InputData)
Function to obtain the nodes that are part of a diffusion relation. form (n)
"""
function diffusion_nodes(input_data::InputData)
if input_data.setup.contains_diffusion
return unique(vcat(map(x -> x.node1, input_data.node_diffusion), map(y -> y.node2, input_data.node_diffusion)))
else
return String[]
end
end
"""
delay_nodes(input_data::InputData)
Function to obtain the nodes that are part of a delay relation. form (n)
"""
function delay_nodes(input_data::InputData)
if input_data.setup.contains_delay
return unique(vcat(map(x -> x[1], input_data.node_delay), map(x -> x[2], input_data.node_delay)))
else
return String[]
end
end
"""
bid_slot_tuples(input_data::InputData)
Function to create bid slot tuples. Form (m,slot,t)
"""
function bid_slot_tuples(input_data::InputData)
b_slots = input_data.bid_slots
bid_slot_tup = NTuple{3, String}[]
markets = keys(b_slots)
for m in markets
for s in b_slots[m].slots
for t in b_slots[m].time_steps
push!(bid_slot_tup,(m,s,t))
end
end
end
return bid_slot_tup
end
"""
bid_scenario_tuples(input_data::InputData)
Function to create bid scenario tuples linked to bid slots. Form (m,s,t)
"""
function bid_scenario_tuples(input_data::InputData)
b_slots = input_data.bid_slots
bid_scen_tup = NTuple{3, String}[]
markets = keys(b_slots)
scenarios = collect(keys(input_data.scenarios))
for m in markets
for s in scenarios
for t in b_slots[m].time_steps
push!(bid_scen_tup,(m,s,t))
end
end
end
return bid_scen_tup
end
|
#include <SFML/Graphics.hpp>
#include <iostream>
#include <ctime>
using namespace std;
void handleBallCollision(sf::CircleShape ball, sf::RectangleShape paddle);
const int WINDOW_WIDTH = 1200;
const int WINDOW_HEIGHT = 800;
const int PADDLE_HEIGHT = 200;
const int PADDLE_WIDTH = 20;
const float PADDLE_SPEED = 0.4f;
const float BALL_SPEED = 0.4f;
const int BALL_RADIUS = 10;
int main() {
sf::RenderWindow window(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "Pong!");
sf::RectangleShape playerPaddle(sf::Vector2f((float) PADDLE_WIDTH, (float) PADDLE_HEIGHT));
playerPaddle.setFillColor(sf::Color::White);
playerPaddle.setPosition(0, 0);
sf::RectangleShape cpuPaddle(sf::Vector2f((float) PADDLE_WIDTH, (float) PADDLE_HEIGHT));
cpuPaddle.setFillColor(sf::Color::White);
cpuPaddle.setPosition(WINDOW_WIDTH - PADDLE_WIDTH, 0);
sf::CircleShape ball((float) BALL_RADIUS);
ball.setFillColor(sf::Color::Blue);
ball.setPosition(WINDOW_WIDTH / 2.0, WINDOW_HEIGHT/ 2.0);
float velocity_x = BALL_SPEED;
float velocity_y = 0.f;
sf::Clock clock;
sf::Time timer;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down) && playerPaddle.getPosition().y <= WINDOW_HEIGHT - PADDLE_HEIGHT) {
playerPaddle.move(0.f, PADDLE_SPEED);
//cout << "y: " << playerPaddle.getPosition().y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && playerPaddle.getPosition().y >= 0.f) {
playerPaddle.move(0.f, -PADDLE_SPEED);
}
if (ball.getPosition().x >= WINDOW_WIDTH) {
velocity_x = -BALL_SPEED;
}
else if (ball.getPosition().x <= 0.f) {
velocity_x = BALL_SPEED;
//handleBallCollision(velocity_x, velocity_y, ball, playerPaddle);
}
ball.move(velocity_x, velocity_y);
window.clear(sf::Color::Black);
window.draw(playerPaddle);
window.draw(cpuPaddle);
window.draw(ball);
window.display();
}
}
void handleBallCollision(float &velocity_x, float &velocity_y, sf::CircleShape ball, sf::RectangleShape paddle) {
sf::Vector2f ballPosition = ball.getPosition();
float ball_x = ballPosition.x;
float ball_y = ballPosition.y;
sf::Vector2f paddlePosition = paddle.getPosition();
float paddle_x = paddlePosition.x;
float paddle_y = paddlePosition.y;
if (ball_y >= paddle_y && ball_y <= paddle_y + (float) PADDLE_HEIGHT) {
cout << "Good" << endl;
}
else {
cout << "Miss" << endl;
}
}
|
import argparse
import pandas as pd
import numpy as np
import torch
import os
from models import GraphConvolution, GraphConvolutionalEncoder, GRACE, learner
from utils import setup_config_args, fix_seed, get_logger, get_activation, save_np, save_heatmap, make_route, get_device
from functionals import symmetric_normalization, normalization, similarity_matrix, ssm_fusion, concatenate_fusion
def get_dataset(args):
# csv data to pandas dataframe
data = pd.read_csv(args.data_load_path)
# get certain attributes
label = torch.from_numpy(data.loc[:, 'Label'].to_numpy()).to(torch.long)
audio = torch.from_numpy(
data.loc[:, 'audio_feature1':'audio_feature' + str(args.n_audio_features)].to_numpy()).to(
torch.torch.float32)
text = torch.from_numpy(data.loc[:, 'text_feature1':].to_numpy()).to(
torch.torch.float32)
# convert nan values to zero
audio = torch.where(torch.isnan(audio), torch.zeros_like(audio), audio)
text = torch.where(torch.isnan(text), torch.zeros_like(text), text)
label = torch.where(torch.isnan(label), torch.zeros_like(label), label)
return label, audio, text
def generate_random_unique_indices(n_rows, row_size, max_val):
"""Generates a tensor of shape (n_rows, row_size) with unique values in each row."""
tensor = torch.empty(n_rows, row_size, dtype=torch.long)
for i in range(n_rows):
tensor[i] = torch.randperm(max_val)[:row_size]
return tensor
def main(args):
# Fix random seed
fix_seed(args.seed)
# Get stream and file logger
file_name = args.dataset+'.log'
make_route(args.log_save_path, args.dataset+'.log')
filepath = os.path.join(args.log_save_path, file_name)
log = get_logger(filepath=filepath)
log.info(args)
# select CUDA or CPU
device = get_device(args.cuda_id)
log.info(f'Using device: {device}')
label, audio, text = get_dataset(args)
log.info(f'Label shape : {label.shape}')
log.info(f'Label type : {label.dtype}')
log.info(f'Audio shape : {audio.shape}')
log.info(f'Audio type : {audio.dtype}')
log.info(f'Text shape : {text.shape}')
log.info(f'Text type : {text.dtype}')
# randomly select subjects to be tested based on the number of folds -> 6 out of 24 subjects when 4 folds
# Generate random indices with replacement (might contain duplicates within rows)
# Note: This approach does not guarantee uniqueness within each draw
n_subjects_by_fold = args.n_subjects // args.n_folds
# Generate the tensor
random_unique_indices = generate_random_unique_indices(args.n_times_draw, n_subjects_by_fold, args.n_subjects)
log.info("---------------- Subject-independent experiments - number of subjects: {}, number of folds: {}, number of iterations: {} --------------".format(
int(args.n_subjects), args.n_folds, args.n_times_draw))
log.info(f'Random unique indices : {random_unique_indices}')
im = torch.eye(args.n_samples, dtype=torch.float32)
"""
We conduct subject-independent experiments 30 times for reliability.
In each experiment, we test performances based on 4-fold cross validation due to the lack of data
"""
total_avg_list, total_std_list, total_cfm_list, total_f1_micro_list, total_f1_macro_list = np.array([]), np.array([]), np.array([]), np.array([]), np.array([])
date = '240321'
for j in range(args.n_times_draw):
best_acc_list, cfm_list, f1_micro_list, f1_macro_list = np.array([]), np.array([]), np.array([]), np.array([])
for i in range(args.n_folds):
log.info("******************* TEST fold 3:1 / Fold {} *********************".format(i + 1))
fold_idx = 'fold_' + str(i + 1)
audio = normalization(audio, axis=0, ntype='standardization')
text = normalization(text, axis=0, ntype='standardization')
log.info("similarity matrix construction start...")
asm = similarity_matrix(audio, scale=0.9)
sasm = (asm + asm.T) / 2
nsasm = symmetric_normalization(sasm, im)
tsm = similarity_matrix(text, scale=0.9)
stsm = (tsm + tsm.T) / 2
nstsm = symmetric_normalization(stsm, im)
fsm = ssm_fusion(asm, nsasm, tsm, nstsm, args.k_neighbor, args.timestep)
log.info("similarity matrix construction Done...")
make_route(args.structure_save_path)
save_heatmap(asm, "Audio Similarity Matrix", "Samples", "Samples",
args.structure_save_path + 'asm_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
save_heatmap(nsasm, "Normalized Symmetric Audio Similarity Matrix", "Samples", "Samples",
args.structure_save_path + 'nsasm_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
save_heatmap(tsm, "Text Similarity Matrix", "Samples", "Samples",
args.structure_save_path + 'tsm_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
save_heatmap(nstsm, "Normalized Symmetric Text Similarity Matrix", "Samples", "Samples",
args.structure_save_path + 'nstsm_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
save_heatmap(fsm, "Fused Symmetric Similarity Matrix", "Samples", "Samples",
args.structure_save_path + '/fsm_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
log.info(f"graph structures are saved to {args.structure_save_path}")
ffm = concatenate_fusion(audio, text)
make_route(args.feature_save_path)
save_heatmap(ffm, "Fused Input Features", "Feature dimensions", "Samples",
args.feature_save_path + '/fused_feature_' + fold_idx + '_' + date + '.png', clim_min=None, clim_max=None,
_dpi=300, _facecolor="#eeeeee", _bbox_inches='tight')
adj = fsm.to(device)
feature = ffm.to(device)
label = label.to(device)
log.info(f"graph node features are saved to {args.feature_save_path}")
identifier = torch.ones(args.n_subjects, args.n_trials).bool()
identifier[random_unique_indices[j]] = False
identifier = identifier.reshape(-1)
train_identifier = identifier.squeeze().to(device)
test_identifier = ~train_identifier
activation = get_activation('celu')
gcn = GraphConvolution
encoder = GraphConvolutionalEncoder(args.n_features, args.gcn_hid_channels, args.gcn_out_channels, activation,
base_model=gcn).to(device)
model = GRACE(encoder, args.n_features, args.gcn_out_channels, args.proj_hid_channels, args.out_channels,
args.ptau).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate, weight_decay=args.weight_decay)
model_id = 'iteration'+str(j+1)+'-fold'+str(i+1)
make_route(args.model_save_path)
best_acc, best_z, cfm, f1_micro, f1_macro, out_trigger, best_epoch = learner(model_id, model, optimizer, feature, adj, label,
train_identifier, test_identifier,
args, isdeap=False, verbose=False, earlystop=False)
if out_trigger == 0:
log.info('model id: {}, Epoch : {} - Find best epoch'.format(model_id, best_epoch))
elif out_trigger == 1:
log.info('model id: {}, Epoch : {} - Accuracy - 100.%'.format(model_id, best_epoch))
elif out_trigger == 2:
log.info('model id: {}, Epoch : {} - Early Stopping'.format(model_id, best_epoch))
else:
log.error('unidentifiable model save trigger')
model_save_file = args.model_save_path+'subject_independent_'+model_id+'.pt'
torch.save(model.state_dict(), model_save_file)
make_route(args.tensor_save_path)
#save_np(args.tensor_save_path, 'confusion_matrix_' + fold_idx, cfm)
log.info("*** Best ACC : {} ***".format(round(best_acc.item(), 2)))
best_acc_list = np.append(best_acc_list, best_acc.item())
cfm_list = np.concatenate([cfm_list, cfm[np.newaxis]]) if cfm_list.size else cfm[np.newaxis]
f1_micro_list = np.append(f1_micro_list, f1_micro.item())
f1_macro_list = np.append(f1_macro_list, f1_macro.item())
avg = np.mean(best_acc_list)
std = np.std(best_acc_list)
log.info(f"**************** Best and Average acc of 24 folds by subject in iteration {j+1}*********************")
log.info("** Best ACC : {}, Avearge acc : {}, std : {} **\n".format(np.round(np.max(best_acc_list), 2),
np.round(avg, 2),
np.round(std, 2)))
total_avg_list = np.append(total_avg_list, avg)
total_std_list = np.append(total_std_list, avg)
total_cfm_list = np.concatenate([total_cfm_list, np.mean(cfm_list, axis=0, keepdims=True)]) if total_cfm_list.size else np.mean(cfm_list, axis=0, keepdims=True)
total_f1_micro_list = np.append(total_f1_micro_list, np.mean(f1_micro_list))
total_f1_macro_list = np.append(total_f1_macro_list, np.mean(f1_macro_list))
log.info(f" The average accuracy, standard deviation, f1_score(micro), f1_score(macro) : {np.mean(total_avg_list)}, {np.mean(total_std_list)}, {np.mean(total_f1_micro_list)}, {np.mean(total_f1_macro_list)}")
save_np(args.tensor_save_path, 'subject_independent_n_folds_' + str(args.n_folds) + '_total_avg_list_' + date +'_'+ args.dataset, total_avg_list)
save_np(args.tensor_save_path, 'subject_independent_n_folds_' + str(args.n_folds) + '_total_std_list_' + date, total_std_list)
save_np(args.tensor_save_path, 'subject_independent_n_folds_' + str(args.n_folds) + '_average_confusion_matrix_' + date, np.mean(total_cfm_list, axis=0))
save_np(args.tensor_save_path, 'subject_independent_n_folds_' + str(args.n_folds) + '_total_f1_micro_list_' + date, total_f1_micro_list)
save_np(args.tensor_save_path, 'subject_independent_n_folds_' + str(args.n_folds) + '_total_f1_macro_list_' + date, total_f1_macro_list)
log.info(f"{np.mean(total_cfm_list, axis=0)}")
return
if __name__ == "__main__":
# Load config from YAML file and Setup argparse with the config
parser = argparse.ArgumentParser(description='Arguments set from prompt and YAML configuration.')
parser.add_argument('--dataset', type=str, default='IITP-SMED', help='dataset (default: IITP-SMED)')
parser.add_argument('--cuda_id', type=str, default='0', help='Cuda device ID (default: 0)')
args = setup_config_args(parser, filepath='config.yaml')
main(args)
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Capped.sol";
contract AlchemicaToken is ERC20Capped, Ownable {
//@todo: auto-approve installationDiamond to spend
/*
* EIP-2612 states
*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
constructor(
string memory name,
string memory symbol,
uint256 _maxSupply,
address _realmDiamond
) ERC20(name, symbol) ERC20Capped(_maxSupply) {
transferOwnership(_realmDiamond);
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/// @notice Mint _value tokens for msg.sender
/// @param _value Amount of tokens to mint
function mint(address _to, uint256 _value) public onlyOwner {
_mint(_to, _value);
}
/*
* EIP-2612 LOGIC
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
_approve(owner, spender, value);
}
}
function DOMAIN_SEPARATOR() public view returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256("1"), // version
block.chainid,
address(this)
)
);
}
}
|
# Test assignment aab
__testcafe and JavaScript__
The environment exists of 2 pages, which I mirrored in testcode:
- login_page.js
- index_page.js
__Login_page__
I combined the log in and log out function on the same page, they are both a authentication-related functionality and belong together. This makes them easy to find and maintain.
Other features that are repeated on several pages or for example more complicated features I would usually give their own page.
The users.js file is copied to tests / data. Instead of using the same data source as the code, I chose to repeat the data so the tests fails when there are changes on the code side. After confirming that changes were made on purpose the test data should be changed.
On the login_page.js I made a login function that takes in the email and password as arguments.
The input field does not clear itself after a login attempt - in my opnion a big issue (escpecially for a bank or any other app with sensitive client information)
There is also a loginAdmin function that finds the user in the users data that contains admin and takes the email and password of this user as arguments for the login().
This way we have an Admin user that can be easily used in tests, but when the data needs changing there is only 1 point of truth.
I created a test for the Login page that logs in, asserts that it lands on the index page, and then logs out. The for loop is placed outside of the test so there is a separate test for all users. When a login fails it is immediately clear which user failed and the tests for the other users are still executed (testcafe does not seem to have soft assertions).
Other tests for the login page simply assert the header and footer text.
__Index_page__
For the index page I made a test that asserts the content text. The decision of whether to check the full text or only a certain part of it depends on the context and can be discussed.
There is also a test for the items in the navigation header. The login is a beforeEach that is moved to the fixture. The test is executed for each item in the navigation. If more items are added to the navigation, they only need to be added to the array of objects.
__Other automation / optimalizations__
I completed the yml testcafe file in the github folder so it can run in github actions.
Locally I use the testfolder as the testdirectory, CI runs from what it considers workspace root. I added a patch in util.js to support both cases.
Running the tests was quite slow, therefor I tried to speed it up a bit by specifying in .testcaferc.js in which folder to look for tests, running the browser headless and use concurrency.
To speed the tests up in the pipeline I added in the yml cache for npm and dependencies in the package-lock.json, headless and concurrency.
Finally, I also incorporated an HTML reporter during the test execution process. This HTML reporter generates a detailed report that includes a timestamp, and is automatically saved as an artifact within the GitHub Actions workflow for easy access and review.
*Thanks for the assignment!*
*Elvira 't Hart*
|
# 0x0F. Python - Object-relational mapping
In the first part, we will use the module MySQLdb to connect to a MySQL database and execute your SQL queries.
In the second part, we will use the module SQLAlchemy, an Object Relational Mapper (ORM).
The biggest difference is: no more SQL queries! Indeed, the purpose of an ORM is to abstract the storage to the usage. With an ORM, our biggest concern will be “What can I do with my objects” and not “How this object is stored? where? when?”. We won’t write any SQL queries only Python code. Last thing, your code won’t be “storage type” dependent. We will be able to change our storage easily without re-writing our entire project.
## 🛠 Skills
- SQLAlchemy
- ORM
- MySQL
- SQL
- OOP
- Python
## Tasks and Description
| Tasks | Description |
| ----------------- | ------------------------------------------------------------------ |
| `0. Get all states` | Write a script that lists all states from the database hbtn_0e_0_usa:... |
| `1. Filter states`| Write a script that lists all states with a name starting with N (upper N) from the database hbtn_0e_0_usa:... |
| `2. Filter states by user input` | Write a script that takes in an argument and displays all values in the states table of hbtn_0e_0_usa where name matches the argument. |
| `3. SQL Injection...` | write a script that takes in arguments and displays all values in the states table of hbtn_0e_0_usa where name matches the argument. But this time, write one that is safe from MySQL injections! |
| `4. Cities by states`| Write a script that lists all cities from the database hbtn_0e_4_usa |
| `5. All cities by state` | Write a script that takes in the name of a state as an argument and lists all cities of that state, using the database hbtn_0e_4_usa... |
| `6. First state model` | Write a python file that contains the class definition of a State and an instance Base = declarative_base():... |
| `7. All states via SQLAlchemy`| Write a script that lists all State objects from the database hbtn_0e_6_usa |
| `8. First state` | Write a script that prints the first State object from the database hbtn_0e_6_usa |
| `9. Contains a` | Write a script that lists all State objects that contain the letter a from the database hbtn_0e_6_usa |
| `10. Get a state`| Write a script that prints the State object with the name passed as argument from the database hbtn_0e_6_usa |
| `11. Add a new state` | Write a script that adds the State object “Louisiana” to the database hbtn_0e_6_usa |
| `12. Update a state` | Write a script that changes the name of a State object from the database hbtn_0e_6_usa |
| `13. Delete states` | Write a script that deletes all State objects with a name containing the letter a from the database hbtn_0e_6_usa |
| `14. Cities in state`| Write a Python file similar to model_state.py named model_city.py that contains the class definition of a City. |
| `15. City relationship` | Improve the files model_city.py and model_state.py, and save them as relationship_city.py and relationship_state.py:... |
| `16. List relationship` | Write a script that lists all State objects, and corresponding City objects, contained in the database hbtn_0e_101_usa |
| `17. From city`| Write a script that lists all City objects from the database hbtn_0e_101_usa |
## Tech Stack
**VM(s)** Ubuntu 20.0.4, Ubuntu 14.04 - Python 3.4
|
##-----------------------------------------------##
## Author: Maximilian H.K. Hesselbarth ##
## ##
## mhk.hesselbarth@gmail.com ##
## www.github.com/mhesselbarth ##
##-----------------------------------------------##
#### Import packages & functions ####
source("1_Functions/setup.R")
source("1_Functions/create_simulation_pattern.R")
source("1_Functions/create_simulation_species.R")
# set seed
set.seed(42, kind = "L'Ecuyer-CMRG")
RandomFields::RFoptions(install = "no")
#### Create example data ####
# create landscape
simulation_landscape <- NLMR::nlm_fbm(ncol = 50, nrow = 50,
resolution = 20, fract_dim = 1.5,
verbose = FALSE,
cPrintlevel = 0) |>
terra::rast() |>
shar::classify_habitats(classes = 5, style = "fisher")
# create pattern with 4 species
simulation_pattern <- create_simulation_pattern(raster = simulation_landscape,
number_points = 50,
association_strength = 0.35)
# pick species 2 as example
example_species <- spatstat.geom::subset.ppp(simulation_pattern, species_code == 2)
#### Randomize data ####
# fit clustered pattern to data
gamma_test <- shar::fit_point_process(spatstat.geom::unmark(example_species),
n_random = 99, process = "cluster")
pattern_recon <- shar::reconstruct_pattern(spatstat.geom::unmark(example_species),
n_random = 99, max_runs = max_runs,
method = "cluster", no_change = no_change)
#### Save results ####
suppoRt::save_rds(object = gamma_test, filename = "appendix_gamma_test.rds",
path = "3_Data/", overwrite = FALSE)
suppoRt::save_rds(object = pattern_recon, filename = "appendix_pattern_recon.rds",
path = "3_Data/", overwrite = FALSE)
#### Create figures ####
# read data
gamma <- readr::read_rds("3_Data/appendix_gamma_test.rds")
recon <- readr::read_rds("3_Data/appendix_pattern_recon.rds")
# calculate pcf of inital pattern
pcf_observed <- spatstat.explore::pcf.ppp(gamma$observed, divisor = "d", correction = "Ripley",
r = seq(from = 0, to = 250, length.out = 515)) |>
tibble::as_tibble()
# calculate pcf of all gamma model fits
result_gamma <- purrr::map_dfr(gamma$randomized, function(current_pattern) {
tibble::as_tibble(
spatstat.explore::pcf.ppp(current_pattern, divisor = "d", correction = "Ripley",
r = seq(from = 0, to = 250, length.out = 515))
)}, .id = "pattern")
# calculate pcf of all reconstructions
result_recon <- purrr::map_dfr(recon$randomized, function(current_pattern) {
tibble::as_tibble(
spatstat.explore::pcf.ppp(current_pattern, divisor = "d", correction = "Ripley",
r = seq(from = 0, to = 250, length.out = 515))
)}, .id = "pattern")
# combine both methods
result_combn <- dplyr::bind_rows(gamma = result_gamma, recon = result_recon, .id = "method") |>
dplyr::group_by(method, r) |>
dplyr::summarise(lo = quantile(iso, probs = 0.025),
hi = quantile(iso, probs = 0.975), .groups = "drop") |>
dplyr::mutate(method = factor(method, levels = c("gamma", "recon"),
labels = c("gamma" = "gamma-test", "recon" = "Pattern reconstruction")))
# create ggplot
gg_comparison <- ggplot(data = result_combn) +
geom_hline(yintercept = 1, color = "darkgrey", linetype = 2) +
geom_ribbon(aes(x = r, ymin = lo, ymax = hi, fill = method), alpha = 0.5) +
geom_line(data = pcf_observed, aes(x = r, y = iso), col = "black", linewidth = 0.75) +
scale_fill_manual(name = "", values = c("gamma-test" = "#AE0400", "Pattern reconstruction" = "#0085A9")) +
labs(x = expression(paste("Distance ", italic("r"), " in meters [m]")),
y = expression(paste("Pair-correlation function ", italic("g(r)")))) +
theme_classic(base_size = 12) +
theme(legend.position = c(0.8, 0.8))
suppoRt::save_ggplot(plot = gg_comparison, path = "4_Figures/", filename = "Fig-S1.png",
dpi = dpi, width = width, height = height * 1/2, units = units,
overwrite = FALSE)
|
<?php
namespace backend\models;
use Yii;
use yii\db\Expression;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "parliament_constituency".
*
* @property int $id
* @property string $name
* @property int $constituency_type 1. Rajya Sabha 2.Lok Sabha
* @property int $status
* @property string $created_at
* @property string $modified_at
*/
class ParliamentConstituency extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'parliament_constituency';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'constituency_type','state_id'], 'required'],
[['constituency_type', 'status','state_id'], 'integer'],
[['created_at', 'modified_at','sort_order'], 'safe'],
[['name'], 'string', 'max' => 250],
];
}
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'modified_at',
'value' => new Expression('NOW()')
]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'name' => Yii::t('app', 'Name'),
'constituency_type' => Yii::t('app', 'Contituency Type'),
'state.name' => Yii::t('app', 'State'),
'status' => Yii::t('app', 'Status'),
'created_at' => Yii::t('app', 'Created At'),
'modified_at' => Yii::t('app', 'Modified At'),
];
}
public function deleteParliamentConstituency($id)
{
$connection = Yii::$app->db;
$connection->createCommand()->update('parliament_constituency', ['status' => 0], 'id=:id')->bindParam(':id',$id)->execute();
return true;
}
public function getStates()
{
$states = State::find()->where(['status'=> 1])->all();
return $states;
}
public function getState()
{
return $this->hasOne(State::className(), ['id' => 'state_id']);
}
}
|
# --
# OTOBO is a web-based ticketing system for service organisations.
# --
# Copyright (C) 2001-2020 OTRS AG, https://otrs.com/
# Copyright (C) 2019-2021 Rother OSS GmbH, https://otobo.de/
# --
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# --
package Kernel::System::ProcessManagement::TransitionValidation::ValidateDemo;
use strict;
use warnings;
use Kernel::System::VariableCheck qw(:all);
our @ObjectDependencies = (
'Kernel::System::Log',
);
=head1 NAME
Kernel::System::ProcessManagement::TransitionValidation::ValidateDemo - Demo for Transition Validation Module
=head1 DESCRIPTION
All ValidateDemo functions.
=head1 PUBLIC INTERFACE
=head2 new()
Don't use the constructor directly, use the ObjectManager instead:
my $ValidateDemoObject = $Kernel::OM->Get('Kernel::System::ProcessManagement::TransitionValidation::ValidateDemo');
=cut
sub new {
my ( $Type, %Param ) = @_;
# allocate new hash for object
my $Self = {};
bless( $Self, $Type );
return $Self;
}
=head2 Validate()
Validate Data
my $ValidateResult = $ValidateModuleObject->Validate(
Data => {
Queue => 'Raw',
# ...
},
);
Returns:
$ValidateResult = 1; # or undef, only returns 1 if Queue is 'Raw'
);
=cut
sub Validate {
my ( $Self, %Param ) = @_;
for my $Needed (qw(Data)) {
if ( !defined $Param{$Needed} ) {
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Need $Needed!"
);
return;
}
}
# Check if we have Data to check against transitions conditions
if ( !IsHashRefWithData( $Param{Data} ) ) {
$Kernel::OM->Get('Kernel::System::Log')->Log(
Priority => 'error',
Message => "Data has no values!",
);
return;
}
if ( $Param{Data}->{Queue} && $Param{Data}->{Queue} eq 'Raw' ) {
return 1;
}
return;
}
1;
|
script;
use std::{alloc::alloc, hash::*, intrinsics::{size_of, size_of_val}};
struct TestStruct {
boo: bool,
uwu: u64,
}
struct ExtendedTestStruct {
boo: bool,
uwu: u64,
kek: bool,
bur: u64,
}
fn main() -> bool {
// Create a struct
let foo = TestStruct {
boo: true,
uwu: 42,
};
let foo_len = size_of_val(foo);
assert(foo_len == 16);
// Get a pointer to it
let foo_ptr = __addr_of(foo);
assert(foo_ptr == asm(r1: foo) { r1: raw_ptr });
// Get another pointer to it and compare
let foo_ptr_2 = __addr_of(foo);
assert(foo_ptr_2 == foo_ptr);
// Copy the struct into a buffer
let buf_ptr = alloc::<u64>(2);
foo_ptr.copy_to::<u64>(buf_ptr, 2);
assert(asm(r1: buf_ptr, r2: foo_ptr, r3: foo_len, res) {
meq res r1 r2 r3;
res: bool
});
// Read the pointer as a TestStruct
let foo: TestStruct = buf_ptr.read();
assert(foo.boo == true);
assert(foo.uwu == 42);
// Read fields of the struct
let uwu_ptr = buf_ptr.add_uint_offset(8); // struct fields are aligned to words
let uwu: u64 = uwu_ptr.read();
assert(uwu == 42);
let boo_ptr = uwu_ptr.sub_uint_offset(8);
let boo: bool = boo_ptr.read();
assert(boo == true);
// Write values into a buffer
let buf_ptr = alloc::<u64>(2);
buf_ptr.write(true);
buf_ptr.add_uint_offset(8).write(42);
let foo: TestStruct = buf_ptr.read();
assert(foo.boo == true);
assert(foo.uwu == 42);
// Write structs into a buffer
let buf_ptr = alloc::<u64>(4);
buf_ptr.write(foo);
buf_ptr.add::<TestStruct>(1).write(foo);
let bar: ExtendedTestStruct = buf_ptr.read();
assert(bar.boo == true);
assert(bar.uwu == 42);
assert(bar.kek == true);
assert(bar.bur == 42);
// Make sure that reading a memory location into a variable and then
// overriding the same memory location does not change the variable read.
let buf_ptr = alloc::<u64>(1);
let small_string_1 = __to_str_array("fuel");
let small_string_2 = __to_str_array("labs");
buf_ptr.write(small_string_1);
let read_small_string_1 = buf_ptr.read::<str[4]>();
buf_ptr.write(small_string_2);
let read_small_string_2 = buf_ptr.read::<str[4]>();
assert(sha256_str_array(small_string_1) == sha256_str_array(read_small_string_1));
assert(sha256_str_array(small_string_2) == sha256_str_array(read_small_string_2));
let buf_ptr = alloc::<u64>(2);
let large_string_1 = __to_str_array("fuelfuelfuel");
let large_string_2 = __to_str_array("labslabslabs");
buf_ptr.write(large_string_1);
let read_large_string_1 = buf_ptr.read::<str[12]>();
buf_ptr.write(large_string_2);
let read_large_string_2 = buf_ptr.read::<str[12]>();
assert(sha256_str_array(large_string_1) == sha256_str_array(read_large_string_1));
assert(sha256_str_array(large_string_2) == sha256_str_array(read_large_string_2));
true
}
|
import { AfterViewInit, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Subscription } from 'rxjs';
import { SnackBarService } from 'src/app/shared/snackbar.service';
import { SpinnerService } from 'src/app/shared/spinner.service';
import * as DocumentEditor from '@ckeditor/ckeditor5-build-decoupled-document';
import { HttpEvent, HttpEventType } from '@angular/common/http';
import { UploadService } from 'src/app/shared/services/upload.service';
import { HelperService } from 'src/app/shared/helper.service';
import { ActivatedRoute, Router } from '@angular/router';
import { CustomUploadAdapter } from 'src/app/shared/ckeditorImageUploadAdapter';
import { NewsService } from 'src/app/news/news.service';
import { TravelService } from 'src/app/travels/travels.service';
import { FinanceService } from 'src/app/finance/finance.service';
@Component({
selector: 'app-new-finance',
templateUrl: './new-finance.component.html',
styleUrls: ['./new-finance.component.scss'],
})
export class NewFinanceComponent implements OnInit, AfterViewInit, OnDestroy {
subscriptions: Subscription = new Subscription();
featuredImageSrc: string;
editFinanceId: number = null;
financeForm: FormGroup;
showError = false;
errorMessage = '';
progressFeaturedImage: number = 0;
formCustomvalidation = {
featuredImage: {
validated: true,
message: '',
},
};
ckConfig = {
placeholder: 'Content',
};
ckEditor = DocumentEditor;
// convenience getter for easy access to form fields
get f() {
return this.financeForm.controls;
}
constructor(
private route: ActivatedRoute,
private router: Router,
private financeService: FinanceService,
private uploadService: UploadService,
private helperService: HelperService,
private spinnerService: SpinnerService,
private snackbar: SnackBarService,
private cdk: ChangeDetectorRef
) {}
ngOnInit() {
this.initializeForm();
const financeId = this.route.snapshot.paramMap.get('finance_id');
if (financeId != null) {
this.editFinanceId = parseInt(financeId);
this.spinnerService.show();
this.financeService.getSingleFinance(this.editFinanceId).subscribe(
(result: any) => {
this.spinnerService.hide();
const finance = result.data[0];
if (finance) {
this.prepareForm(finance);
if (finance.featured_image) {
this.featuredImageSrc = this.helperService.getImageUrl(finance.featured_image, 'finance', 'thumb');
}
}
},
(error) => {
this.spinnerService.hide();
this.snackbar.openSnackBar(error.error.message, 'Close', 'warn');
}
);
}
}
ngAfterViewInit() {}
onCkeditorReady(editor: DocumentEditor): void {
editor.ui
.getEditableElement()
.parentElement.insertBefore(editor.ui.view.toolbar.element, editor.ui.getEditableElement());
editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
return new CustomUploadAdapter(loader, this.helperService.apiUrl, 'finance', 'upload/image-finance-ckeditor');
};
}
initializeForm() {
this.financeForm = new FormGroup({
title: new FormControl('', Validators.required),
content: new FormControl('', Validators.required),
featured_image: new FormControl('', Validators.required),
meta_title: new FormControl(''),
meta_keywords: new FormControl(''),
meta_desc: new FormControl(''),
});
}
prepareForm(finance: any) {
if (!finance) {
return;
}
this.financeForm.patchValue({
title: finance.title,
content: finance.content,
featured_image: finance.featured_image,
meta_title: finance.meta_title,
meta_keywords: finance.meta_keywords,
meta_desc: finance.meta_desc,
});
}
onAttachmentChange(event) {
// reset validation
this.formCustomvalidation.featuredImage.validated = true;
this.formCustomvalidation.featuredImage.message = '';
if (event.target.files && event.target.files.length) {
const file = event.target.files[0];
// do validation
const res = this.helperService.imageValidation(file);
if (!res.validated) {
this.formCustomvalidation.featuredImage.validated = false;
this.formCustomvalidation.featuredImage.message = res.message;
return;
}
this.featuredImageSrc = URL.createObjectURL(file);
// send image to the server
const fd = new FormData();
fd.append('image', file, file.name);
fd.append('resize', 'yes');
this.uploadService.uploadImage(fd, 'finance').subscribe((result: HttpEvent<any>) => {
switch (result.type) {
case HttpEventType.UploadProgress:
this.progressFeaturedImage = Math.round((result.loaded / result.total) * 100);
break;
case HttpEventType.Response:
// check for validation
if (result.body.data.fileValidationError) {
this.formCustomvalidation.featuredImage.validated = false;
this.formCustomvalidation.featuredImage.message = result.body.data.fileValidationError;
} else {
this.financeForm.get('featured_image').patchValue(result.body.data.filename);
}
// hide progress bar
setTimeout(() => {
this.progressFeaturedImage = 0;
}, 1500);
}
});
}
}
onSubmit() {
if (this.editFinanceId == null) {
this.createFinance();
} else {
this.updateFinance();
}
}
createFinance() {
const formValues = this.financeForm.getRawValue();
this.spinnerService.show();
const newNewsSubscription = this.financeService.addFinance(formValues).subscribe(
(result: any) => {
this.spinnerService.hide();
// console.log(result);
this.router.navigate(['/admin/all-finance']);
this.snackbar.openSnackBar(result.message);
},
(error) => {
this.spinnerService.hide();
this.snackbar.openSnackBar(error.error.message, 'Close', 'warn');
}
);
this.subscriptions.add(newNewsSubscription);
}
updateFinance() {
const formValues = this.financeForm.value;
this.spinnerService.show();
const updateNewsSubscription = this.financeService.updateFinance(this.editFinanceId, formValues).subscribe(
(result: any) => {
this.spinnerService.hide();
// console.log(result);
this.router.navigate(['/admin/all-finance']);
this.snackbar.openSnackBar(result.message);
},
(error) => {
this.spinnerService.hide();
this.snackbar.openSnackBar(error.error.message, 'Close', 'warn');
}
);
this.subscriptions.add(updateNewsSubscription);
}
formatSalarySliderLabel(value: number) {
return Math.round(value / 1000) + 'k';
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
}
}
|
// Solución al reto de PlayGrounds
export async function runCode(url) {
if (url.substring(0, 8) != "https://") throw new Error('Invalid URL'); // Verifico que la url comience con "https://" y uso método ".substring(0,8)"
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
throw new Error('Something was wrong');
}
}
// Solución 2, enviando solicitud con parámetro "options" con atributo "GET"
export async function runCode(url) {
const option = {
method: "GET"
}
if (url.substring(0, 8) != "https://") throw new Error('Invalid URL');
try {
const response = await fetch(url, option);
const data = await response.json();
return data;
} catch (error) {
throw new Error('Something was wrong');
}
}
// Solución 3, verificando "url" usando "new URL(url)"
export async function runCode(url) {
try { // Validar formato correcto url
new URL(url); // Puedo validar que sea una URL al crear un objeto de tipo URL
} catch (e) {
throw new Error('Invalid URL');
}
try { // Validar que exista url
const response = await fetch(url)
return response.json();
} catch (e) {
throw new Error('Something was wrong');
}
}
// Solución 4, usando "url.substring(0, 8) != 'https://'"
export async function runCode(url) {
if (url.substring(0, 8) != "https://") {
throw new Error('Invalid URL');
}
else {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch {
throw new Error('Something was wrong');
}
}
}
// Solución 5, mandando como parámetro Objeto "option"
export async function runCode(url) {
const options = {
method: "GET"
}
try {
new URL(url)
} catch (error) {
throw new Error('Invalid URL');
}
try {
const response = await fetch(url, options);
const data = await response.json()
return data
} catch (error) {
throw new Error('Something was wrong');
}
}
// Solución 6, usando "ReGex" (Regular Expressions) para validar el formato de la URL
export async function runCode(url) {
// Tu código aquí 👈
const options = {
method: 'GET'
};
const reg = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;
if (!url.match(reg)) {
throw new Error("Invalid URL");
}
try {
const response = await fetch(url, options);
const data = await response.json();
return data;
} catch (error) {
throw new Error("Something was wrong");
}
}
|
package com.example.budgetwise
import android.app.Application
import android.content.Context
import androidx.room.Room
import com.example.budgetwise.database.RecordDAO
import com.example.budgetwise.database.RecordDatabase
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
fun provideRecordDAO(recDatabase: RecordDatabase): RecordDAO {
return recDatabase.recordDao()
}
@Provides
@Singleton
fun provideRecordDatabase(@ApplicationContext appContext: Context): RecordDatabase {
return Room.databaseBuilder(
appContext,
RecordDatabase::class.java,
"RecReader"
).build()
}
}
|
#pragma once
#include "core/operator.h"
namespace infini {
/**
* @brief Base class of **binary** element-wise operators.
* Unary operators like activations are not the derived classes of
* ElementWiseObj.
*
*/
class ElementWiseObj : public OperatorObj {
public:
/**
* @brief Construct a new ElementWise object
*
* @param type Operator type.
* @param graph The computation graph that this operator belongs to.
* @param input0 The first input tensor.
* @param input1 The second input tensor.
* @param output The output tensor.
*/
ElementWiseObj(OpType type, GraphObj *graph, Tensor input0, Tensor input1,
Tensor output);
optional<vector<Shape>> inferShape(const TensorVec &inputs) const override;
std::string toString() const override;
int numInputs() const override { return 2; }
int numOutputs() const override { return 1; }
private:
vector<int> getWorkloadVector() const override;
vector<int> getOpAttrVector() const override;
};
class MSELossObj : public OperatorObj {
public:
enum Reduction { None = 0, Sum, Mean };
MSELossObj(GraphObj *graph, Tensor input0, Tensor input1,
Reduction reduction, Tensor output);
OP_CLONE(MSELossObj);
optional<vector<Shape>> inferShape(const TensorVec &inputs) const override;
Reduction getReduction() const { return reductionMode; }
std::string toString() const override;
int numInputs() const override { return 2; }
int numOutputs() const override { return 1; }
private:
Reduction reductionMode;
vector<int> getWorkloadVector() const override;
vector<int> getOpAttrVector() const override;
};
#define DEFINE_ELEMENT_WISE_OBJ(prefix, type) \
class prefix##Obj : public ElementWiseObj { \
public: \
prefix##Obj(GraphObj *graph, Tensor input0, Tensor input1, \
Tensor output) \
: ElementWiseObj(type, graph, input0, input1, output) {} \
OP_CLONE(prefix##Obj); \
};
DEFINE_ELEMENT_WISE_OBJ(Add, OpType::Add)
DEFINE_ELEMENT_WISE_OBJ(Sub, OpType::Sub)
DEFINE_ELEMENT_WISE_OBJ(Mul, OpType::Mul)
DEFINE_ELEMENT_WISE_OBJ(Div, OpType::Div)
DEFINE_ELEMENT_WISE_OBJ(Pow, OpType::Pow)
DEFINE_ELEMENT_WISE_OBJ(Maximum, OpType::Maximum)
DEFINE_ELEMENT_WISE_OBJ(Minimum, OpType::Minimum)
DEFINE_ELEMENT_WISE_OBJ(Power, OpType::Power)
DEFINE_ELEMENT_WISE_OBJ(FloorDiv, OpType::FloorDiv)
DEFINE_ELEMENT_WISE_OBJ(FloorMod, OpType::FloorMod)
DEFINE_ELEMENT_WISE_OBJ(SquaredDifference, OpType::SquaredDifference)
DEFINE_ELEMENT_WISE_OBJ(Equal, OpType::Equal)
DEFINE_ELEMENT_WISE_OBJ(NotEqual, OpType::NotEqual)
DEFINE_ELEMENT_WISE_OBJ(GreaterThan, OpType::GreaterThan)
DEFINE_ELEMENT_WISE_OBJ(GreaterEqual, OpType::GreaterEqual)
DEFINE_ELEMENT_WISE_OBJ(LessThan, OpType::LessThan)
DEFINE_ELEMENT_WISE_OBJ(LessEqual, OpType::LessEqual)
DEFINE_ELEMENT_WISE_OBJ(And, OpType::And)
DEFINE_ELEMENT_WISE_OBJ(Or, OpType::Or)
DEFINE_ELEMENT_WISE_OBJ(Xor, OpType::Xor)
DEFINE_ELEMENT_WISE_OBJ(Not, OpType::Not)
DEFINE_ELEMENT_WISE_OBJ(BitAnd, OpType::BitAnd)
DEFINE_ELEMENT_WISE_OBJ(BitOr, OpType::BitOr)
DEFINE_ELEMENT_WISE_OBJ(BitXor, OpType::BitXor)
DEFINE_ELEMENT_WISE_OBJ(BitNot, OpType::BitNot)
DEFINE_ELEMENT_WISE_OBJ(BitLeftShift, OpType::BitLeftShift)
DEFINE_ELEMENT_WISE_OBJ(BitRightShift, OpType::BitRightShift)
}; // namespace infini
|
/**
* @swagger
* /api/v1/products/categories/{category}:
* get:
* summary: Get products based on category
* description: Retrieve a list of products based on the specified category
* parameters:
* - in: path
* name: category
* required: true
* description: Category name
* schema:
* type: string
* responses:
* 200:
* description: Successful operation
* content:
* application/json:
* schema:
* type: array
* items:
* $ref: '#/components/schemas/Product'
* 500:
* description: Internal server error
*/
// Import necessary dependencies
const express = require('express');
const db = require('../../config');
const getCategoryBasedProducts = require('../../controller/productController/getCategoryBasedProduct');
const router = express.Router();
router.get('/products/categories/:category', getCategoryBasedProducts);
module.exports = router;
|
/*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.google.mlkit.codelab.translate.analyzer
import android.content.Context
import android.graphics.Rect
import android.util.Log
import android.widget.Toast
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.tasks.Task
import com.google.mlkit.common.MlKitException
import com.google.mlkit.codelab.translate.util.ImageUtils
import com.google.mlkit.vision.common.InputImage
import com.google.mlkit.vision.text.Text
import com.google.mlkit.vision.text.TextRecognition
import java.lang.Exception
/**
* Analyzes the frames passed in from the camera and returns any detected text within the requested
* crop region.
*/
private val detector = TextRecognition.getClient()
class TextAnalyzer(
private val context: Context,
private val lifecycle: Lifecycle,
private val result: MutableLiveData<String>,
private val imageCropPercentages: MutableLiveData<Pair<Int, Int>>
) : ImageAnalysis.Analyzer {
// TODO: Instantiate TextRecognition detector
// TODO: Add lifecycle observer to properly close ML Kit detectors
@androidx.camera.core.ExperimentalGetImage
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image ?: return
val rotationDegrees = imageProxy.imageInfo.rotationDegrees
// We requested a setTargetAspectRatio, but it's not guaranteed that's what the camera
// stack is able to support, so we calculate the actual ratio from the first frame to
// know how to appropriately crop the image we want to analyze.
val imageHeight = mediaImage.height
val imageWidth = mediaImage.width
val actualAspectRatio = imageWidth / imageHeight
val convertImageToBitmap = ImageUtils.convertYuv420888ImageToBitmap(mediaImage)
val cropRect = Rect(0, 0, imageWidth, imageHeight)
// If the image has a way wider aspect ratio than expected, crop less of the height so we
// don't end up cropping too much of the image. If the image has a way taller aspect ratio
// than expected, we don't have to make any changes to our cropping so we don't handle it
// here.
val currentCropPercentages = imageCropPercentages.value ?: return
if (actualAspectRatio > 3) {
val originalHeightCropPercentage = currentCropPercentages.first
val originalWidthCropPercentage = currentCropPercentages.second
imageCropPercentages.value =
Pair(originalHeightCropPercentage / 2, originalWidthCropPercentage)
}
// If the image is rotated by 90 (or 270) degrees, swap height and width when calculating
// the crop.
val cropPercentages = imageCropPercentages.value ?: return
val heightCropPercent = cropPercentages.first
val widthCropPercent = cropPercentages.second
val (widthCrop, heightCrop) = when (rotationDegrees) {
90, 270 -> Pair(heightCropPercent / 100f, widthCropPercent / 100f)
else -> Pair(widthCropPercent / 100f, heightCropPercent / 100f)
}
cropRect.inset(
(imageWidth * widthCrop / 2).toInt(),
(imageHeight * heightCrop / 2).toInt()
)
val croppedBitmap =
ImageUtils.rotateAndCrop(convertImageToBitmap, rotationDegrees, cropRect)
// TODO call recognizeText() once implemented
recognizeTextOnDevice(InputImage.fromBitmap(croppedBitmap, 0)).addOnCompleteListener {
imageProxy.close()
}
}
// fun recognizeText() {
// // TODO Use ML Kit's TextRecognition to analyze frames from the camera live feed.
// }
private fun recognizeTextOnDevice(
image: InputImage
): Task<Text> {
// Pass image to an ML Kit Vision API
return detector.process(image)
.addOnSuccessListener { visionText ->
// Task completed successfully
result.value = visionText.text
}
.addOnFailureListener { exception ->
// Task failed with an exception
Log.e(TAG, "Text recognition error", exception)
val message = getErrorMessage(exception)
message?.let {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}
}
}
private fun getErrorMessage(exception: Exception): String? {
val mlKitException = exception as? MlKitException ?: return exception.message
return if (mlKitException.errorCode == MlKitException.UNAVAILABLE) {
"Waiting for text recognition model to be downloaded"
} else exception.message
}
companion object {
private const val TAG = "TextAnalyzer"
}
}
|
package com.bpplanner.bpp.model.base
import androidx.lifecycle.LiveData
import com.bpplanner.bpp.utils.LogUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import retrofit2.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
class LiveDataCallAdapter<R>(private val responseType: Type) :
CallAdapter<R, LiveData<ApiStatus<R>>> {
override fun responseType(): Type = responseType
override fun adapt(call: Call<R>): ApiLiveData<R> {
val liveData = MutableApiLiveData<R>()
liveData.value = ApiStatus.Loading
process(call, liveData)
return liveData
}
private fun process(call: Call<R>, liveData: MutableApiLiveData<R>) {
call.enqueue(object : Callback<R> {
override fun onFailure(call: Call<R>, t: Throwable) {
LogUtil.e("HttpRetrofit", "onFailure", t)
}
override fun onResponse(call: Call<R>, response: Response<R>) {
CoroutineScope(Dispatchers.Main).launch {
val code = response.code()
if (response.isSuccessful) {
liveData.value = ApiStatus.Success(code, response.body())
return@launch
}
when (response.code()) {
else -> {
liveData.value = ApiStatus.Error(code, response.message())
return@launch
}
}
}
}
})
}
class Factory : CallAdapter.Factory() {
override fun get(
returnType: Type,
annotations: Array<Annotation>,
retrofit: Retrofit
): CallAdapter<*, *>? {
if (getRawType(returnType) != LiveData::class.java) {
return null
}
val observableType = getParameterUpperBound(0, returnType as ParameterizedType)
val rawObservableType = getRawType(observableType)
require(rawObservableType == ApiStatus::class.java) { "type must be a resource" }
require(observableType is ParameterizedType) { "resource must be parameterized" }
val bodyType = getParameterUpperBound(0, observableType)
return LiveDataCallAdapter<Any>(
bodyType
)
}
}
}
|
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.17;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./INarfexP2pFactory.sol";
import "./INarfexP2pRouter.sol";
/// @title Buy offer in Narfex P2P service
/// @author Danil Sakhinov
/// @dev Allow to create trades with current offer parameters
contract NarfexP2pBuyOffer {
struct Trade {
uint8 status; // 0 = closed, 1 = active, 2 = created by owner
uint32 createDate;
uint moneyAmount; // Fiat to send to bank account
uint fiatAmount; // Initial amount - commission - fee
uint fiatLocked; // Initial amount - commission
address client;
address lawyer;
uint bankAccountId;
bytes32 chatRoom;
}
INarfexP2pFactory immutable factory;
address immutable public fiat;
address immutable public owner;
uint constant DAY = 86400;
uint constant PERCENT_PRECISION = 10**4;
uint constant ETH_PRECISION = 10**18;
uint16 public commission;
uint public minTradeAmount;
uint public maxTradeAmount;
bool public isKYCRequired;
address[] private _currentClients;
string[] private _bankAccounts;
bool private _isActive;
bytes21 private _activeHours; // Active hours of week. 21 bytes = 24 x 7 / 8
mapping(address => Trade) private _trades;
mapping(address => bool) private _blacklist;
event P2pOfferBlacklisted(address indexed _client);
event P2pOfferUnblacklisted(address indexed _client);
event P2pOfferDisable();
event P2pOfferEnable();
event P2pOfferScheduleUpdate(bytes21 _schedule);
event P2pOfferAddBankAccount(uint _index, string _jsonData);
event P2pOfferClearBankAccount(uint _index);
event P2pOfferKYCRequired();
event P2pOfferKYCUnrequired();
event P2pOfferSetCommission(uint _percents);
event P2pCreateTrade(address indexed _client, uint moneyAmount, uint fiatAmount);
event P2pOfferWithdraw(uint _amount);
event P2pSetLawyer(address indexed _client, address _offer, address indexed _lawyer);
event P2pConfirmTrade(address indexed _client, address indexed _lawyer);
event P2pCancelTrade(address indexed _client, address indexed _lawyer);
event P2pSetTradeAmounts(uint _minTradeAmount, uint _maxTradeAmount);
/// @param _factory Factory address
/// @param _owner Validator as offer owner
/// @param _fiatAddress Fiat
/// @param _commission in percents with precision 4 digits (10000 = 100%);
constructor(
address _factory,
address _owner,
address _fiatAddress,
uint16 _commission,
uint _minTradeAmount,
uint _maxTradeAmount
) {
fiat = _fiatAddress;
factory = INarfexP2pFactory(_factory);
require (factory.getFiatFee(fiat) + _commission < PERCENT_PRECISION, "Commission too high");
owner = _owner;
_isActive = true;
// Fill all hours as active
_activeHours = ~bytes21(0);
isKYCRequired = true;
commission = _commission;
minTradeAmount = _minTradeAmount;
maxTradeAmount = _maxTradeAmount;
}
modifier onlyOwner() {
require(owner == msg.sender, "Caller is not the owner");
_;
}
/// @notice Check trade is active
/// @return isActive
/// @dev Checks permanent activity, allowance by Protocol and schedule
function getIsActive() public view returns(bool isActive) {
if (!_isActive) return false;
if (!factory.getCanTrade(owner)) return false;
uint8 weekDay = uint8((block.timestamp / DAY + 4) % 7);
uint8 hour = uint8((block.timestamp / 60 / 60) % 24);
uint bitIndex = 7 * weekDay + hour;
bytes21 hourBit = ~(~bytes21(0) >> 1 << 1) << bitIndex;
return _activeHours & hourBit > 0;
}
/// @notice Get current fiat balance in this offer contract
/// @return Fiat balance
function getBalance() public view returns(uint) {
return IERC20(fiat).balanceOf(address(this));
}
/// @notice Get fiat amount locked by current trades
/// @return Locked fiat amount
function getLockedAmount() public view returns(uint) {
uint locked;
unchecked {
for (uint i; i < _currentClients.length; i++) {
address client = _currentClients[i];
if (client != address(0)) {
locked += _trades[client].fiatLocked;
}
}
}
return locked;
}
/// @notice Get how much balance available for new trades of withdraw
/// @return Available balance
function getAvailableBalance() public view returns(uint) {
return getBalance() - getLockedAmount();
}
/// @notice Get fiat limit for a new trade
/// @return Fiat limit
function getTradeLimitAvailable() private view returns(uint) {
uint balance = getAvailableBalance();
uint poolLimit = factory.getValidatorLimit(owner, fiat);
uint limit = maxTradeAmount;
if (balance < limit) limit = balance;
if (poolLimit < limit) limit = poolLimit;
return limit;
}
/// @notice Get sum of Protocol and Offer commissions
/// @return Commission in percents with precision 4 digits
function getTotalCommission() private view returns(uint) {
return uint(factory.getFiatFee(fiat) + commission);
}
/// @notice Sets offer commission
/// @param _percents Commission in percents with 4 digits of precision
function setCommission(uint16 _percents) public onlyOwner {
require (factory.getFiatFee(fiat) + _percents < PERCENT_PRECISION, "Commission too high");
commission = _percents;
emit P2pOfferSetCommission(_percents);
}
/// @notice Sets trade minumum and maximum amounts
/// @param _minTradeAmount Minimal trade amount
/// @param _maxTradeAmount Maximal trade amount
function setTradeAmounts(uint _minTradeAmount, uint _maxTradeAmount) public onlyOwner {
minTradeAmount = _minTradeAmount;
maxTradeAmount = _maxTradeAmount;
emit P2pSetTradeAmounts(_minTradeAmount, _maxTradeAmount);
}
/// @notice Get offer data in one request
/// @return Offer address
/// @return Fiat address
/// @return Validator address
/// @return Is this Buy offer
/// @return Is current offer active now
/// @return Offer commission
/// @return Total commission
/// @return Minimum fiat amount for trade start
/// @return Maximum fiat amount fot trade start
/// @return Trades quote
function getOffer() public view returns(address, address, address, bool, bool, uint, uint, uint, uint, uint) {
return (
address(this),
fiat,
owner,
true,
getIsActive(),
uint(commission),
getTotalCommission(),
minTradeAmount,
getTradeLimitAvailable(),
getTradesQuote()
);
}
/// @notice Get current client trade
/// @param _client Client account address
/// @return Trade data
function getTrade(address _client) public view returns(Trade memory) {
Trade memory trade = _trades[_client];
return trade;
}
/// @notice Get current trades
/// @return Array of Trade structure
function getCurrentTrades() public view returns(Trade[] memory) {
Trade[] memory trades = new Trade[](_currentClients.length);
unchecked {
for (uint i; i < _currentClients.length; i++) {
trades[i] = getTrade(_currentClients[i]);
}
}
return trades;
}
/// @notice Returns the offer schedule
/// @return Activity hours
function getSchedule() public view returns(bytes21) {
return _activeHours;
}
/// @notice Set new schedule
/// @param _schedule Schedule bytes
function setSchedule(bytes21 _schedule) public onlyOwner {
_activeHours = _schedule;
emit P2pOfferScheduleUpdate(_schedule);
}
/// @notice Get is client blacklisted by Offer or Protocol
/// @param _client Account address
/// @return Is blacklisted
function getIsBlacklisted(address _client) public view returns(bool) {
return _blacklist[_client] || factory.getIsBlacklisted(_client);
}
/// @notice Add client to offer blacklist
/// @param _client Account address
function addToBlacklist(address _client) public onlyOwner {
require(!_blacklist[_client], "Client already in blacklist");
_blacklist[_client] = true;
emit P2pOfferBlacklisted(_client);
}
/// @notice Remove client from offer blacklist
/// @param _client Account address
function removeFromBlacklist(address _client) public onlyOwner {
require(_blacklist[_client], "Client is not in your blacklist");
_blacklist[_client] = false;
emit P2pOfferUnblacklisted(_client);
}
/// @notice Set the offer is permanently active
/// @param _newState Is active bool value
function setActiveness(bool _newState) public onlyOwner {
require(_isActive != _newState, "Already seted");
_isActive = _newState;
if (_newState) {
emit P2pOfferEnable();
} else {
emit P2pOfferDisable();
}
}
/// @notice Set is KYC verification required
/// @param _newState Is required
function setKYCRequirement(bool _newState) public onlyOwner {
require(isKYCRequired != _newState, "Already seted");
isKYCRequired = _newState;
if (_newState) {
emit P2pOfferKYCRequired();
} else {
emit P2pOfferKYCUnrequired();
}
}
/// @notice Add validator's bank account
/// @param _jsonData JSON encoded object
function addBankAccount(string calldata _jsonData) public onlyOwner {
_bankAccounts.push(_jsonData);
emit P2pOfferAddBankAccount(_bankAccounts.length - 1, _jsonData);
}
/// @notice Clead bank account data
/// @param _index Account index
function clearBankAccount(uint _index) public onlyOwner {
_bankAccounts[_index] = '';
emit P2pOfferClearBankAccount(_index);
}
/// @notice Returns validator bank accounts
/// @return Array of strings with JSON encoded objects
function getBankAccounts() public view returns(string[] memory) {
return _bankAccounts;
}
/// @notice Is account have a trade in this offer
/// @param _client Account address
/// @return Is have trade
function isClientHaveTrade(address _client) public view returns(bool) {
unchecked {
for (uint i; i < _currentClients.length; i++) {
if (_currentClients[i] == _client) return true;
}
}
return false;
}
/// @notice Returns how many trades can be created
/// @return Trades amount
function getTradesQuote() public view returns(uint) {
uint limit = factory.getTradesLimit();
return limit > _currentClients.length
? limit - _currentClients.length
: 0;
}
/// @notice Withdraw unlocked fiat amount to the owner
/// @param _amount Amount to withdraw
function withdraw(uint _amount) public onlyOwner {
require(_amount <= getAvailableBalance(), "Not enouth free balance");
SafeERC20.safeTransferFrom(IERC20(fiat), address(this), msg.sender, _amount);
emit P2pOfferWithdraw(_amount);
}
/// @notice Add random lawyer to the trade
/// @param _client Client in a trade
/// @dev Can be called by client and validator once per trade
/// @dev Factory can change the lawyer at any time
function setLawyer(address _client) public {
Trade storage trade = _trades[_client];
require(trade.status > 0, "Trade is not active");
require(trade.lawyer == address(0) || msg.sender == address(factory), "Trade already have a lawyer");
require(
msg.sender == address(this)
|| msg.sender == owner
|| msg.sender == trade.client
|| msg.sender == address(factory),
"You don't have permission to this trade"
);
trade.lawyer = factory.getLawyer();
emit P2pSetLawyer(_client, address(this), trade.lawyer);
}
/// @notice Creade a new trade
/// @param moneyAmount How much money the client should send to the bank account of the validator
/// @param bankAccountId Choosed bank account index
function createTrade(
uint moneyAmount,
uint bankAccountId
) public {
require(getIsActive(), "Offer is not active now");
require(!getIsBlacklisted(msg.sender), "Your account is blacklisted");
require(!isKYCRequired || factory.isKYCVerified(msg.sender), "KYC verification required");
require(bytes(_bankAccounts[bankAccountId]).length > 0, "Bank account is not available");
require(!isClientHaveTrade(msg.sender), "You already have a trade");
require(getTradesQuote() >= 1, "Too much trades in this offer");
uint fiatToLock = moneyAmount - (moneyAmount * commission / PERCENT_PRECISION);
uint fiatAmount = moneyAmount - (moneyAmount * getTotalCommission() / PERCENT_PRECISION);
require(moneyAmount >= minTradeAmount, "Too small trade");
require(fiatAmount <= getTradeLimitAvailable(), "Too big trade");
bytes32 chatRoom = keccak256(abi.encodePacked(
block.timestamp,
owner,
msg.sender
));
_trades[msg.sender] = Trade({
status: 1, /// Normally created trade
createDate: uint32(block.timestamp),
moneyAmount: moneyAmount,
fiatAmount: fiatAmount,
fiatLocked: fiatToLock,
client: msg.sender,
lawyer: address(0),
bankAccountId: bankAccountId,
chatRoom: chatRoom
});
_currentClients.push(msg.sender);
emit P2pCreateTrade(msg.sender, moneyAmount, fiatAmount);
}
/// @notice Create a new trade by the validator when requested by the client
/// @param moneyAmount How much money the client should send to the bank account of the validator
/// @param bankAccountId Choosed bank account index
/// @param clientAddress Client account address
/// @dev The method is called when the client has no gas
/// @dev The client will pay for the gas with fiat later
function createTrade(
uint moneyAmount,
uint bankAccountId,
address clientAddress
) public onlyOwner {
uint gas = gasleft() * tx.gasprice;
require(getIsActive(), "Offer is not active now");
require(!getIsBlacklisted(clientAddress), "Client's account is blacklisted");
require(!isKYCRequired || factory.isKYCVerified(clientAddress), "KYC verification required");
require(bytes(_bankAccounts[bankAccountId]).length > 0, "Bank account is not available");
require(!isClientHaveTrade(clientAddress), "Client already have a trade");
require(getTradesQuote() >= 1, "Too much trades in this offer");
uint fiatToLock = moneyAmount - (moneyAmount * commission / PERCENT_PRECISION);
uint fiatAmount = moneyAmount - (moneyAmount * getTotalCommission() / PERCENT_PRECISION);
require(moneyAmount >= minTradeAmount, "Too small trade");
require(fiatAmount <= getTradeLimitAvailable(), "Too big trade");
/// Subtract fiat equivalent of gas deduction from the final fiat amount
{
uint ethFiatPrice = ETH_PRECISION / factory.getETHPrice(fiat);
uint gasFiatDeduction = ethFiatPrice * gas;
fiatToLock -= gasFiatDeduction;
fiatAmount -= gasFiatDeduction;
}
bytes32 chatRoom = keccak256(abi.encodePacked(
block.timestamp,
owner,
clientAddress
));
_trades[clientAddress] = Trade({
status: 2, /// Trade created by validator
createDate: uint32(block.timestamp),
moneyAmount: moneyAmount,
fiatAmount: fiatAmount,
fiatLocked: fiatToLock,
client: clientAddress,
lawyer: address(0),
bankAccountId: bankAccountId,
chatRoom: chatRoom
});
_currentClients.push(clientAddress);
emit P2pCreateTrade(clientAddress, moneyAmount, fiatAmount);
/// Add a lawyer right away
setLawyer(clientAddress);
}
function removeClientFromCurrent(address _client) public {
unchecked {
uint j;
for (uint i; i < _currentClients.length; i++) {
if (_currentClients[i] == _client) {
j++;
}
if (i < _currentClients.length - 1 && j > 0) {
_currentClients[i] = _currentClients[i + 1];
}
}
if (j > 0) {
_currentClients.pop();
}
}
}
/// @notice Cancel trade
/// @param _client Client account address
/// @dev If the deal is canceled by a lawyer, he will be compensated for gas costs
/// @dev Can't be called by validator
function cancelTrade(address _client) public {
uint gas = gasleft() * tx.gasprice;
Trade storage trade = _trades[_client];
require (trade.status > 0, "Trade is not active");
require (msg.sender == trade.client || msg.sender == trade.lawyer, "You don't have permission");
if (msg.sender == trade.lawyer) {
/// If cancel called by lawyer send fiat equivalent of gas to lawyer
uint ethFiatPrice = ETH_PRECISION / factory.getETHPrice(fiat);
uint gasFiatDeduction = ethFiatPrice * gas;
if (gasFiatDeduction > trade.fiatLocked) {
gasFiatDeduction = trade.fiatLocked;
}
SafeERC20.safeTransferFrom(IERC20(fiat), address(this), trade.lawyer, gasFiatDeduction);
emit P2pCancelTrade(_client, trade.lawyer);
} else {
emit P2pCancelTrade(_client, address(0));
}
trade.status = 0;
removeClientFromCurrent(_client);
}
/// @notice Finish the trade
/// @param _client Client account address
/// @dev If the trade is finished by a lawyer, he will be compensated for gas costs
/// @dev Can be called by validator of lawyer
/// @dev If the trade was initiated by the validator, the funds will be converted to ETH
/// @dev If the trade was initiated by the validator, the caller will receive gas compensation
function confirmTrade(address _client) public {
uint gas = gasleft() * tx.gasprice;
Trade storage trade = _trades[_client];
require (trade.status > 0, "Trade is not active");
require (msg.sender == owner || msg.sender == trade.lawyer, "You don't have permission");
/// Pay fee to the pool
uint fee = trade.fiatLocked - trade.fiatAmount;
INarfexP2pRouter router = INarfexP2pRouter(factory.getRouter());
router.payFee(fiat, fee);
uint fiatAmount = trade.fiatAmount;
uint gasFiatDeduction;
if (msg.sender == trade.lawyer || trade.status == 2) {
/// Subtract fiat equivalent of gas deduction
uint ethFiatPrice = ETH_PRECISION / factory.getETHPrice(fiat);
gasFiatDeduction = ethFiatPrice * gas;
fiatAmount -= gasFiatDeduction;
}
if (msg.sender == trade.lawyer) {
/// If confirmation called by lawyer send fiat equivalent of gas to lawyer
SafeERC20.safeTransferFrom(IERC20(fiat), address(this), trade.lawyer, gasFiatDeduction);
emit P2pConfirmTrade(_client, trade.lawyer);
} else {
emit P2pConfirmTrade(_client, address(0));
}
if (trade.status == 2) {
/// Swap fiat to ETH and send to client
router.swapToETH(_client, fiat, trade.fiatAmount);
} else {
/// Send fiat to client
SafeERC20.safeTransferFrom(IERC20(fiat), address(this), _client, trade.fiatAmount);
}
trade.status = 0;
removeClientFromCurrent(_client);
}
/// @notice Update all settings
/// @param _commission New commission
/// @param _minTradeAmount New minimal trade amount
/// @param _maxTradeAmount New maximum trade amount
/// @param _schedule New active hours packed to bits
function setSettings(uint16 _commission, uint _minTradeAmount, uint _maxTradeAmount, bytes21 _schedule) public onlyOwner {
if (_commission != commission) {
setCommission(_commission);
}
if (_minTradeAmount != minTradeAmount || _maxTradeAmount != maxTradeAmount) {
setTradeAmounts(_minTradeAmount, _maxTradeAmount);
}
if (_schedule != _activeHours) {
setSchedule(_schedule);
}
}
}
|
import React, { PureComponent } from 'react';
import {
FlatList,
Text,
StyleSheet,
View,
Platform,
TouchableOpacity,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { adaptiveColor, setAlphaColor } from './util';
import type {
ItemType,
IViuPickerProps,
IViuPickerState,
RenderItemProps,
} from './types';
import * as Haptics from 'expo-haptics';
class WheelPickerExpo extends PureComponent<IViuPickerProps, IViuPickerState> {
static defaultProps = {
items: [],
backgroundColor: '#FFFFFF',
width: 150,
haptics: false,
};
flatListRef = React.createRef<FlatList>();
backgroundColor = setAlphaColor(this.props.backgroundColor as any, 1);
state = {
selectedIndex: 0,
itemHeight: 40,
listHeight: 200,
data: [],
};
userTouch = false;
componentDidUpdate(prevProps: IViuPickerProps) {
if (this.props.items?.length !== prevProps.items?.length) {
this.setData();
}
}
componentDidMount() {
this.setData();
}
get gradientColor(): string {
return Platform.select({
ios: setAlphaColor(this.backgroundColor, 0.2),
android: setAlphaColor(this.backgroundColor, 0.4),
web: setAlphaColor(this.backgroundColor, 0.4),
}) as string;
}
get gradientContainerStyle() {
const { itemHeight } = this.state;
const { selectedStyle } = this.props;
return [
{ height: 2 * itemHeight, borderColor: selectedStyle?.borderColor },
styles.gradientContainer,
];
}
handleOnSelect(index: number) {
const { items, onChange, haptics } = this.props;
const selectedIndex = Math.abs(index);
if (selectedIndex >= 0 && selectedIndex <= items.length - 1) {
if (
haptics &&
this.userTouch &&
this.state.selectedIndex !== selectedIndex
) {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
}
this.setState({ selectedIndex });
onChange &&
onChange({ index: selectedIndex, item: items[selectedIndex] });
}
}
handleOnPressItem = (index: number) => {
if (index >= 0 && index <= this.props.items.length - 1) {
this.flatListRef.current?.scrollToIndex({
animated: true,
index: index,
});
}
};
setData() {
let { itemHeight, listHeight } = this.state;
const { items, height } = this.props;
if (items?.length) {
const additionalItem = { label: '', value: null };
const data = [
additionalItem,
additionalItem,
...items,
additionalItem,
additionalItem,
] as ItemType[];
if (height) {
listHeight = height;
itemHeight = listHeight / 5;
}
this.setState({ data, itemHeight, listHeight });
}
}
render() {
const { data, itemHeight, listHeight, selectedIndex } = this.state;
const { width, initialSelectedIndex, flatListProps, selectedStyle } =
this.props;
if (!data.length) return;
return (
<View
style={{
height: listHeight,
width,
backgroundColor: this.backgroundColor,
}}
>
<FlatList
keyExtractor={(_, index) => index.toString()}
showsVerticalScrollIndicator={false}
renderItem={(options) =>
PickerItem(
options,
selectedIndex,
{
...styles.listItem,
backgroundColor: this.backgroundColor,
fontSize: itemHeight / 2,
height: itemHeight,
},
this.handleOnPressItem,
this.props.renderItem as any
)
}
{...flatListProps}
onTouchStart={(e) => {
this.userTouch = true;
!!flatListProps?.onTouchStart && flatListProps.onTouchStart(e);
}}
ref={this.flatListRef}
initialScrollIndex={initialSelectedIndex}
data={data}
onScroll={(event) => {
let index = Math.round(
event.nativeEvent.contentOffset.y / itemHeight
);
this.handleOnSelect(index);
}}
getItemLayout={(_, index) => ({
length: itemHeight,
offset: index * itemHeight,
index,
})}
snapToInterval={itemHeight}
/>
<View
style={[
this.gradientContainerStyle,
styles.topGradient,
{ borderBottomWidth: selectedStyle?.borderWidth },
]}
pointerEvents="none"
>
<LinearGradient
style={styles.linearGradient}
colors={[this.backgroundColor, this.gradientColor]}
/>
</View>
<View
style={[
this.gradientContainerStyle,
styles.bottomGradient,
{ borderTopWidth: selectedStyle?.borderWidth },
]}
pointerEvents="none"
>
<LinearGradient
style={styles.linearGradient}
colors={[this.gradientColor, this.backgroundColor]}
/>
</View>
</View>
);
}
}
const Item = React.memo(
({ fontSize, label, fontColor, textAlign }: RenderItemProps) => (
<Text style={{ fontSize, color: fontColor, textAlign }}>{label}</Text>
)
);
const PickerItem = (
{ item, index }: any,
indexSelected: number,
style: any,
onPress: (index: number) => void,
renderItem: (props: RenderItemProps) => JSX.Element
) => {
const gap = Math.abs(index - (indexSelected + 2));
const sizeText = [style.fontSize, style.fontSize / 1.5, style.fontSize / 2];
const fontSize = gap > 1 ? sizeText[2] : sizeText[gap];
const fontColor = adaptiveColor(style.backgroundColor);
const textAlign = 'center';
return (
<TouchableOpacity activeOpacity={1} onPress={() => onPress(index - 2)}>
<View style={style}>
{typeof renderItem === 'function' &&
renderItem({ fontSize, fontColor, label: item.label, textAlign })}
{!renderItem && (
<Item
fontSize={fontSize}
fontColor={fontColor}
textAlign={textAlign}
label={item.label}
/>
)}
</View>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
listItem: {
alignItems: 'center',
justifyContent: 'center',
},
gradientContainer: {
position: 'absolute',
width: '100%',
},
linearGradient: { flex: 1 },
topGradient: { top: 0 },
bottomGradient: { bottom: 0 },
});
export default WheelPickerExpo;
|
package me.joeleoli.hcfactions.faction.argument;
import com.doctordark.util.command.CommandArgument;
import me.joeleoli.hcfactions.FactionsPlugin;
import me.joeleoli.hcfactions.faction.FactionMember;
import me.joeleoli.hcfactions.faction.struct.Relation;
import me.joeleoli.hcfactions.faction.type.Faction;
import me.joeleoli.hcfactions.faction.type.PlayerFaction;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import me.joeleoli.hcfactions.faction.struct.Role;
import java.util.*;
/**
* Faction argument used to demote players to members in {@link Faction}s.
*/
public class FactionDemoteArgument extends CommandArgument {
private final FactionsPlugin plugin;
public FactionDemoteArgument(FactionsPlugin plugin) {
super("demote", "Demotes a player to a member.", new String[]{"uncaptain", "delcaptain", "delofficer"});
this.plugin = plugin;
}
@Override
public String getUsage(String label) {
return '/' + label + ' ' + getName() + " <playerName>";
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "This command is only executable by players.");
return true;
}
if (args.length < 2) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "Usage: " + getUsage(label));
return true;
}
Player player = (Player) sender;
PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(player);
if (playerFaction == null) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "You are not in a faction.");
return true;
}
if (playerFaction.getMember(player.getUniqueId()).getRole() != Role.LEADER) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "You must be a officer to edit the faction roster.");
return true;
}
@SuppressWarnings("deprecation")
FactionMember targetMember = playerFaction.getMember(args[1]);
if (targetMember == null) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "That player is not in your faction.");
return true;
}
Role role = targetMember.getRole();
if (role == Role.MEMBER) {
sender.sendMessage(FactionsPlugin.PREFIX + ChatColor.RED + "That player is already the lowest rank possible.");
return true;
}
if (role == Role.CAPTAIN) {
role = Role.MEMBER;
} else if (role == Role.COLEADER) {
role = Role.CAPTAIN;
}
targetMember.setRole(role);
playerFaction.broadcast(FactionsPlugin.PREFIX + Relation.MEMBER.toChatColour() + targetMember.getName() + ChatColor.YELLOW + " has been demoted to a faction " + role.name().toLowerCase() + ".");
return true;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String label, String[] args) {
if (args.length != 2 || !(sender instanceof Player)) {
return Collections.emptyList();
}
Player player = (Player) sender;
PlayerFaction playerFaction = plugin.getFactionManager().getPlayerFaction(player);
if (playerFaction == null || (playerFaction.getMember(player.getUniqueId()).getRole() != Role.LEADER)) {
return Collections.emptyList();
}
List<String> results = new ArrayList<>();
Collection<UUID> keySet = playerFaction.getMembers().keySet();
for (UUID entry : keySet) {
OfflinePlayer target = Bukkit.getOfflinePlayer(entry);
String targetName = target.getName();
if (targetName != null && playerFaction.getMember(target.getUniqueId()).getRole() == Role.CAPTAIN) {
results.add(targetName);
}
}
return results;
}
}
|
import { Footer } from "@features/chat/components"
import { render } from "@src/test-utils"
import { screen } from "@testing-library/react"
import UserEvent from "@testing-library/user-event"
import { axe } from "jest-axe"
import { testId } from "@src/test-utils"
const mockContent = "Hello world!"
const mockOnSend = jest.fn()
const mockSetContent = jest.fn()
describe("Feature: Chat - Component: Footer", () => {
it("should render without errors", () => {
render(
<Footer
content={mockContent}
onSend={mockOnSend}
setContent={mockSetContent}
/>
)
const chatInput = screen.getByTestId(testId.chat)
expect(chatInput).toBeInTheDocument()
})
it("should call onSend when input is not empty", async () => {
render(
<Footer
content={mockContent}
onSend={mockOnSend}
setContent={mockSetContent}
/>
)
const chatInput = screen.getByTestId(testId.chat)
await UserEvent.type(chatInput, "Hello{enter}")
expect(mockOnSend).toHaveBeenCalledTimes(1)
expect(mockSetContent).toHaveBeenCalled()
})
it("should not call onSend when input is empty", async () => {
render(
<Footer content="" onSend={mockOnSend} setContent={mockSetContent} />
)
const sendButton = screen.getByTestId(testId.chatSubmit)
await UserEvent.click(sendButton)
expect(mockOnSend).not.toHaveBeenCalled()
expect(mockSetContent).not.toHaveBeenCalled()
})
it("should pass an accessibility test", async () => {
const { container } = render(
<Footer
content={mockContent}
onSend={mockOnSend}
setContent={mockSetContent}
/>
)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
})
|
//
// TVShowDetailInteractor.swift
// Euskal-Telebista
//
// Created by Aitor Zubizarreta on 2023-04-01.
//
//
import Foundation
class TVShowDetailInteractor {
// MARK: - Properties (from TVShowDetailPresenterToInteractorProtocol)
var presenter: TVShowDetailInteractorToPresenterProtocol?
var apiManager: TVShowDetailInteractorToAPIManagerProtocol?
var selectedTVShowDetail: TVShowDetail?
var playlistsIDsAndPositions: [[Int]] = [[]]
var selectedTVShowPlaylists: [TVShowPlaylist] = [] {
didSet {
if selectedTVShowPlaylists.count == playlistsIDsAndPositions.count {
orderedTVShowPlaylists = []
for playlistsIDsAndPosition in playlistsIDsAndPositions {
let tvShowPlaylist = selectedTVShowPlaylists.first { $0.id == "\(playlistsIDsAndPosition[0])" }
if let tvShowPlaylist = tvShowPlaylist {
orderedTVShowPlaylists.append(tvShowPlaylist)
}
}
selectedTVShowPlaylists = orderedTVShowPlaylists
presenter?.getTVShowPlaylistSuccess()
}
}
}
var orderedTVShowPlaylists: [TVShowPlaylist] = []
var selectedTVShowVideoSource: TVShowVideoSource? = nil
}
// MARK: - TVShowDetail Presenter To InteractorProtocol
extension TVShowDetailInteractor: TVShowDetailPresenterToInteractorProtocol {
func getTVShowDetailById(_ tvShowId: Int) {
apiManager?.fetchTVShowDetailWithId(tvShowId: tvShowId)
}
func getTVShowVideoById(_ videoId: Int) {
apiManager?.fetchTVShowVideo(videoId: videoId)
}
}
// MARK: - TVShowDetail APIManager To InteractorProtocol
extension TVShowDetailInteractor: TVShowDetailAPIManagerToInteractorProtocol {
func fetchTVShowDetailSuccess(tvShow: TVShow, baseURL: String) {
// TVShow Playlists IDs.
playlistsIDsAndPositions = tvShow.web_playlist.map { [$0.ID, $0.ORDEN] }
print("NOT Ordered : \(playlistsIDsAndPositions)")
playlistsIDsAndPositions.sort { $0[1] > $1[1] }
print("Ordered : \(playlistsIDsAndPositions)")
for playlistsID in playlistsIDsAndPositions {
apiManager?.fetchTVShowPlaylistWithId(tvShowPlaylistId: playlistsID[0])
}
// TVShow Main Info
let name = tvShow.NOMBRE_GROUP
let description = tvShow.SHORT_DESC
// TODO: Category is missing.
var image: URL? = nil
if let imageData = tvShow.images.first {
let imageString = baseURL + imageData.URL
image = URL(string: imageString)
}
let tvShowDetail = TVShowDetail(name: name, category: "", description: description, image: image)
selectedTVShowDetail = tvShowDetail
presenter?.getTVShowDetailSuccess()
}
func fetchTVShowDetailFailure(errorDescription: String) {
presenter?.getTVShowDetailFailure(errorDescription: errorDescription)
}
func fetchTVShowPlaylistSuccess(tvShowPlaylistResponse: TVShowPlaylistResponse) {
// TVShowPlaylistEpisode
var tvShowPlaylistEpisodes: [TVShowPlaylistEpisode] = []
for episode in tvShowPlaylistResponse.web_media {
let image: URL? = URL(string: episode.STILL_URL)
let tvShowPlaylistEpisode = TVShowPlaylistEpisode(id: episode.ID,
startDate: Date(),
endDate: Date(),
pubDate: Date(),
imageURL: image,
length: episode.LENGTH,
language: episode.IDIOMA,
title_EU: episode.NAME_EU,
description_EU: episode.SHORT_DESC_EU)
tvShowPlaylistEpisodes.append(tvShowPlaylistEpisode)
}
// TVShowPlaylist
let tvShowPlaylist = TVShowPlaylist(id: tvShowPlaylistResponse.id,
language: tvShowPlaylistResponse.idioma,
title_EU: tvShowPlaylistResponse.name,
description_EU: tvShowPlaylistResponse.desc_group,
episodes: tvShowPlaylistEpisodes)
selectedTVShowPlaylists.append(tvShowPlaylist)
}
func fetchTVShowPlaylistFailure(errorDescription: String) {
presenter?.getTVShowPlaylistFailure(errorDescription: errorDescription)
}
func fetchTVShowVideoSucess(tvShowVideo: TVShowVideo) {
if let firstVideoSource: TVShowVideoSource = tvShowVideo.RENDITIONS.first {
self.selectedTVShowVideoSource = firstVideoSource
presenter?.getTVShowVideoSuccess()
}
}
}
|
<div *ngIf="mobiliarios" class="container order-container py-2">
<form [formGroup]="orderForm" (ngSubmit)="onNewOrder()">
<!-- Details -->
<div class="row my-3">
<div class="col">
<div class="row">
<label>Detalle pedido: Lista de mobiliarios</label>
</div>
<div class="row table-container" formArrayName="mobiliarios">
<table class="table" aria-labelledby="mobiliario">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Categoría</th>
<th scope="col">Nombre</th>
<th scope="col">Precio unitario</th>
<th scope="col">Cantidad</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr
*ngFor="let mobiliario of mobiliariosControls; let i = index"
[formGroupName]="i"
>
<td>
<button
class="btn"
type="button"
(click)="onRemoveMobiliario(i)"
>
-
</button>
</td>
<td>
<select
class="form-select"
aria-label="Mobiliario"
formControlName="category"
(change)="onChangeCategory()"
>
<option selected>Selecciona categoría</option>
<option
*ngFor="let category of categories; let i = index"
[value]="category.name"
>
{{ category.name }}
</option>
</select>
</td>
<td>
<select
class="form-select"
aria-label="Mobiliario"
formControlName="nameMobiliario"
(change)="onCheckPrices()"
>
<option selected>Selecciona el mobiliario</option>
<option
*ngFor="
let mobiliario of mobiliarios
| filterCategory : categoriesSelected[i] || '';
let i = index
"
[value]="mobiliario.name"
>
{{ mobiliario.name }}
</option>
</select>
</td>
<td>
<input
type="text"
class="form-control no-click"
aria-label="Precio unitario"
aria-describedby="precio-unitario"
formControlName="priceMobiliario"
/>
</td>
<td>
<input
type="text"
class="form-control"
aria-label="Cantidad"
aria-describedby="cantidad-mobiliario"
formControlName="quantityMobiliario"
/>
</td>
<td>
<button
*ngIf="i === mobiliariosControls.length - 1"
class="btn"
type="button"
(click)="onAddMobiliario()"
>
+
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="row">
<div class="form-floating">
<textarea
class="form-control"
placeholder="Descripción del evento"
id="descripcionMobiliarioTextArea"
formControlName="eventDescription"
></textarea>
<label for="descripcionMobiliarioTextArea"
>Descripción del evento</label
>
</div>
</div>
</div>
</div>
<!-- Date -->
<div class="row my-3">
<div class="col">
<div class="row">
<label>Fecha:</label>
</div>
<div class="row" formGroupName="date">
<div class="col-12 col-md-6">
<mat-form-field appearance="fill">
<mat-label>Fecha de inicio</mat-label>
<input
matInput
[matDatepicker]="pickerStart"
class="form-control"
formControlName="startDate"
/>
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle
matIconSuffix
[for]="pickerStart"
></mat-datepicker-toggle>
<mat-datepicker #pickerStart></mat-datepicker>
</mat-form-field>
</div>
<div class="col-12 col-md-6">
<mat-form-field appearance="fill">
<mat-label>Fecha de inicio</mat-label>
<input
matInput
[matDatepicker]="pickerEnd"
class="form-control"
formControlName="endDate"
/>
<mat-hint>MM/DD/YYYY</mat-hint>
<mat-datepicker-toggle
matIconSuffix
[for]="pickerEnd"
></mat-datepicker-toggle>
<mat-datepicker #pickerEnd></mat-datepicker>
</mat-form-field>
</div>
</div>
</div>
</div>
<!-- Address -->
<div class="row my-3">
<div class="col" formGroupName="address">
<div class="row">
<label>Dirección:</label>
</div>
<div class="row">
<div [ngClass]="{ 'input-group': !mobile }">
<div *ngIf="mobile; else InputMobileC" class="input-group">
<input
type="text"
class="form-control"
placeholder="Colonia"
aria-label="Colonia"
formControlName="colonia"
/>
<button
type="button"
class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<span class="visually-hidden">Colonia</span>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li *ngFor="let colonia of colonias">
<a class="dropdown-item" (click)="onSetColonia(colonia)">
{{ colonia }}
</a>
</li>
</ul>
</div>
<ng-template #InputMobileC>
<input
type="text"
class="form-control"
placeholder="Colonia"
aria-label="Colonia"
formControlName="colonia"
/>
<button
type="button"
class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<span class="visually-hidden">Colonia</span>
</button>
<ul class="dropdown-menu dropdown-menu-end">
<li *ngFor="let colonia of colonias">
<a class="dropdown-item" (click)="onSetColonia(colonia)">
{{ colonia }}
</a>
</li>
</ul>
</ng-template>
<input
type="text"
class="form-control"
placeholder="Calle 1"
aria-label="Calle 1"
aria-describedby="calle-1"
formControlName="street1"
/>
<input
type="text"
class="form-control"
placeholder="Calle 2"
aria-label="Calle 2"
aria-describedby="calle-2"
formControlName="street2"
/>
<input
type="text"
class="form-control"
placeholder="No. Interior"
aria-label="No. Interior"
aria-describedby="no-interior"
formControlName="noInterior"
/>
<input
type="text"
class="form-control"
placeholder="No. Exterior"
aria-label="No. Exterior"
aria-describedby="no-exterior"
formControlName="noExterior"
/>
<input
type="text"
class="form-control"
placeholder="Código Postal"
aria-label="Codigo Postal"
aria-describedby="codigo-postal"
formControlName="codigoPostal"
/>
</div>
</div>
<div class="row">
<div class="form-floating">
<textarea
class="form-control"
placeholder="Descripción"
id="descripcionTextArea"
formControlName="description"
></textarea>
<label for="descripcionTextArea">Descripción</label>
</div>
</div>
</div>
</div>
<!-- Consumer -->
<div class="row my-3">
<div class="col">
<div class="row">
<label>Consumidor:</label>
</div>
<div class="row">
<div [ngClass]="{ 'input-group': !mobile }" formGroupName="customer">
<input
type="text"
class="form-control"
placeholder="Nombre"
aria-label="Nombre del consumidor"
aria-describedby="nombre-consumidor"
formControlName="customerName"
/>
<input
type="text"
class="form-control"
placeholder="Apellido"
aria-label="Apellido del consumidor"
aria-describedby="apellido-consumidor"
formControlName="customerLastName"
/>
<input
type="text"
class="form-control"
placeholder="Email"
aria-label="Email del consumidor"
aria-describedby="email-consumidor"
formControlName="customerEmail"
/>
<input
type="text"
class="form-control"
placeholder="Teléfono"
aria-label="Telefono del consumidor"
aria-describedby="telefono-consumidor"
formControlName="customerPhoneNumber"
/>
<input
type="text"
class="form-control"
placeholder="Fecha de nacimiento"
aria-label="Fecha de nacimiento del consumidor"
aria-describedby="fecha-nacimiento-consumidor"
formControlName="customerBirthday"
/>
<select
class="form-select"
aria-label="Genero"
formControlName="genre"
>
<option selected>Selecciona género</option>
<option value="Masculino">Masculino</option>
<option value="Femenino">Femenino</option>
<option value="No binario">No binario</option>
</select>
</div>
</div>
</div>
</div>
<!-- Buttons -->
<div class="row my-5 justify-content-center">
<div class="col-auto">
<button class="btn" type="submit">Solicitar renta</button>
</div>
<div class="col-auto">
<button class="btn">Cancelar</button>
</div>
</div>
</form>
</div>
<app-footer></app-footer>
|
import React, { useState } from 'react';
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import './ImageUploader.css';
function ImageUploader({ setFilesUploaded }) {
const [imageUrls, setImageUrls] = useState([]);
const [moderationResults, setModerationResults] = useState([]);
const [uploadMessage, setUploadMessage] = useState('');
const [uploadProgress, setUploadProgress] = useState({});
const handleFileChange = (event) => {
const selectedFiles = event.target.files;
const urls = Array.from(selectedFiles).map((file) =>
URL.createObjectURL(file)
);
setImageUrls(urls);
};
const handleUpload = async () => {
try {
const selectedFiles = document.getElementById('imageFileInput').files;
if (!selectedFiles.length) {
console.error('No files selected');
return;
}
const results = [];
for (const file of selectedFiles) {
const uuid = uuidv4();
const formData = new FormData();
formData.append('file', file);
formData.append('uuid', uuid);
setUploadProgress((prevProgress) => ({ ...prevProgress, [uuid]: 0 })); // Initialize progress
try {
const response = await axios.post('http://localhost:5000/cms', formData, {
onUploadProgress: (progressEvent) => {
const progress = Math.round((progressEvent.loaded / progressEvent.total) * 100);
setUploadProgress((prevProgress) => ({ ...prevProgress, [uuid]: progress }));
},
});
console.log('Server Response:', response.data);
// Process response and add to results...
} catch (error) {
console.error('Error uploading image:', error);
// Handle error...
}
}
setUploadProgress({}); // Reset progress
setModerationResults(results);
setUploadMessage('Files uploaded successfully');
} catch (error) {
console.error('Error:', error);
setUploadMessage('Upload failed. Please try again.');
}
};
const isUploadComplete = Object.keys(uploadProgress).length === imageUrls.length;
const overallProgress = isUploadComplete
? 100
: Math.round(
(Object.values(uploadProgress).reduce((total, progress) => total + progress, 0) / imageUrls.length)
);
return (
<div className="container">
<h1>Image Moderation</h1>
<div className="image-container">
<form>
<label htmlFor="imageFileInput" className="file-label">
Choose Files
</label>
<input
type="file"
name="file"
id="imageFileInput"
accept="image/*"
multiple
onChange={handleFileChange}
/>
<button type="button" id="uploadButton" onClick={handleUpload}>
Upload Images
</button>
</form>
<div className="progress-container">
<div className="progress">
<div
className="progress-bar bg-success"
role="progressbar"
style={{ width: `${overallProgress}%` }}
aria-valuenow={overallProgress}
aria-valuemin="0"
aria-valuemax="100"
>
{isUploadComplete ? '100%' : `${overallProgress}%`}
</div>
</div>
</div>
<div className="image-preview-container">
{imageUrls.map((imageUrl, index) => (
<img
key={index}
src={imageUrl}
alt={`Uploaded ${index}`}
className="uploaded-image"
/>
))}
</div>
</div>
{/* {moderationResults.length > 0 && (
<div className="result-container">
{moderationResults.map((result, index) => (
<div
key={index}
className={`status-container ${
result.status.toLowerCase() === 'rejected'
? 'status-rejected'
: 'status-approved'
}`}
>
Image {index + 1} Moderation Status: {result.status}
</div>
))}
</div>
)} */}
{uploadMessage && (
<div className={`upload-message alert ${uploadMessage.includes('successfully') ? 'alert-success' : 'alert-danger'}`}>
{uploadMessage}
</div>
)}
</div>
);
}
export default ImageUploader;
|
//
// Copyright (c) Clemens Cords (mail@clemens-cords.com), created 5/3/23
//
#pragma once
#include <mousetrap/menu_model.hpp>
namespace mousetrap
{
#ifndef DOXYGEN
class PopoverMenu;
namespace detail
{
struct _PopoverMenuInternal
{
GObject parent;
GtkPopoverMenu* native;
detail::MenuModelInternal* model;
};
using PopoverMenuInternal = _PopoverMenuInternal;
DEFINE_INTERNAL_MAPPING(PopoverMenu);
}
#endif
/// @brief displays a menu inside a popover that is attached to a popover menu button. If the button is pressed, the popover is shown automatically
/// \signals
/// \signal_closed{PopoverMenu}
/// \widget_signals{PopoverMenu}
class PopoverMenu : public detail::notify_if_gtk_uninitialized,
public Widget,
HAS_SIGNAL(PopoverMenu, closed),
HAS_SIGNAL(PopoverMenu, realize),
HAS_SIGNAL(PopoverMenu, unrealize),
HAS_SIGNAL(PopoverMenu, destroy),
HAS_SIGNAL(PopoverMenu, hide),
HAS_SIGNAL(PopoverMenu, show),
HAS_SIGNAL(PopoverMenu, map),
HAS_SIGNAL(PopoverMenu, unmap)
{
friend class PopoverButton;
public:
/// @brief create from menu model
/// @param model
PopoverMenu(const MenuModel& model);
/// @brief construct from internal
PopoverMenu(detail::PopoverMenuInternal*);
/// @brief destructor
~PopoverMenu();
/// @brief expose internal
NativeObject get_internal() const override;
protected:
void refresh_widgets();
private:
detail::PopoverMenuInternal* _internal = nullptr;
};
}
|
package cms
import (
"errors"
"fmt"
client "github.com/openshift-online/ocm-sdk-go"
v1 "github.com/openshift-online/ocm-sdk-go/accountsmgmt/v1"
cmv1 "github.com/openshift-online/ocm-sdk-go/clustersmgmt/v1"
)
// RetrieveClusterDetail will retrieve cluster detailed information based on the clusterID
func RetrieveClusterDetail(connection *client.Connection, clusterID string) (*cmv1.ClusterGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Get().Send()
}
// ListClusters will list the clusters
func ListClusters(connection *client.Connection, parameters ...map[string]interface{}) (response *cmv1.ClustersListResponse, err error) {
request := connection.ClustersMgmt().V1().Clusters().List()
for _, param := range parameters {
for k, v := range param {
request = request.Parameter(k, v)
}
}
response, err = request.Send()
return
}
// ListClusterResources will retrieve cluster detailed information about its resources based on the clusterID
func ListClusterResources(connection *client.Connection, clusterID string) (*cmv1.ClusterResourcesGetResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Resources().Live().Get()
return request.Send()
}
// RetrieveClusterCredentials will return the response of cluster credentials
func RetrieveClusterCredentials(connection *client.Connection, clusterID string) (*cmv1.CredentialsGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Credentials().Get().Send()
}
// ListClusterGroups will return cluster groups
func ListClusterGroups(connection *client.Connection, clusterID string) (*cmv1.GroupsListResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Groups().List().Send()
}
// RetrieveClusterGroupDetail will return cluster specified group information
func RetrieveClusterGroupDetail(connection *client.Connection, clusterID string, groupID string) (*cmv1.GroupGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Groups().Group(groupID).Get().Send()
}
func ListClusterGroupUsers(connection *client.Connection, clusterID string, groupID string) (*cmv1.UsersListResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Groups().Group(groupID).Users().List().Send()
}
func RetrieveClusterGroupUserDetail(connection *client.Connection, clusterID string, groupID string, userID string) (*cmv1.UserGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Groups().Group(groupID).Users().User(userID).Get().Send()
}
func ListClusterIDPs(connection *client.Connection, clusterID string) (*cmv1.IdentityProvidersListResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().List().Send()
}
func RetrieveClusterIDPDetail(connection *client.Connection, clusterID string, IDPID string) (*cmv1.IdentityProviderGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().IdentityProvider(IDPID).Get().Send()
}
func ListHtpasswdUsers(connection *client.Connection, clusterID string, IDPID string) (*cmv1.HTPasswdUsersListResponse, error) {
return connection.ClustersMgmt().V1().
Clusters().
Cluster(clusterID).
IdentityProviders().
IdentityProvider(IDPID).
HtpasswdUsers().
List().
Send()
}
// RetrieveClusterLogDetail return the log response based on parameter
func RetrieveClusterInstallLogDetail(connection *client.Connection, clusterID string,
parameter ...map[string]interface{}) (*cmv1.LogGetResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Logs().Install().Get()
if len(parameter) == 1 {
for paramK, paramV := range parameter[0] {
request = request.Parameter(paramK, paramV)
}
}
return request.Send()
}
// RetrieveClusterUninstallLogDetail return the uninstall log response based on parameter
func RetrieveClusterUninstallLogDetail(connection *client.Connection, clusterID string,
parameter ...map[string]interface{}) (*cmv1.LogGetResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Logs().Uninstall().Get()
if len(parameter) == 1 {
for paramK, paramV := range parameter[0] {
request = request.Parameter(paramK, paramV)
}
}
return request.Send()
}
func RetrieveClusterStatus(connection *client.Connection, clusterID string) (*cmv1.ClusterStatusGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Status().Get().Send()
}
// cloud_providers & regions
func ListCloudProviders(connection *client.Connection, params ...map[string]interface{}) (*cmv1.CloudProvidersListResponse, error) {
request := connection.ClustersMgmt().V1().CloudProviders().List()
if len(params) == 1 {
for k, v := range params[0] {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func RetrieveCloudProviderDetail(connection *client.Connection, providerID string) (*cmv1.CloudProviderGetResponse, error) {
return connection.ClustersMgmt().V1().CloudProviders().CloudProvider(providerID).Get().Send()
}
// ListRegions list the regions of specified cloud providers
// If params passed, will add parameter to the request
func ListRegions(connection *client.Connection, providerID string, params ...map[string]interface{}) (*cmv1.CloudRegionsListResponse, error) {
request := connection.ClustersMgmt().V1().CloudProviders().CloudProvider(providerID).Regions().List()
if len(params) == 1 {
for k, v := range params[0] {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func RetrieveRegionDetail(connection *client.Connection, providerID string, regionID string) (*cmv1.CloudRegionGetResponse, error) {
return connection.ClustersMgmt().V1().CloudProviders().CloudProvider(providerID).Regions().Region(regionID).Get().Send()
}
func ListAvailableRegions(connection *client.Connection, providerID string, body *cmv1.AWS) (
*cmv1.AvailableRegionsSearchResponse, error) {
return connection.ClustersMgmt().
V1().CloudProviders().
CloudProvider(providerID).
AvailableRegions().
Search().
Body(body).
Send()
}
// version
func ListVersions(connection *client.Connection, parameter ...map[string]interface{}) (resp *cmv1.VersionsListResponse, err error) {
request := connection.ClustersMgmt().V1().Versions().List()
if len(parameter) == 1 {
for k, v := range parameter[0] {
request = request.Parameter(k, v)
}
}
resp, err = request.Send()
return
}
func RetrieveVersionDetail(connection *client.Connection, versionID string) (*cmv1.VersionGetResponse, error) {
return connection.ClustersMgmt().V1().Versions().Version(versionID).Get().Send()
}
// ListMachineTypes will list the machine types
func ListMachineTypes(connection *client.Connection, params ...map[string]interface{}) (*cmv1.MachineTypesListResponse, error) {
request := connection.ClustersMgmt().V1().MachineTypes().List()
if len(params) == 1 {
for k, v := range params[0] {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func DeleteMachinePool(connection *client.Connection, clusterID string, mpID string) (*cmv1.MachinePoolDeleteResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).MachinePools().MachinePool(mpID).Delete().Send()
}
// RetrieveMachineTypeDetail will return the retrieve result of machine type detailed information
func RetrieveMachineTypeDetail(connection *client.Connection, machineTypeID string) (*client.Response, error) {
return connection.Get().Path(fmt.Sprintf(machineTypeIDURL, machineTypeID)).Send()
}
func RetrieveIDP(connection *client.Connection, clusterID string, idpID string) (*cmv1.IdentityProviderGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().IdentityProvider(idpID).Get().Send()
}
func ListIDPs(connection *client.Connection, clusterID string) (*cmv1.IdentityProvidersListResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().List().Send()
}
func DeleteIDP(connection *client.Connection, clusterID string, idpID string) (*cmv1.IdentityProviderDeleteResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().IdentityProvider(idpID).Delete().Send()
}
func PatchIDP(connection *client.Connection, clusterID string, idpID string, patchBody *cmv1.IdentityProvider) (*cmv1.IdentityProviderUpdateResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().IdentityProvider(idpID).Update().Body(patchBody).Send()
}
func CreateClusterIDP(connection *client.Connection, clusterID string, body *cmv1.IdentityProvider) (*cmv1.IdentityProvidersAddResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).IdentityProviders().Add().Body(body).Send()
}
// RetrieveClusterCPUTotalByNodeRolesOS will return the physical cpu_total of the compute nodes of the cluster
func RetrieveClusterCPUTotalByNodeRolesOS(connection *client.Connection, clusterID string) (*cmv1.CPUTotalByNodeRolesOSMetricQueryGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).MetricQueries().CPUTotalByNodeRolesOS().Get().Send()
}
// RetrieveClusterSocketTotalByNodeRolesOS will return the physical socket_total of the compute nodes of the cluster
func RetrieveClusterSocketTotalByNodeRolesOS(connection *client.Connection, clusterID string) (*cmv1.SocketTotalByNodeRolesOSMetricQueryGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).MetricQueries().SocketTotalByNodeRolesOS().Get().Send()
}
func RetrieveDetailedIngressOfCluster(connection *client.Connection, clusterID string, ingressID string) (*cmv1.IngressGetResponse, error) {
resp, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).Ingresses().Ingress(ingressID).Get().Send()
return resp, err
}
// Cluster labels
func ListClusterExternalConfiguration(connection *client.Connection, clusterID string) (*cmv1.ExternalConfigurationGetResponse, error) {
resp, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).ExternalConfiguration().Get().Send()
return resp, err
}
func ListClusterLabels(connection *client.Connection, clusterID string, parameter ...map[string]interface{}) (*cmv1.LabelsListResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).ExternalConfiguration().Labels().List()
for _, param := range parameter {
for k, v := range param {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func RetrieveDetailedLabelOfCluster(connection *client.Connection, clusterID string, labelID string) (*cmv1.LabelGetResponse, error) {
return connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).ExternalConfiguration().Labels().Label(labelID).Get().Send()
}
// Machine Pool related
func ListMachinePool(connection *client.Connection, clusterID string, params ...map[string]interface{}) (*cmv1.MachinePoolsListResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).MachinePools().List()
for _, param := range params {
for k, v := range param {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func RetrieveClusterMachinePool(connection *client.Connection, clusterID string, machinePoolID string) (*cmv1.MachinePool, error) {
resp, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).MachinePools().MachinePool(machinePoolID).Get().Send()
if err != nil {
return nil, err
}
return resp.Body(), nil
}
// Upgrade policies related
func ListUpgradePolicies(connection *client.Connection, clusterID string, params ...map[string]interface{}) (*cmv1.UpgradePoliciesListResponse, error) {
request := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).UpgradePolicies().List()
for _, param := range params {
for k, v := range param {
request = request.Parameter(k, v)
}
}
return request.Send()
}
func RetrieveUpgradePolicies(connection *client.Connection, clusterID string, upgradepolicyID string) (*cmv1.UpgradePolicyGetResponse, error) {
resp, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).UpgradePolicies().UpgradePolicy(upgradepolicyID).Get().Send()
return resp, err
}
// RetrieveCurrentAccount return the response of retrieve current account
func RetrieveCurrentAccount(connection *client.Connection, params ...map[string]interface{}) (resp *v1.CurrentAccountGetResponse, err error) {
if len(params) > 1 {
return nil, errors.New("only one parameter map is allowed")
}
resp, err = connection.AccountsMgmt().V1().CurrentAccount().Get().Send()
return resp, err
}
// RetrieveKubeletConfig returns the kubeletconfig
func RetrieveKubeletConfig(connection *client.Connection, clusterID string) (*cmv1.KubeletConfig, error) {
resp, err := connection.ClustersMgmt().V1().Clusters().Cluster(clusterID).KubeletConfig().Get().Send()
return resp.Body(), err
}
|
const methodMap = [
[
'requestFullscreen',
'exitFullscreen',
'fullscreenElement',
'fullscreenEnabled',
'fullscreenchange',
'fullscreenerror',
],
// New WebKit
[
'webkitRequestFullscreen',
'webkitExitFullscreen',
'webkitFullscreenElement',
'webkitFullscreenEnabled',
'webkitfullscreenchange',
'webkitfullscreenerror',
],
// Old WebKit
[
'webkitRequestFullScreen',
'webkitCancelFullScreen',
'webkitCurrentFullScreenElement',
'webkitCancelFullScreen',
'webkitfullscreenchange',
'webkitfullscreenerror',
],
[
'mozRequestFullScreen',
'mozCancelFullScreen',
'mozFullScreenElement',
'mozFullScreenEnabled',
'mozfullscreenchange',
'mozfullscreenerror',
],
[
'msRequestFullscreen',
'msExitFullscreen',
'msFullscreenElement',
'msFullscreenEnabled',
'MSFullscreenChange',
'MSFullscreenError',
],
];
/**
* NOTE: 首先根据Document对象的区别,区分应该调用哪一个全屏模式的API
*/
const nativeAPI = (() => {
if (typeof document === 'undefined') {
return false;
}
const unprefixedMethods = methodMap[0];
const returnValue: any = {};
for (const methodList of methodMap) {
const exitFullscreenMethod = methodList?.[1];
if (exitFullscreenMethod in document) {
for (const [index, method] of methodList.entries()) {
returnValue[unprefixedMethods[index]] = method;
}
return returnValue;
}
}
return false;
})();
const eventNameMap: any = {
change: nativeAPI.fullscreenchange,
error: nativeAPI.fullscreenerror,
};
class FullScreen {
dom: any;
fullStatus: boolean;
constructor() {
this.dom = null;
this.fullStatus = false;
}
/**
* @method startup 开启全屏模式
* @param dom
* @param options
*/
startup(dom: any, options: any) {
return new Promise((resolve: any, reject: any) => {
if (!document.fullscreenEnabled) {
return false;
}
this.dom = dom;
this.fullStatus = true;
const enterFullScreen = () => {
dom.style.flexDirection = 'row';
dom.style.justifyContent = 'center';
this.off('change', enterFullScreen);
this.fullStatus = false;
resolve();
}
//NOTE: 添加在开启fullscreen模式时的事件监听
this.on('change', enterFullScreen);
//NOTE: 调用对应平台的fullscreen的api,获取返回的promise对象
const createPromise: any = dom[nativeAPI.requestFullscreen]();
if (createPromise instanceof Promise) {
createPromise.then(enterFullScreen).catch(reject);
}
})
}
/**
* @method exit 退出全屏模式时调用
*/
exit() {
return new Promise((resolve: any, reject: any) => {
if (!this.isFullscreen) {
resolve();
return;
}
const exitFullScreen = () => {
this.off('change', exitFullScreen);
resolve();
}
this.on('change', exitFullScreen);
const exitPromise: any = Reflect.get(document, nativeAPI.exitFullscreen)();
if (exitPromise instanceof Promise) {
exitPromise.then(exitFullScreen).catch(reject);
}
})
}
/**
* @method onchange 自定义在开启与关闭时触发的change事件
* @param callback
*/
onchange(callback: any) {
this.on('change', callback);
}
/**
* @method onerror 自定义在开启与关闭时触发的error事件
* @param callback
*/
onerror(callback: any) {
this.on('error', callback);
}
on(event: string, callback: any) {
const eventName = eventNameMap[event];
if (eventName) {
document.addEventListener(eventName, callback, false);
}
}
off(event: string, callback: any) {
const eventName = eventNameMap[event];
if (eventName) {
document.removeEventListener(eventName, callback, false);
}
}
/**
* @property {boolean} isFullscreen 是否是全屏状态
* @property {Element} element 获取当前全屏状态的element对象
* @property {boolean} isEnabled 是否允许全屏模式
*/
get isFullscreen() {
return Boolean(Reflect.get(document, nativeAPI.fullscreenElement))
}
get element() {
return Reflect.get(document, nativeAPI.fullscreenElement) ?? undefined
}
get isEnabled() {
return Reflect.get(document, nativeAPI.fullscreenEnabled)
}
}
export default FullScreen;
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from "../../environments/environment";
import { Post } from './post.model';
const BACKEND_URL = environment.apiUrl+'/posts/';
@Injectable({
providedIn: 'root'
})
export class PostsService {
private posts: Post[]=[];
private postsUpdated = new Subject<{posts: Post[], postCount: number}>()
constructor(private http: HttpClient, private router: Router) { }
getPosts(postsPerPage: number, currentPage: number){
const queryParams = `?pagesize=${postsPerPage}&page=${currentPage}`
//https://github.com/ZoiloGranda/mean-course#observables-and-rxjs
this.http.get<{message:string, posts:any, maxPosts: number}>(BACKEND_URL+queryParams)
.pipe(
map(postData => {
return {
posts: postData.posts.map(post=>{
return {
title: post.title,
content: post.content,
id: post._id,
imagePath: post.imagePath,
creator:post.creator
}
}), maxPosts: postData.maxPosts
}
})
)
.subscribe((transformedPostData)=>{
console.log(transformedPostData)
this.posts = transformedPostData.posts;
//using spread operator and array[] to return a the posts as a new array instead of a reference to this.posts
this.postsUpdated.next({
posts:[...this.posts],
postCount: transformedPostData.maxPosts
})
});
}
getPostsUpdateListener(){
return this.postsUpdated.asObservable()
}
getPost(id: string){
return this.http.get<{
_id:string,
title:string,
content:string,
imagePath:string,
creator:string
}>(
BACKEND_URL+id)
}
addPost(title:string, content:string, image:File){
const postData = new FormData();
postData.append('title',title);
postData.append('content',content);
postData.append('image', image, title);
this.http
.post<{message:string, post: Post}>
(BACKEND_URL,
postData)
.subscribe((responseData)=>{
this.router.navigate(["/"]);
})
}
updatePost(id: string, title: string, content:string, image:File|string){
let postData: Post|FormData;
if (typeof(image)==='object') {
postData = new FormData();
postData.append('id', id);
postData.append('title', title);
postData.append('content', content);
postData.append('image', image, title);
}else{
postData = {
id:id,
title:title,
content:content,
imagePath:image,
creator: null
}
}
this.http
.put(BACKEND_URL + id, postData)
.subscribe(response => {
this.router.navigate(["/"]);
})
}
deletePost(postId: string){
return this.http.delete(BACKEND_URL + postId)
}
}
|
import React, { useEffect, useMemo, useState } from "react";
import { useSelector } from "react-redux";
import { Button, Container, Content, Sidebar, Nav, Sidenav, Modal } from "rsuite";
import { useActions } from "../../store";
import { GridTable } from "../../components/grid";
import GroupIcon from "@rsuite/icons/legacy/Group";
import AdminIcon from "@rsuite/icons/Admin";
import SettingHorizontalIcon from "@rsuite/icons/SettingHorizontal";
import ExitIcon from "@rsuite/icons/Exit";
import { Storage } from "../storage/storage";
const NavHeader = () => {
const [showConfirmExit, setShowConfirmExit] = useState(false);
const { dispatch, actions } = useActions();
const { data, isAdmin } = useSelector((state) => state.user);
const handleConfirmExit = async (confirm) => {
if (confirm) {
dispatch(actions.user.onLogout());
dispatch(actions.user.clearUserData());
dispatch(actions.main.clearUsers());
}
setShowConfirmExit(false);
};
return (
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "start" }}>
<div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 6 }}>
<div
style={{
width: 40,
height: 40,
background: "#f5f5f5",
borderRadius: "50%",
marginTop: 2,
overflow: "hidden",
display: "inline-block",
}}
>
<img loading="lazy" src={`https://i.pravatar.cc/100`} width="40" />
</div>
<span style={{ fontSize: 14 }}>
{isAdmin ? "admin" : "user"} - {data?.username}
</span>
</div>
<Button startIcon={<ExitIcon />} onClick={() => setShowConfirmExit(true)} color="red" appearance="ghost" size="xs">
Выйти
</Button>
<Modal backdrop="static" role="alertdialog" open={showConfirmExit} size="xs">
<Modal.Header>
<ExitIcon color="red" />
</Modal.Header>
<Modal.Body>
Все не сохраненные данные будут утеряны.
<br />
<br />
Выйти?
</Modal.Body>
<Modal.Footer>
<Button onClick={() => handleConfirmExit(true)} color="red" appearance="ghost">
Выйти
</Button>
<Button onClick={() => handleConfirmExit(false)} appearance="subtle">
Отмена
</Button>
</Modal.Footer>
</Modal>
</div>
);
};
export const MainPage = () => {
const { isAdmin, data: userData } = useSelector((state) => state.user);
const [expanded, setExpanded] = React.useState(true);
const [activeKey, setActiveKey] = React.useState(!isAdmin ? "1" : localStorage.getItem("activeKey") || "1");
const { users } = useSelector((state) => state.main);
const { files } = useSelector((state) => state.storage);
const { dispatch, actions } = useActions();
useEffect(() => {
isAdmin && !users.length && dispatch(actions.main.getUsers());
}, [users]);
useEffect(() => {
if (activeKey === "2") {
isAdmin && dispatch(actions.main.getUsers());
}
}, [activeKey, files.length]);
useMemo(() => localStorage.setItem("activeKey", activeKey), [activeKey]);
return (
<Container style={{ height: "100vh", width: "100vw" }}>
<Sidebar width={expanded ? 260 : 56} collapsible>
<Sidenav
style={{ display: "flex", flexDirection: "column", justifyContent: "space-between", height: "100vh" }}
expanded={expanded}
// appearance="inverse"
>
<Sidenav.Body>
<Nav activeKey={activeKey} onSelect={setActiveKey}>
<Nav.Item eventKey={activeKey} icon={<AdminIcon />}>
<NavHeader />
</Nav.Item>
<Nav.Item eventKey="1" icon={<SettingHorizontalIcon />}>
Мое хранилище
</Nav.Item>
{isAdmin && (
<Nav.Item eventKey="2" icon={<GroupIcon />}>
Список пользователей
</Nav.Item>
)}
</Nav>
</Sidenav.Body>
<Sidenav.Toggle onToggle={setExpanded} />
</Sidenav>
</Sidebar>
<Container>
<Content style={{ padding: 20 }}>
{activeKey === "1" && userData && <Storage />}
{isAdmin && activeKey === "2" && <GridTable />}
</Content>
</Container>
</Container>
);
};
|
from dataclasses import dataclass
from ..entities.chat import ChatID
from ..entities.player import PlayerState
from ..common import (
Handler,
UnitOfWork,
ApplicationException,
GameOver,
)
from ..protocols.gateways.game import GameGateway
from ..protocols.gateways.player import PlayerGateway
@dataclass(frozen=True)
class IdleTurnCommand:
chat_id: ChatID
class IdleTurnHandler(Handler[IdleTurnCommand, None]):
def __init__(
self,
game_gateway: GameGateway,
player_gateway: PlayerGateway,
uow: UnitOfWork,
) -> None:
self._game_gateway = game_gateway
self._player_gateway = player_gateway
self._uow = uow
async def execute(self, command: IdleTurnCommand) -> None:
async with self._uow.pipeline:
chat_id = command.chat_id
current_game = await self._game_gateway.get_current_game(chat_id)
if not current_game:
raise ApplicationException(
"Игра не создана. Начните игру командой /game."
)
player = current_game.cur_player
if not player:
raise ApplicationException(
"Не удалось обнаружить текущего игрока."
)
player.state = PlayerState.WAITING
next_player = await self._player_gateway.get_next_player(
player, current_game.id # type: ignore
)
if next_player:
next_player.state = PlayerState.PROCESSING
current_game.set_next_player(next_player)
await self._player_gateway.update_player(next_player)
await self._game_gateway.update_game(current_game)
await self._player_gateway.update_player(player)
await self._uow.commit()
else:
current_game.finish()
await self._uow.commit()
raise GameOver(
(
f"🫤 {player.username} решил пропустить ход. \n"
"Игра завершилась ничьёй, никто не угадал слово... \n"
"Попробуйте ещё раз! /game"
)
)
|
Curso de Arduino e AVR 149
WR Kits Channel
Sensor de Temperatura DS18B20 Dallas
Autor: Eng. Wagner Rambo Data: Dezembro de 2017
www.wrkits.com.br | facebook.com/wrkits | youtube.com/user/canalwrkits
HARDWARE Termômetro olhando-o de frente:
Terminal da direita -> 5V do Arduino
Terminal da esquerda -> GND do Arduino
Terminal central -> digital 10 do Arduino (ligar um resistor de 4,7k entre esta entrada e os 5V)
// --- Bibliotecas Auxiliares ---
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ThingsBoard.h>
#include <Arduino_MQTT_Client.h>
#include <WiFi.h>
#define WIFI_AP "fontes"
#define WIFI_PASS "fontes123"
#define TB_SERVER "thingsboard.cloud"
#define TOKEN "o0u5024pm2u0y9ozw82w"
constexpr uint32_t MAX_MESSAGE_SIZE = 1024U;
WiFiClient espClient;
Arduino_MQTT_Client mqttClient(espClient);
ThingsBoard tb(mqttClient, MAX_MESSAGE_SIZE);
// --- Constantes Auxiliares ---
#define ONE_WIRE_BUS 13
// --- Declaração de Objetos ---
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress insideThermometer = { 0x28, 0xB7, 0x5B, 0x80, 0xE3, 0xE1, 0x3C, 0x2F };
// --- Protótipo das Funções ---
float temp = 0.0;
void printTemperature(DeviceAddress deviceAddress);
// --- Configurações Iniciais ---
void setup() {
Serial.begin(9600); //inicializa comunicação serial
initWiFi();
sensors.begin(); //inicializa sensores
sensors.setResolution(insideThermometer, 10); //configura para resolução de 10 bits
} //end setup
// --- Loop Infinito ---
void loop(void) {
if (WiFi.status() != WL_CONNECTED) {
initWiFi();
}
delay(10);
Serial.println("Sensor DS18B20");
sensors.requestTemperatures();
printTemperature(insideThermometer);
if (!tb.connected()) {
Serial.println("Conectando ao servidor...");
if (!tb.connect(TB_SERVER, TOKEN)) {
Serial.println("Não foi possivel conectar");
return;
}
} else {
Serial.println("Conectado ao Servidor!");
}
tb.sendTelemetryData("Temp", temp);
Serial.println("Enviando dados...");
delay(1000);
tb.loop();
delay(1000);
} //end loop
// --- Desenvolvimento das Funções ---
void printTemperature(DeviceAddress deviceAddress) {
temp = sensors.getTempC(deviceAddress);
if (temp == -127.00) {
Serial.print("Erro de leitura");
} else {
Serial.print(temp);
Serial.print(" °C ");
}
Serial.print("\n\r");
} //end printTemperature
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_AP, WIFI_PASS);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
|
// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tttt_project/common/constant.dart';
import 'package:tttt_project/routes.dart';
import 'package:tttt_project/common/user_controller.dart';
class Header extends StatelessWidget {
const Header({super.key, this.userName});
final String? userName;
@override
Widget build(BuildContext context) {
double screenHeight = MediaQuery.of(context).size.height;
double screenWidth = MediaQuery.of(context).size.width;
final currentUser = Get.put(UserController());
return Container(
color: Colors.blue.shade600,
height: screenHeight * 0.15,
padding: EdgeInsets.only(
left: screenWidth * 0.1,
right: screenWidth * 0.1,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image(image: AssetImage('assets/images/LOGO CICT-06.png')),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Hệ thống quản lý thực tập thực tế",
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white),
),
Text(
"Trường Công nghệ Thông tin và Truyền thông",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w900,
color: Colors.white),
),
],
),
],
),
Container(
constraints: const BoxConstraints(minWidth: 100),
padding: const EdgeInsets.only(top: 15),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: [
ElevatedButton(
onPressed: () async {
final SharedPreferences sharedPref =
await SharedPreferences.getInstance();
await sharedPref.remove('userId');
await sharedPref.setBool("isLoggedIn", false);
await sharedPref.remove('menuSelected');
await GV.auth.signOut();
currentUser.resetUser();
// Navigator.pushNamedAndRemoveUntil(
// context, RouteGenerator.login, (route) => false);
Get.toNamed(RouteGenerator.login);
},
child: const Text("Thoát"))
],
),
const SizedBox(height: 5),
Row(
children: [
const Text(
"Xin chào, ",
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontStyle: FontStyle.italic,
),
),
if (userName != null)
Text(
userName!,
style: const TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
)
else
Obx(
() => Text(
currentUser.userName.value,
style: const TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
],
),
],
),
)
],
),
);
}
}
|
import React, { Component } from 'react'
class ClassComponentIntro extends Component {
render() {
return (
<>
<div className="row">
<div className="col">
<p>class components are more complex than function components.It required you to extend from react component and creat a reander function which return a react element. you can pass data from one class to other class component</p>
<br />
<pre>
class Welcome extends React.Component { <br />
render() {<br />
return <h1>Hello, {this.props.name}</h1>;<br />
}<br />
}<br />
</pre>
<h3>Rendering Components in ReactJS</h3>
<p>React is also capable of rendering user-defined components. To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as the first argument to the ReactDOM.render() method. </p>
</div>
</div>
</>
)
}
}
export default ClassComponentIntro;
|
import './register.css'
import { useRef, useState } from 'react';
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';
import { Navigate } from 'react-router-dom';
export default function Register(props) {
const [disabledButton, setDisabledButton] = useState(false)
const [message, setMessage] = useState('')
const username = useRef()
const email = useRef()
const password = useRef()
if(props.isRedirect.redirect){
return <Navigate to='/'/>
}
let onSubmit = async () => {
try {
// step.1 get input value
let inputUsername = username.current.value
let inputEmail = email.current.value
let inputPassword = password.current.value
// step.2 validate input value
if (inputUsername.length === 0 || inputPassword.length === 0 || inputEmail.length === 0) throw { message: 'Inputan Belum Lengkap' }
if (inputPassword.length < 8) throw { message: 'password invalid' }
let character = /^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/
if (!character.test(inputPassword)) throw { message: 'password must contains number' }
setDisabledButton(true)
let checkEmail = await axios.get(`http://my-json-server.typicode.com/rafliros/jsonserver-jcwd-2203/users?email=${inputEmail}`)
let checkUsername = await axios.get(`http://my-json-server.typicode.com/rafliros/jsonserver-jcwd-2203/users?username=${inputUsername}`)
if (checkEmail.data.length === 0 && checkUsername.data.length === 0) {
//post
let register = await axios.post('http://my-json-server.typicode.com/rafliros/jsonserver-jcwd-2203/users', { username: inputUsername, email: inputEmail, password: inputPassword })
username.current.value = ''
password.current.value = ''
email.current.value = ''
setDisabledButton(false)
toast('Register Success');
setMessage('')
} else {
throw { message:'Email/username already register' }
}
} catch (error) {
setMessage(error.message)
} finally {
}
}
return (
<div className="flex flex-col items-center py-20">
<h1 className="my-fs-25 font-bold">
Create an account
</h1>
<h1 className="my-fs-15 my-grey mt-5 font-bold">
PURWADHIKA® REWARDS
</h1>
<p className="my-grey mt-3" style={{maxWidth: '600px', textAlign: 'center'}}>
Join Purwadhika Rewards to earn Stars for free food and drinks, any way you pay. Get access to mobile ordering, a birthday Reward, and moremore.
</p>
<div className="cards mt-20 px-20 py-10 w-2/5 rounded-md flex flex-column">
<p className='font-bold'>
* indicates required field
</p>
<h1 className='my-fs-20 mt-5 mb-3 font-bold'>
Personal Information
</h1>
<input ref={username} type='text' placeholder='Input you username' className='py-2 px-2 w-100 rounded-md' style={{border: '1px solid grey'}} />
<h1 className='my-fs-20 mt-5 mb-3 font-bold'>
Account Security
</h1>
<input ref={email} type='text' placeholder='Input you email' className='py-2 px-2 w-100 rounded-md' style={{border: '1px solid grey'}} />
<input ref={password} type='text' placeholder='Input you password' className='py-2 px-2 w-100 rounded-md mt-3' style={{border: '1px solid grey'}} />
<div className='text-red-500'>
{message}
</div>
<button disabled={disabledButton} onClick={onSubmit} className='my-bg-main my-light px-3 py-3 mt-3 rounded-full self-end'>
Register
</button>
</div>
<Toaster />
</div>
)
}
|
# Google Fit Data Heatmap
This repository contains a Python script to generate a heatmap from Google Fit data exported in `.tcx` format.
The script parses the `.tcx` files for geolocation data (latitude and longitude) and creates an interactive heatmap using `folium`.
## Requirements
- Python 3.6 or later
- `pandas`
- `folium`
You can install the required packages using pip:
```
pip install pandas folium
```
## Usage
Export Google Fit Data:
- Request your Google Fit data from Google Takeout.
- Extract the downloaded archive to a directory.
Run the Script:
- Navigate to the directory where you extracted your Google Fit data.
- Run the script with the path to the Activities directory as an argument.
```
python script.py <path_to_activities_dir>
# for example:
python script.py Takeout/Fit/Activities
```
The script will parse the `.tcx` files in the specified directory and generate a heatmap saved as `heatmap.html` in the current directory.
## Example output
After running the script, open `heatmap.html` in a web browser to view the interactive heatmap.
|
const express = require('express');
const bodyParser = require('body-parser');
const admin = require('firebase-admin');
const cors = require('cors');
const dotenv = require('dotenv');
const multer = require('multer');
dotenv.config();
const serviceAccountPath = process.env.SERVICE_ACCOUNT_KEY_PATH;
if (!serviceAccountPath) {
throw new Error("Missing SERVICE_ACCOUNT_KEY_PATH environment variable");
}
const serviceAccount = require(serviceAccountPath);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
storageBucket: process.env.FIREBASE_STORAGE_BUCKET
});
const db = admin.firestore();
const bucket = admin.storage().bucket();
const app = express();
app.set('view engine', 'ejs');
app.use(cors());
app.use(bodyParser.json());
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
app.get("/", (req, res) => {
console.log("I am up and running");
res.send("Server is up and running");
});
const productRouter = require("./routes/products")(db, upload, bucket); // Ensure correct path and arguments
const cartRouter = require("./routes/cart")(db);
const adminRouter = require('./routes/admin')(db, upload, bucket)
app.use("/cart", cartRouter);
app.use("/products", productRouter);
app.use("/admin", adminRouter)
const PORT = process.env.PORT || 61361;
app.listen(PORT, () => {
console.log(`Server listening at http://localhost:${PORT}/`);
});
|
from aiogram.types import ReplyKeyboardMarkup, KeyboardButtonPollType
from aiogram.utils.keyboard import ReplyKeyboardBuilder
def reply_keyboard() -> ReplyKeyboardMarkup:
"""
Creating of the Inline Keyboard works in 4 stages:
1. Initialization InlineKeyboardBuilder
2. Make buttons with button() method; You can use request parameters to take some info from sender
3. Resize your keyboard by adjust() method; every argument is count of buttons in line
4. Setup markup with resize, changed input_field_placeholder, one_time parameters
:keyboard: ReplyKeyboardBuilder object
:return: Markup of keyboard
"""
keyboard = ReplyKeyboardBuilder()
keyboard.button(text="Hello")
keyboard.button(text="How to play?")
keyboard.button(text="My phone number is...", request_contact=True)
keyboard.button(text="I'm here...", request_location=True)
keyboard.button(text="Create poll", request_poll=KeyboardButtonPollType(type="regular"))
keyboard.adjust(2, 2)
return keyboard.as_markup(
resize_keyboard=True,
input_field_placeholder="Send message from buttons that is bottom",
one_time_keyboard=True
)
|
# rpc框架
## 总体思路
1. 第一步,先定义一个接口,这个接口就是客户端向服务端发起调用所使用的接口
```java
public interface EchoService {
String echo(String request);
}
```
2. 在服务端实现这个RPC
```java
class EchoServiceImpl implements EchoService {
public String echo(String request) {
return "echo : " + request;
}
}
```
3. 把这个接口发布到网络上
```java
public class RpcPublisher {
public static void main(String args[]) {
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
Socket clientSocket = null;
ServerSocket ss = null;
try {
ss = new ServerSocket(8081);
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
clientSocket = ss.accept();
ois = new ObjectInputStream(clientSocket.getInputStream());
oos = new ObjectOutputStream(clientSocket.getOutputStream());
String serviceName = ois.readUTF();
String methodName = ois.readUTF();
Class<?>[] parameterTypes = (Class<?>[]) ois.readObject();
Object[] parameters = (Object[]) ois.readObject();
Class<?> service = Class.forName(serviceName);
Method method = service.getMethod(methodName, parameterTypes);
oos.writeObject(method.invoke(service.newInstance(), parameters));
} catch (Exception e) {
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
```
> 逻辑比较简单,就是在8081端口等待客户端连接。有新的客户端连接进来的时候,就从客户端那里读取要调用的类名,方法名,然后通过反射找到并且调用这个方法,然后再把调用结果发送给客户端。
4. 客户端只知道调用echo接口
```java
public class Caller {
public static void main(String args[]) {
EchoService echo = (EchoService)Proxy.newProxyInstance(EchoService.class.getClassLoader(),
new Class<?>[]{EchoService.class}, new DynamicProxyHandler());
for (int i = 0; i < 3; i++) {
System.out.println(echo.echo(String.valueOf(i)));
}
}
}
```
5. 使用动态代理来代替客户端与服务端通讯
```java
class DynamicProxyHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Socket s = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
s = new Socket();
s.connect(new InetSocketAddress("localhost", 8081));
oos = new ObjectOutputStream(s.getOutputStream());
ois = new ObjectInputStream(s.getInputStream());
oos.writeUTF("cn.hinus.rpc.EchoServiceImpl");
oos.writeUTF(method.getName());
oos.writeObject(method.getParameterTypes());
oos.writeObject(args);
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (s != null)
s.close();
if (ois != null)
ois.close();
if (oos != null)
oos.close();
}
return null;
}
}
```
## 通过netty重构rpc的网络访问方式
- 服务端
1. RpcServer netty的引导和启动,作为服务端 添加了RequestHandler
2. RequestHandler 用于数据的处理,最重要的是一点是:channelRead0的时候,执行了InvocationTask的run方法,就是对应方法的反射
3. InvocationTask,实现自Runable,run方法中执行反射,如果非异步通过channel写回方法执行结果
- 客户端
1. RpcClients getProxy 获取需要调用的Interface的代理类ClientInvocationHandler
2. ClientInvocationHandler 代理类invoke方法将在Interface方法被调用时执行
3. invoke方法:创建Invocation invocation = new Invocation(method, args);-包装方法调用信息,然后通过conn.send(invocation);或request方法发送给Server
至此形成闭环,也就是总体思路的通过网络通讯的方式发布接口和客户端通过代理类封装网络请求的步骤使用了netty来实现
|
# ----------------------------------------------------------------------- #
# Cartes interractives permettant de représenter le nb de périls par an
# pour une maille géographique donnée
# Pour lancer le shiny : Ctr+A puis Ctrl+Entrée
# Etre patient pour l'affichage en maille commune qui est un peu lent
# ----------------------------------------------------------------------- #
require(shiny)
require(leaflet)
require(dplyr)
require(tidyr)
require(reshape)
# Contours
dep_bound <- sf::st_read("../Data_GIS/geojson/departements-version-simplifiee.geojson")
com_bound <- sf::st_read("../Data_GIS/geojson/communes-version-simplifiee.geojson")
# Data par dep
data_dep <- readRDS("../Data/data_dep_an.rds")
data_inondation <- data_dep %>% cast(departement ~ annee, value = "nb_inondation")
dep_bound_inondation <- left_join(dep_bound, data_inondation, by = c("code"="departement"))
data_secheresse <- data_dep %>% cast(departement ~ annee, value = "nb_secheresse")
dep_bound_secheresse <- left_join(dep_bound, data_secheresse, by = c("code"="departement"))
# Data par dep
data_dep_dedup <- readRDS("../Data/data_dep_an_dedup.rds")
data_inondation_dedup <- data_dep_dedup %>% cast(departement ~ annee, value = "nb_inondation")
dep_bound_inondation_dedup <- left_join(dep_bound, data_inondation_dedup, by = c("code"="departement"))
data_secheresse_dedup <- data_dep_dedup %>% cast(departement ~ annee, value = "nb_secheresse")
dep_bound_secheresse_dedup <- left_join(dep_bound, data_secheresse_dedup, by = c("code"="departement"))
# Data par com
data_com <- readRDS("../Data/data_com_an.rds")
data_inondation_c <- data_com %>% cast(insee ~ annee, value = "nb_inondation")
com_bound_inondation <- left_join(com_bound, data_inondation_c, by = c("code"="insee"))
data_secheresse_c <- data_com %>% cast(insee ~ annee, value = "nb_secheresse")
com_bound_secheresse <- left_join(com_bound, data_secheresse_c, by = c("code"="insee"))
# Quelques paramètres généraux pour les cartes
hl_opt <- highlightOptions(
weight = 2,
color = "#666",
dashArray = "",
bringToFront = TRUE)
# UI -----
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("year", label=h3("Sélectionner une année"),
choices = as.character(1982:2015)),
radioButtons("peril", label = h3("Sélectionner un péril"),
choices = list("Inondation" = 1, "Secheresse" = 2),
selected = 1),
radioButtons("geo", label = h3("Sélectionner une granularité"),
choices = list("Départements sans déduplication" = 1,
"Départements avec déduplication" = 2,
"Communes" = 3),
selected = 1)
),
mainPanel(
leafletOutput("map", height = "605")
)
)
)
server = function(input, output) {
year_to_map <- reactive({input$year})
peril_to_map <- reactive({input$peril})
geo_to_map <- reactive({input$geo})
output$map <- renderLeaflet({
leaflet() %>%
addProviderTiles(providers$Esri.WorldGrayCanvas) %>%
setView(lng = 3, lat = 47, zoom = 4.5)
})
observeEvent(c(input$year, input$peril, input$geo), {
if (peril_to_map() == "1"){ # Cartes inondation
if (geo_to_map() == "1"){ # Inondations par dep sans dedup
pal <- colorNumeric("Blues", range(dep_bound_inondation[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = dep_bound_inondation,
fillColor =~ pal(dep_bound_inondation[[year_to_map()]]),
label =~ paste(dep_bound_inondation$nom),
weight = 0.5,
fillOpacity = 0.5,
color = "white",
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = dep_bound_inondation[[year_to_map()]],
title = "Nombre d'inondations")
} else if(geo_to_map() == "2"){ # Inondations par dep avec dedup
pal <- colorNumeric("Blues", range(dep_bound_inondation_dedup[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = dep_bound_inondation_dedup,
fillColor =~ pal(dep_bound_inondation_dedup[[year_to_map()]]),
label =~ paste(dep_bound_inondation_dedup$nom),
weight = 0.5,
fillOpacity = 0.5,
color = "white",
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = dep_bound_inondation_dedup[[year_to_map()]],
title = "Nombre d'inondations")
}else{ # Inondations par com
pal <- colorNumeric("Blues", range(com_bound_inondation[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = com_bound_inondation,
color =~ pal(com_bound_inondation[[year_to_map()]]),
fillColor =~ pal(com_bound_inondation[[year_to_map()]]),
label =~ paste(com_bound_inondation$nom),
weight = 0.5,
fillOpacity = 0.6,
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = com_bound_inondation[[year_to_map()]],
title = "Nombre d'inondations")
}
}else{ # Cartes secheresse
if (geo_to_map() == "1"){ # Secheresses par dep sans dedup
pal <- colorNumeric("Reds", range(dep_bound_secheresse[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = dep_bound_secheresse,
fillColor =~ pal(dep_bound_secheresse[[year_to_map()]]),
label =~ paste(dep_bound_secheresse$nom),
weight = 0.5,
fillOpacity = 0.5,
color = "white",
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = dep_bound_secheresse[[year_to_map()]],
title = "Nombre de secheresses")
} else if(geo_to_map() == "2"){ # Secheresses par dep avec dedup
pal <- colorNumeric("Reds", range(dep_bound_secheresse_dedup[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = dep_bound_secheresse_dedup,
fillColor =~ pal(dep_bound_secheresse_dedup[[year_to_map()]]),
label =~ paste(dep_bound_secheresse_dedup$nom),
weight = 0.5,
fillOpacity = 0.5,
color = "white",
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = dep_bound_secheresse_dedup[[year_to_map()]],
title = "Nombre de secheresses")
} else{ # Secheresses par com
pal <- colorNumeric("Reds", range(com_bound_inondation[[year_to_map()]], na.rm=T))
leafletProxy("map") %>%
clearShapes() %>%
clearControls() %>%
addPolygons(data = com_bound_secheresse,
color =~ pal(com_bound_secheresse[[year_to_map()]]),
fillColor =~ pal(com_bound_secheresse[[year_to_map()]]),
label =~ paste(com_bound_secheresse$nom),
weight = 0.5,
fillOpacity = 0.6,
dashArray = "1",
highlightOptions = hl_opt) %>%
addLegend(
position = "bottomleft",
pal = pal,
values = com_bound_secheresse[[year_to_map()]],
title = "Nombre de secheresses")
}
}
})
}
shinyApp(ui, server)
|
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:monochrome_jump/game/monochrome_jump.dart';
import 'package:monochrome_jump/widgets/credits_menu.dart';
import 'package:monochrome_jump/widgets/hud.dart';
import 'package:monochrome_jump/widgets/settings_menu.dart';
class MainMenu extends StatelessWidget {
static const id = 'MainMenu';
final MonochromeJumpGame gameRef;
const MainMenu(this.gameRef, {super.key});
@override
Widget build(BuildContext context) {
return Center(
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
child: Card(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
color: Colors.black.withAlpha(100),
child: FittedBox(
fit: BoxFit.scaleDown,
child: Padding(
padding:
const EdgeInsets.symmetric(vertical: 20, horizontal: 100),
child: Wrap(
direction: Axis.vertical,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 10,
children: [
const Text(
'Monochrome Jump',
style: TextStyle(
fontSize: 50,
),
),
ElevatedButton(
onPressed: () {
gameRef.startGamePlay();
gameRef.overlays.remove(MainMenu.id);
gameRef.overlays.add(Hud.id);
},
child: const Text(
'Play',
style: TextStyle(
fontSize: 30,
),
),
),
ElevatedButton(
onPressed: () {
gameRef.overlays.remove(MainMenu.id);
gameRef.overlays.add(SettingsMenu.id);
},
child: const Text(
'Settings',
style: TextStyle(
fontSize: 30,
),
),
),
ElevatedButton(
onPressed: () {
gameRef.overlays.remove(MainMenu.id);
gameRef.overlays.add(CreditsMenu.id);
},
child: const Text(
'Credits',
style: TextStyle(
fontSize: 30,
),
),
),
],
),
),
),
),
),
);
}
}
|
import { resolve } from './deps.ts';
export const externalToInternalURL = (
externalURL: string,
vendorSourcePrefix: string,
): string => {
const url = new URL(externalURL);
return `${vendorSourcePrefix}/${url.hostname}${url.pathname}`;
};
export const internalToExternalURL = (
internalURL: string,
vendorSourcePrefix: string,
): string => {
const url = new URL(internalURL);
const pathname = url.pathname.replace(`${vendorSourcePrefix}/`, '');
return `https://${pathname}`;
};
export const isPathAnURL = (path: string): boolean => {
try {
new URL(path);
return true;
} catch (_error: unknown) {
return false;
}
};
export const fetchSourceFromPath = async (path: string) => {
if (isPathAnURL(path)) {
return await (await fetch(path)).text();
} else {
return await Deno.readTextFile(path);
}
};
export const resolveLocalPath = (path: string) => {
if (path.startsWith('.')) {
return resolve(`${Deno.cwd()}/${path}`);
} else {
return resolve(path);
}
};
// Takes a path and returns a URL or locally resolved path starting with file://.
export function resolvePathToURL(path: string): string {
let resolvedPath: string;
const isURL = isPathAnURL(path);
if (isURL) {
resolvedPath = path;
} else {
resolvedPath = `file://${resolveLocalPath(path)}`;
}
return resolvedPath;
}
|
import { GetItemsInFolderUseCase } from '@app/inventory/read/hexagon/usecases/get-items-in-folder/get-items-in-folder.usecase';
import { InMemoryAuthGateway } from '@app/authentication/infra/gateways/auth-gateways/in-memory-auth.gateway';
import { StubGetItemsInFolderQuery } from '@app/inventory/read/infra/queries/get-items-in-folder/stub-get-items-in-folder.query';
import { GetItemsInFolderResponse } from '@app/inventory/read/hexagon/queries/get-items-in-folder.query';
describe('Feature: Get items in folder', () => {
describe('Scenario: Folder exist', () => {
test('Items are returned', async () => {
const authGateway = new InMemoryAuthGateway();
authGateway.givenAuthUser({
id: 'user-id',
companyId: 'company-id',
});
const getItemsInFolderQuery = new StubGetItemsInFolderQuery();
getItemsInFolderQuery.givenItems(
{
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
companyId: 'company-id',
},
[
{
id: '502150e0-65db-4189-941a-a679f5ec0845',
name: 'item-name',
note: 'This is a note',
tags: [],
createdAt: new Date('2024-01-01'),
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
quantity: 10,
},
],
);
const items = await new GetItemsInFolderUseCase(
authGateway,
getItemsInFolderQuery,
).execute({
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
});
expect(items).toEqual<GetItemsInFolderResponse>([
{
id: '502150e0-65db-4189-941a-a679f5ec0845',
name: 'item-name',
note: 'This is a note',
tags: [],
createdAt: new Date('2024-01-01'),
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
quantity: 10,
},
]);
});
test('Folder is root', async () => {
const authGateway = new InMemoryAuthGateway();
authGateway.givenAuthUser({
id: 'user-id',
companyId: 'company-id',
});
const getItemsInFolderQuery = new StubGetItemsInFolderQuery();
getItemsInFolderQuery.givenItems(
{
companyId: 'company-id',
},
[
{
id: '502150e0-65db-4189-941a-a679f5ec0845',
name: 'item-name',
note: 'This is a note',
tags: [],
createdAt: new Date('2024-01-01'),
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
quantity: 10,
},
],
);
const items = await new GetItemsInFolderUseCase(
authGateway,
getItemsInFolderQuery,
).execute({});
expect(items).toEqual<GetItemsInFolderResponse>([
{
id: '502150e0-65db-4189-941a-a679f5ec0845',
name: 'item-name',
note: 'This is a note',
tags: [],
createdAt: new Date('2024-01-01'),
folderId: 'e0a5e0a5-65db-4189-941a-a679f5ec0845',
quantity: 10,
},
]);
});
});
});
|
const {
fetchAllPlayers,
fetchSinglePlayer,
addNewPlayer,
removePlayer,
renderAllPlayers,
renderSinglePlayer,
renderNewPlayerForm,
} = require("./script");
class Player{
constructor(name, breed, status, imageUrl){
this.name = name;
this.breed = breed;
this.status = status;
this.imageUrl = imageUrl;
};
}
describe("fetchAllPlayers", () => {
// Make the API call once before all the tests run
let players;
beforeAll(async () => {
players = await fetchAllPlayers();
});
test("returns an array", async () => {
expect(Array.isArray(await fetchAllPlayers())).toBe(true);
});
test("returns players with name and id", async () => {
players.forEach((player) => {
expect(player).toHaveProperty("name");
expect(player).toHaveProperty("id");
});
});
});
// TODO: Tests for `fetchSinglePlayer`
describe("fetchSinglePlayer", () => {
// Make the API call once before all the tests run
let player;
beforeAll(async () => {
player = await fetchSinglePlayer(5562);
});
test("returns not null", async () => {
expect(player).not.toBe(null);
});
test("returns player with name and id", async () => {
expect(player).toHaveProperty("name");
expect(player).toHaveProperty("id");
});
});
// TODO: Tests for `addNewPlayer`
describe("addNewPlayer", () => {
let player;
test("returns not null", async () => {
player = await addNewPlayer(new Player("George","Siberian Husky","bench","https://www.siberianhuskyrescue.org/wp-content/uploads/husky.jpg"));
await expect(player).not.toBe(null);
});
});
// (Optional) TODO: Tests for `removePlayer`
|
import { customAlphabet } from 'nanoid/async';
import { createTransport } from 'nodemailer';
import { z } from 'zod';
import got from 'got';
import urlcat from 'urlcat';
const Env = z
.object({
EMAIL_HOST: z.string(),
EMAIL_PORT: z.string(),
EMAIL_SECURE: z.string(),
EMAIL_AUTH_USER: z.string(),
EMAIL_AUTH_PASS: z.string(),
API_URL: z.string().url(),
})
.parse(process.env);
export async function generateConfirmationCode(): Promise<string> {
const nanoid = customAlphabet('0123456789ABCDEF', 6);
return await nanoid();
}
export async function sendConfirmationCodeEmail({
confirmationCode,
email,
}: {
confirmationCode: string;
email: string;
}): Promise<void> {
try {
const mailer = createTransport({
host: Env.EMAIL_HOST,
port: Env.EMAIL_PORT,
secure: Env.EMAIL_SECURE === 'true',
auth: {
user: Env.EMAIL_AUTH_USER,
pass: Env.EMAIL_AUTH_PASS,
},
tls: {
ciphers: 'SSLv3',
},
} as any);
await mailer.sendMail({
from: '"Temporal Electronic Signature" <temporal@electronic-signature.com>',
to: email,
subject: 'Electronic Signature - Confirmation Code',
text: `
The code to confirm the electronic signature is: ${confirmationCode}.
`,
});
} catch (err) {
console.error('sending confirmation code email activity error', err);
throw err;
}
}
export async function stampDocument(documentId: string): Promise<void> {
const url = urlcat(Env.API_URL, `/procedure/stamp/${documentId}`);
await got.post(url);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>React Quick Start Guide</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="./styles.css"/>
</head>
<body>
<nav id="navbar">
<header>GET STARTED</header>
<a class="nav-link" href="#Quick_Start">Quick Start</a>
<a class="nav-link" href="#Creating_and_nesting_components">Creating and nesting components</a>
<a class="nav-link" href="#Writing_markup_with_JSX">Writing markup with JSX</a>
<a class="nav-link" href="#Adding_styles">Adding styles</a>
<a class="nav-link" href="#Displaying_data">Displaying data</a>
<a class="nav-link" href="#Conditional_rendering">Conditional rendering</a>
<a class="nav-link" href="#Rendering_lists">Rendering lists</a>
<a class="nav-link" href="#Responding_to_events">Responding to events</a>
<a class="nav-link" href="#Updating_the_screen">Updating the screen</a>
<a class="nav-link" href="#Using_Hooks">Using Hooks</a>
<a class="nav-link" href="#Sharing_data_between_components">Sharing data between components</a>
<a class="nav-link" href="#Next_Steps">Next Steps</a>
</nav>
<main id="main-doc">
<section id="Quick_Start" class="main-section">
<header>Quick Start</header>
<article>
<p>Welcome to the React documentation! This page will give you an introduction to the 80% of React concepts that you will use on a daily basis.</p>
<ul>
<h3>You will learn</h3>
<li>How to create and nest components</li>
<li>How to add markup and styles</li>
<li>How to display data</li>
<li>How to render conditions and lists</li>
<li>How to respond to events and update the screen</li>
<li>How to share data between components</li>
</ul>
</article>
</section>
<div class="divider"></div>
<section id="Creating_and_nesting_components" class="main-section">
<header>Creating and nesting components</header>
<article>
<p>React apps are made out of components. A component is a piece of the UI (user interface) that has its own logic and appearance. A component can be as small as a button, or as large as an entire page. React components are JavaScript functions that return markup:
</p>
<pre><code>function MyButton() {
return (
<button>I'm a button</button>
);
}</code></pre>
<p>Now that you've declared MyButton, you can nest it into another component:</p>
<pre><code>export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}</code></pre>
<p>Notice that <code><MyButton /></code> starts with a capital letter. That's how you know it's a React component. React component names must always start with a capital letter, while HTML tags must be lowercase.</p>
<p >The <code>export default</code> keywords specify the main component in the file. If you're not familiar with some piece of JavaScript syntax, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export" target="_blank">MDN</a> and <a target="_blank" href="https://javascript.info/import-export" target="_blank">javascript.info</a> have great references.</p>
</article>
</section>
<div class="divider"></div>
<section id="Writing_markup_with_JSX" class="main-section">
<header>Writing markup with JSX</header>
<article>
<p>The markup syntax you've seen above is called JSX. It is optional, but most React projects use JSX for its convenience. All of the <a target="_blank" href="https://react.dev/learn/installation">tools we recommend for local development</a> support JSX out of the box.</p>
<p>JSX is stricter than HTML. You have to close tags like <code><br /></code>. Your component also can't return multiple JSX tags. You have to wrap them into a shared parent, like a <code><div>...</div></code> or an empty <code><>...</></code> wrapper:</p>
<pre><code>function AboutPage () {
return(
<>
<h1>About</h1>
<p>Hello there.<br />How do you do?</p>
</>
);}</code></pre>
<p>If you have a lot of HTML to port to JSX, you can use an <a target="_blank" href="https://transform.tools/html-to-jsx">online converter.</a></p>
</article>
</section>
<div class="divider"></div>
<section id="Adding_styles" class="main-section">
<header>Adding styles</header>
<article>
<p>In React, you specify a CSS class with <code>className</code>. It works the same way as the HTML <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class" target="_blank"><code>class</code></a> attribute:</p>
<pre><code><img className="avatar" /></code></pre>
<p>Then you write the CSS rules for it in a separate CSS file:</p>
<pre><code>/* In your CSS */
.avatar {
border-radius: 50%;
}</code></pre>
<p>React does not prescribe how you add CSS files. In the simplest case, you'll add a <link> tag to your HTML. If you use a build tool or a framework, consult its documentation to learn how to add a CSS file to your project.</p>
</article>
</section>
<div class="divider"></div>
<section id="Displaying_data" class="main-section">
<header>Displaying data</header>
<article>
<p>JSX lets you put markup into JavaScript. Curly braces let you “escape back” into JavaScript so that you can embed some variable from your code and display it to the user. For example, this will display <code>user.name</code>:</p>
<pre><code>return (
<h1>
{user.name}
</h1>
);</code></pre>
<p>You can also “escape into JavaScript” from JSX attributes, but you have to use curly braces instead of quotes. For example, <code>className="avatar"</code> passes the <code>"avatar"</code> string as the CSS class, but <code>src={user.imageUrl}</code> reads the JavaScript <code>user.imageUrl</code> variable value, and then passes that value as the <code>src</code> attribute:</p>
<pre><code>return (
<img
className="avatar"
src={user.imageUrl}
/>
);</code></pre>
<p>You can put more complex expressions inside the JSX curly braces too, for example, <a target="_blank" href="https://javascript.info/operators#string-concatenation-with-binary">string concatenation:</a></p>
<pre><code>const user = {
name: 'Hedy Lamarr',
imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
imageSize: 90,
};
export default function Profile() {
return (
<>
<h1>{user.name}</h1>
<img
className="avatar"
src={user.imageUrl}
alt={'Photo of ' + user.name}
style={{
width: user.imageSize,
height: user.imageSize
}}
/>
</>
);
}</code></pre>
<p>In the above example, <code>style={{}}</code> is not a special syntax, but a regular <code>{}</code> object inside the <code>style={ }</code> JSX curly braces. You can use the <code>style</code> attribute when your styles depend on JavaScript variables.</p>
</article>
</section>
<div class="divider"></div>
<section id="Conditional_rendering" class="main-section">
<header>Conditional rendering</header>
<article>
<p>In React, there is no special syntax for writing conditions. Instead, you'll use the same techniques as you use when writing regular JavaScript code. For example, you can use an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else"><code>if</code></a> statement to conditionally include JSX:</p>
<pre><code>let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return (
<div>
{content}
</div>
);</code></pre>
<p>If you prefer more compact code, you can use the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">conditional <code>?</code> operator</a>. Unlike <code>if</code>, it works inside JSX:</p>
<pre><code><div>
{isLoggedIn ? (
<AdminPanel />
) : (
<LoginForm />
)}
</div></code></pre>
<p>When you don't need the <code>else</code> branch, you can also use a shorter <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#short-circuit_evaluation">logical <code>&&</code> syntax</a>:</p>
<pre><code><div>
{isLoggedIn && <AdminPanel />}
</div></code></pre>
<p>All of these approaches also work for conditionally specifying attributes. If you're unfamiliar with some of this JavaScript syntax, you can start by always using <code>if...else</code>.</p>
</article>
</section>
<div class="divider"></div>
<section id="Rendering_lists" class="main-section">
<header>Rendering lists</header>
<article>
<p>You will rely on JavaScript features like <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for"><code>for</code> loop</a> and the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"><code>array map()</code> function</a> to render lists of components.<br/><br/>
For example, let's say you have an array of products:</p>
<pre><code>const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];</code></pre>
<p>Inside your component, use the <code>map()</code> function to transform an array of products into an array of <code><li></code> items:</p>
<pre><code>const listItems = products.map(product =>
<li key={product.id}>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);</code></pre>
<p>Notice how <code><li></code> has a <code>key</code> attribute. For each item in a list, you should pass a string or a number that uniquely identifies that item among its siblings. Usually, a key should be coming from your data, such as a database ID. React uses your keys to know what happened if you later insert, delete, or reorder the items.</p>
<pre><code>const products = [
{ title: 'Cabbage', isFruit: false, id: 1 },
{ title: 'Garlic', isFruit: false, id: 2 },
{ title: 'Apple', isFruit: true, id: 3 },
];
export default function ShoppingList() {
const listItems = products.map(product =>
<li>
key={product.id}
style={{
color: product.isFruit ? 'magenta' : 'darkgreen'
}}
>
{product.title}
</li>
);
return (
<ul>{listItems}</ul>
);
}</code></pre>
</article>
</section>
<div class="divider"></div>
<section id="Responding_to_events" class="main-section">
<header>Responding to events</header>
<article>
<p>You can respond to events by declaring <i>event handler</i> functions inside your components:</p>
<pre><code>function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return (
<button onClick={handleClick}>
Click me
</button>
);
}</code></pre>
<p>Notice how <code>onClick={handleClick}</code> has no parentheses at the end! Do not <i>call</i> the event handler function: you only need to <i>pass it down</i>. React will call your event handler when the user clicks the button.</p>
</article>
</section>
<div class="divider"></div>
<section id="Updating_the_screen" class="main-section">
<header>Updating the screen</header>
<article>
<p>Often, you'll want your component to “remember” some information and display it. For example, maybe you want to count the number of times a button is clicked. To do this, add state to your component.
First, import <a target="_blank" href="https://react.dev/reference/react/useState"><code>useState</code></a> from React:</p>
<pre><code>import { useState } from 'react';</code></pre>
<p>Now you can declare a <i>state</i> variable inside your component:</p>
<pre><code>function MyButton() {
const [count, setCount] = useState(0);
// ...</code></pre>
<p>You'll get two things from <code>useState</code>: the current state (<code>count</code>), and the function that lets you update it (setCount). You can give them any names, but the convention is to write <code>[something, setSomething]</code>.
The first time the button is displayed, <code>count</code> will be <code>0</code> because you passed <code>0</code> to <code>useState()</code>. When you want to change state, call <code>setCount()</code> and pass the new value to it. Clicking this button will increment the counter:<p>
<pre><code>function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button> onClick={handleClick}>
Clicked {count} times
</button>
);
}</code></pre>
<p>React will call your component function again. This time, <code>count</code> will be <code>1</code>. Then it will be <code>2</code>. And so on.
If you render the same component multiple times, each will get its own state. Click each button separately:<p>
<pre><code>import { useState } from 'react';
export default function MyApp() {
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}</code></pre>
<p>Notice how each button “remembers” its own <code>count</code> state and doesn't affect other buttons.</p>
</article>
</section>
<div class="divider"></div>
<section id="Using_Hooks" class="main-section">
<header>Using Hooks</header>
<article>
<p>Functions starting with <code>use</code> are called <i>Hooks</i>. <code>useState</code> is a built-in Hook provided by React. You can find other built-in Hooks in the API reference. You can also write your own Hooks by combining the existing ones.
Hooks are more restrictive than other functions. You can only call Hooks <i>at the top</i> of your components (or other Hooks). If you want to use <code>useState</code> in a condition or a loop, extract a new component and put it there.</p>
</article>
</section>
<div class="divider"></div>
<section id="Sharing_data_between_components" class="main-section">
<header>Sharing data between components</header>
<article>
<p>In the previous example, each <code>MyButton</code> had its own independent <code>count</code>, and when each button was clicked, only the <code>count</code> for the button clicked changed:</p>
<div class="img-group-left">
<img class="img-left" src="https://react.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child.png&w=640&q=75" />
<p class="img-left-caption">Initially, each <code>MyButton</code>'s <code>count</code> state is <code>0</code></p>
</div>
<div class="img-group-right">
<img class="img-right" src="https://react.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_child_clicked.png&w=640&q=75" />
<p class="img-right-caption">The first <code>MyButton</code> updates its <code>count</code> to <code>1</code></p>
</div>
<p>However, often you'll need components to share data and always update together.
To make both <code>MyButton</code> components display the same <code>count</code> and update together, you need to move the state from the individual buttons “upwards” to the closest component containing all of them.
In this example, it is <code>MyApp</code>:</p>
<div class="img-group-left">
<img class="img-left" src="https://react.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent.png&w=640&q=75" />
<p class="img-left-caption">Initially, <code>MyApp</code>'s <code>count</code> state is <code>0</code> and is passed down to both children</p>
</div>
<div class="img-group-right">
<img class="img-right" src="https://react.dev/_next/image?url=%2Fimages%2Fdocs%2Fdiagrams%2Fsharing_data_parent_clicked.png&w=640&q=75" />
<p class="img-right-caption">On click, <code>MyApp</code> updates its <code>count</code> state to <code>1</code> and passes it down to both children</p>
</div>
<p>Now when you click either button, the <code>count</code> in <code>MyApp</code> will change, which will change both of the counts in <code>MyButton</code>. Here's how you can express this in code.
First, move the state up from <code>MyButton</code> into <code>MyApp</code>:</p>
<pre><code>export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
function MyButton() {
// ... we're moving code from here ...
}</code></pre>
<p>Then, pass the state down from <code>MyApp</code> to each <code>MyButton</code>, together with the shared click handler. You can pass information to <code>MyButton</code> using the JSX curly braces, just like you previously did with built-in tags like <img>:</p>
<pre><code>export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}</code></pre>
<p>The information you pass down like this is called props. Now the <code>MyApp</code> component contains the <code>count</code> state and the <code>handleClick</code> event handler, and passes both of them down as props to each of the buttons.
Finally, change <code>MyButton</code> to read the props you have passed from its parent component:</p>
<pre><code>function MyButton({ count, onClick }) {
return (
<button> onClick={onClick}>
Clicked {count} times
</button>
);
}</code></pre>
<p>When you click the button, the <code>onClick</code> handler fires. Each button's <code>onClick</code> prop was set to the <code>handleClick</code> function inside <code>MyApp</code>, so the code inside of it runs. That code calls <code>setCount(count + 1)</code>, incrementing the <code>count</code> state variable. The new <code>count</code> value is passed as a prop to each button, so they all show the new value. This is called “lifting state up”. By moving state up, you've shared it between components.</p>
<pre><code>import { useState } from 'react';
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
function MyButton({ count, onClick }) {
return (
<button onClick={onClick}>
Clicked {count} times
</button>
);
}</code></pre>
</article>
</section>
<div class="divider"></div>
<section id="Next_Steps" class="main-section">
<header>Next Steps</header>
<article>
<p>
By now, you know the basics of how to write React code!
Check out the <a target="_blank" href="https://react.dev/learn/tutorial-tic-tac-toe">Tutorial</a> to put them into practice and build your first mini-app with React.</p>
<p class="footer">All the documentation in this page is taken from the <a href="https://react.dev/learn" target="_blank">React Learn Website</a></p>
</article>
</section>
</main>
</body>
</html>
|
import React, { useState } from 'react'
function Todo() {
const [inputData, setInputData] = useState('')
const [items, setItems] = useState([])
function onAdd (){
if(!inputData){
}
else{
setItems([...items, inputData])
setInputData('')
}
}
function delEvent(id){
const updatedItems = items.filter((elem, ind)=>{
return ind !== id
})
setItems(updatedItems)
}
function clearList(){
setItems([])
}
return (
<div className="container">
<h1>ToDo List 🚀</h1>
<input type="text" placeholder="✏️Add todo item" value={inputData}
onChange={(e)=>{setInputData(e.target.value)}}/>
<button onClick={onAdd}>Add</button>
<div>
{
items.map((elem, ind)=>{
return(
<div key={ind}>
<span>{elem}</span>
<button onClick={()=>{delEvent(ind)}}>delete</button>
</div>
)
})
}
</div>
<br />
<button onClick={clearList}>Clear List</button>
</div>
)
}
export default Todo
|
<template>
<v-container>
<v-card class="mx-auto" outlined>
<v-card-title class="justify-center pb-0">O que desenhar? </v-card-title>
<v-card-text>
<p>{{ idea }}</p>
<v-btn
color="primary"
:loading="!showButton"
:disabled="!showButton"
@click="submit"
>Gerar
<template v-slot:loader>
<v-progress-circular indeterminate></v-progress-circular>
</template>
</v-btn>
</v-card-text>
</v-card>
</v-container>
</template>
<script>
import { mapState } from 'vuex'
export default {
data: () => ({
showButton: true,
terms: '',
urlToFind: '',
isCity: true,
before_first_result: true,
}),
computed: {
...mapState('ideas', ['idea']),
},
methods: {
submit() {
this.showButton = false
this.$store.commit('ideas/RESET_IDEA')
this.$store
.dispatch('ideas/getIdea')
.then(() => {
this.showButton = true
})
.catch((e) => {
console.log(e)
this.showButton = true
})
},
},
}
</script>
<style scoped>
.center {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
}
</style>
|
import {
Links,
LiveReload,
Meta,
Outlet,
Scripts,
ScrollRestoration,
} from "@remix-run/react";
import type { LinksFunction, MetaFunction } from "@remix-run/cloudflare";
import globalStyle from "./global.css";
import tailwind from "./tailwind.css";
export const meta: MetaFunction = () => ({
charset: "utf-8",
title: "New Remix App",
viewport: "width=device-width,initial-scale=1",
lang: "ja",
});
export const links: LinksFunction = () => [
{
rel: "preconnect",
href: "https://fonts.googleapis.com",
},
{
rel: "preconnect",
href: "https://fonts.gstatic.com",
crossOrigin: "anonymous",
},
{
rel: "stylesheet",
href: "https://fonts.googleapis.com/css2?family=Fira+Code:wght@300;400;500;600;700&family=Noto+Sans+JP:wght@100;300;400;500;700;900&family=Noto+Serif+JP:wght@200;300;400;500;600;700;900&display=swap",
},
{
rel: "stylesheet",
href: globalStyle,
},
{
rel: "stylesheet",
href: tailwind,
},
];
export default function App() {
return (
// <html data-theme="light">
<html data-theme="dark">
<head>
<Meta />
<Links />
</head>
<body className="prose">
<Outlet />
<ScrollRestoration />
<Scripts />
<LiveReload />
</body>
</html>
);
}
|
package xfacthd.framedblocks.cmdtests;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.context.CommandContext;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.commands.arguments.blocks.BlockStateArgument;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import xfacthd.framedblocks.FramedBlocks;
import xfacthd.framedblocks.cmdtests.tests.*;
import java.io.IOException;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.function.Consumer;
public final class SpecialTestCommand
{
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("uuuu_MM_dd-kk_mm_ss");
private static final Path EXPORT_DIR = Path.of("./logs/test");
public static void registerCommands(final RegisterCommandsEvent event)
{
event.getDispatcher().register(Commands.literal("fbtest")
.then(Commands.literal("skippredicates")
.then(Commands.literal("errors")
.executes(async(
SkipPredicateErrors.NAME, SkipPredicateErrors::testSkipPredicates
))
)
.then(Commands.literal("consistency")
.executes(async(
SkipPredicateConsistency.NAME, SkipPredicateConsistency::testSkipPredicates
))
)
.then(Commands.literal("redundancy")
.executes(async(
SkipPredicateRedundancy.NAME, SkipPredicateRedundancy::testSkipPredicates
))
)
)
.then(Commands.literal("recipecollision")
.executes(async(RecipeCollisions.NAME, RecipeCollisions::checkForRecipeCollisions))
)
.then(Commands.literal("recipepresent")
.executes(RecipePresent::checkForRecipePresence)
)
.then(Commands.literal("chunkban")
.then(Commands.argument("confirm", StringArgumentType.string())
.then(Commands.argument("state", BlockStateArgument.block(event.getBuildContext()))
.executes(ctx -> ChunkBanTest.startChunkBanTest(ctx, true))
)
.executes(ctx-> ChunkBanTest.startChunkBanTest(ctx, false))
)
)
.then(Commands.literal("stateinfo")
.executes(BlockStateInfo::dumpBlockStateInfo)
)
.then(Commands.literal("modelperf")
.executes(async(ModelPerformanceTest.NAME, ModelPerformanceTest::testModelPerformance))
)
);
}
private static Command<CommandSourceStack> async(String testName, AsyncCommand cmd)
{
return ctx ->
{
ctx.getSource().sendSuccess(() -> Component.literal("Starting " + testName + " test"), false);
Consumer<Component> appender = msg -> ctx.getSource().getServer().submit(() ->
ctx.getSource().source.sendSystemMessage(msg)
);
runGuardedOffThread(testName, appender, () -> cmd.run(ctx, appender));
return Command.SINGLE_SUCCESS;
};
}
public static void runGuardedOffThread(String testName, Consumer<Component> msgQueueAppender, Runnable test)
{
Util.backgroundExecutor().submit(() ->
{
try
{
test.run();
}
catch (Throwable t)
{
msgQueueAppender.accept(Component.literal(
"Encountered an uncaught error while testing " + testName + ". See log for details"
));
FramedBlocks.LOGGER.error("Encountered an error while testing {}", testName, t);
}
});
}
public static Component writeResultToFile(String filePrefix, String data)
{
return writeResultToFile(filePrefix, "txt", data);
}
public static Component writeResultToFile(String filePrefix, String fileType, String data)
{
try
{
Files.createDirectories(EXPORT_DIR);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
String dateTime = FORMATTER.format(LocalDateTime.now());
Path path = EXPORT_DIR.resolve("%s_%s.%s".formatted(filePrefix, dateTime, fileType));
try
{
Files.writeString(path, data, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
String pathText = path.toAbsolutePath().toString();
Component pathComponent = Component.literal(pathText).withStyle(style ->
style.withClickEvent(new ClickEvent(ClickEvent.Action.OPEN_FILE, pathText))
.applyFormat(ChatFormatting.UNDERLINE)
);
return Component.literal("Tests results exported to ").append(pathComponent);
}
catch (IOException e)
{
FramedBlocks.LOGGER.error("Encountered an error while exporting test results", e);
return Component.literal("Export of test results failed with error: %s: %s".formatted(
e.getClass().getSimpleName(), e.getMessage()
));
}
}
public interface AsyncCommand
{
void run(CommandContext<CommandSourceStack> ctx, Consumer<Component> msgQueueAppender);
}
private SpecialTestCommand() { }
}
|
---
title: "Chapter 02.01: Linear Models with L2 Loss"
weight: 2001
quizdown: true
---
In this section, we focus on the general concept of linear regression and explain how the linear regression model can be used from a machine learning perspective to predict a continuous numerical target variable. Furthermore, we introduce the \\(L2\\) loss in the context of linear regression and explain how its use results in an SSE-minimal model.
<!--more-->
### Lecture video
{{< video id="ajqQ3NUuNzE" >}}
### Lecture slides
{{< pdfjs file="https://github.com/slds-lmu/lecture_i2ml/blob/master/slides-pdf/slides-regression-linearmodel-l2.pdf" >}}
### Quiz
{{< quizdown >}}
---
shuffle_questions: false
---
## Which statements are true?
- [x] The target in linear regression has to be numeric.
- [ ] The features in linear regression have to be numeric.
- [x] The classical linear model from statistics with Gaussian errors is linear regression with $L2$ loss.
- [x] The hypothesis space of linear regression consists of linear functions of the features.
{{< /quizdown >}}
|
import axios from "axios";
import React, { useState } from "react";
import useSWR, { mutate } from "swr";
const BestPost = () => {
const [pageIndex, setPageIndex] = useState(1);
const { data } = useSWR(
`http://localhost:8000/bestpost?_page=${pageIndex}&_limit=10`
);
return (
<div className="container mt-3">
<div className="d-flex justify-content-between">
<h1 className="lead fs-3">Welcome to Best Post Page</h1>
<button
onClick={() =>
mutate(
`http://localhost:8000/bestpost?_page=${pageIndex + 1}&_limit=10`,
axios
.get(
`http://localhost:8000/bestpost?_page=${
pageIndex + 1
}&_limit=10`
)
.then((res) => res.data)
)
}
className="btn btn-outline-primary"
>
prefetch next pagination{" "}
</button>
</div>
<hr />
<table className="table table-striped table-hover">
<thead>
<tr>
<th>index</th>
<th>title</th>
<th>email</th>
<th>text</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => (
<tr>
<td>{index + 1}</td>
<td>{item.title}</td>
<td>{item.email}</td>
<td>{item.text}</td>
</tr>
))}
</tbody>
</table>
<div className="my-5 d-flex justify-content-between">
<button
onClick={() => setPageIndex(pageIndex - 1)}
className="btn btn-outline-secondary w-50 mx-2"
>
Prev
</button>
<button
onClick={() => setPageIndex(pageIndex + 1)}
className="btn btn-outline-success w-50 mx-2"
>
Next
</button>
</div>
</div>
);
};
export default BestPost;
|
import React from "react";
import { useProductContext } from "../Context/Product";
import ConfirmBox from "./ConfirmBox";
function CartList() {
const { productInfo, incriment, dicrement, checkout, confirm, remove } =
useProductContext();
const price = productInfo?.map((price) => price);
const totalPrice = price.reduce(
(total, unit) => total + unit.quantity * unit.unit,
0
);
return (
<>
<div className=" relative h-[500px] p-3 bg-gary-50 ml-1 overflow-y-scroll">
<table className="w-full">
<thead className="border-b-2 border-slate-400">
<tr>
<th>SL.</th>
<th>Item</th>
<th>qty.</th>
<th>price</th>
</tr>
</thead>
<tbody>
{productInfo?.map((item, index) => (
<tr key={index} className="text-left py-2">
<td className="text-center">{index + 1}</td>
<td>{item.name}</td>
<td className="text-center flex items-center justify-center">
<button
className="bg-gray-300 px-2 rounded-md"
onClick={() => dicrement(item.id)}
>
{"-"}
</button>
<input
type="text"
value={item.quantity}
disabled
className="w-8 text-center bg-gray-300 rounded-sm mx-2"
/>
<button
className="bg-gray-300 px-2 rounded-md"
onClick={() => incriment(item.id)}
>
{"+"}
</button>
</td>
<td className="text-center">{item.quantity * item.unit}</td>
<td
onClick={() => remove(item.id)}
className="cursor-pointer select-none"
>
x
</td>
</tr>
))}
</tbody>
<tfoot className="">
<tr>
<td colSpan={3} className="text-right capitalize">
total:
</td>
<td className="text-center">{totalPrice}</td>
</tr>
</tfoot>
</table>
<button
type="button"
className="absolute bottom-0 left-1/2 -translate-x-1/2 bg-gray-300 px-5 py-1 block mx-auto rounded-md"
onClick={() => checkout(productInfo)}
>
Confirm
</button>
</div>
{confirm && <ConfirmBox totalPrice={totalPrice} />}
</>
);
}
export default React.memo(CartList);
|
const socket = new WebSocket('ws://35.90.15.131:8999');
const configuration = { iceServers: [{ urls: 'stun:stun.stunprotocol.org:3478' }] };
const peerConnection = new RTCPeerConnection(configuration);
const gamepads = {};
const dataChannel = peerConnection.createDataChannel('dataChannel');
document.addEventListener('DOMContentLoaded', async () => {
//new code starts
const remoteVideoElement = document.getElementById('FirstVideo');
//new code ends
window.addEventListener('gamepadconnected', event => {
const gamepad = event.gamepad;
console.log(`Gamepad connected: ${gamepad}`);
gamepads[gamepad.index] = gamepad;
});
window.addEventListener('gamepaddisconnected', event => {
const gamepad = event.gamepad;
console.log(`Gamepad disconnected: ${gamepad}`);
delete gamepads[gamepad.index];
});
socket.addEventListener('open', () => {
console.log('Connected to server');
peerConnection.createOffer({ offerToReceiveVideo: true })
.then(offer => peerConnection.setLocalDescription(offer))
.then(() => {
// Send SDP offer to the server
const offerMessage = JSON.stringify({ type: 'offer', offer: peerConnection.localDescription });
socket.send(offerMessage);
console.log('offer sent', offerMessage);
})
.catch(error => {
console.error('Error during offer creation or local description:', error);
});
peerConnection.onicecandidateerror = event => {
console.error('Error gathering ICE candidate:', event.error);
};
peerConnection.onicecandidate = event => {
if (event.candidate) {
// Send local ICE candidate to the server
console.log ('candidate generated', event.candidate);
socket.send(JSON.stringify({ type: 'candidate', candidate: event.candidate }));
}
};
socket.addEventListener('message', event => {
console.log('Message from server:', event.data);
// Parse the message as JSON
const parsedMessage = JSON.parse(event.data);
// Check the message type and handle accordingly
if (parsedMessage.type === 'candidate') {
// Handle remote ICE candidate
const candidate = new RTCIceCandidate(parsedMessage.candidate);
peerConnection.addIceCandidate(candidate);
} else if (parsedMessage.type === 'answer') {
// Handle SDP answer
const answer = new RTCSessionDescription(parsedMessage.answer);
peerConnection.setRemoteDescription(answer);
}
});
// Connection closed
socket.addEventListener('close', () => {
console.log('Disconnected from server');
});
//new code starts
peerConnection.ontrack = event => {
console.log('Trying to Play Video Track');
console.log('Received streams:', event.streams);
if (event.streams.length > 0) {
const stream = event.streams[0];
console.log('Length seems more than 0 in the Received stream:', stream);
// Check if the stream contains a video track
const videoTracks = stream.getVideoTracks();
if (videoTracks.length > 0) {
console.log('Received video track:', videoTracks[0]);
remoteVideoElement.srcObject = stream; // Set the video stream to the video element
remoteVideoElement.onloadeddata = () => {
console.log('Video metadata loaded. Setting width and height...');
// Set the width and height of the video element to match the video stream size
remoteVideoElement.width = remoteVideoElement.videoWidth;
console.log('Width is:', remoteVideoElement.width);
remoteVideoElement.height = remoteVideoElement.videoHeight;
console.log('Height is:', remoteVideoElement.height);
};
} else {
console.log('No video track in the received stream.');
}
} else {
console.log('No streams in the event.');
}
};
//new code ends
dataChannel.onopen = event => {
console.log('Data channel opened');
dataChannel.send('Hello, World!'); // Send "hello world" when the channel is opened
};
dataChannel.onmessage = event => {
console.log('Received message:', event.data);
};
peerConnection.ondatachannel = event => {
console.log('Data channel received:', event.channel);
const dataChannel = event.channel;
dataChannel.onopen = event => {
console.log('Data channel opened');
dataChannel.send('Hello, World!'); // Send "hello world" when the channel is opened
console.log('Hello World Sent');
setInterval(() => {
const gamepadList = navigator.getGamepads();
for (let i = 0; i < gamepadList.length; i++) {
const gamepad = gamepadList[i];
if (gamepad) {
if (!gamepads[gamepad.index] || gamepad.timestamp !== gamepads[gamepad.index].timestamp) {
console.log(`Gamepad ${i} status changed:`);
console.log(gamepad);
gamepads[gamepad.index] = gamepad;
const gamepadData = {
id: gamepad.id,
timestamp: gamepad.timestamp,
axes: gamepad.axes,
buttons: gamepad.buttons.map(button => ({ pressed: button.pressed, value: button.value })),
connected: gamepad.connected
};
const json = JSON.stringify(gamepadData);
dataChannel.send(json); // Send "hello world" when the channel is opened
console.log('Gamepad State Changed Message Sent', json);
}
} else if (gamepads[i]) {
console.log(`Gamepad ${i} disconnected`);
delete gamepads[i];
}
}
}, 100); // Every 100 milliseconds
};
dataChannel.onmessage = event => {
console.log('Received message:', event.data);
};
};
});
});
peerConnection.oniceconnectionstatechange = function(event) {
console.log('ICE connection state change: ', peerConnection.iceConnectionState);
if (peerConnection.iceConnectionState === 'connected' || peerConnection.iceConnectionState === 'completed') {
console.log('WebRTC connection established with the exchanged SDP offer and ICE candidates');
}
};
|
import json
import os
from typing import Optional, Dict
import click
import sys
from commands import Db
from commands.base import DbCommandBase
from ivr_gateway.exceptions import InvalidRoutingConfigException
from ivr_gateway.api.exceptions import MissingInboundRoutingException
from ivr_gateway.models.admin import AdminCallFrom, AdminCallTo
from ivr_gateway.models.contacts import InboundRouting, Greeting, TransferRouting
from ivr_gateway.models.enums import TransferType, Partner, ContactType
from ivr_gateway.models.queues import Queue
from ivr_gateway.models.workflows import Workflow
from ivr_gateway.services.admin import AdminService
from ivr_gateway.services.calls import CallService
from ivr_gateway.services.operating_times import HolidayHoursService
from ivr_gateway.services.queues import QueueService
from ivr_gateway.services.workflows import WorkflowService
from ivr_gateway.services.graphs import StepTreeGraph
from commands.workflow_registry import workflow_step_tree_registry
class Scaffold(DbCommandBase):
@property
def admin_service(self):
return AdminService(self.db_session)
@property
def workflow_service(self):
return WorkflowService(self.db_session)
@click.command()
@click.option("--confirm", prompt="Are you sure you want to clear out the database?", type=click.BOOL)
@click.pass_context
def delete_all_dev_data(context, self, confirm) -> None:
if os.getenv("IVR_APP_ENV") not in ["local", "dev", "uat", "test"]:
click.echo("Exiting because command cannot be run in production mode")
sys.exit(1)
# Test for reset
if not confirm:
click.echo("Quitting due to lack of confirmation")
sys.exit(1)
else:
click.echo("Deleting data")
context.invoke(Db.clear_workflow_runs)
context.invoke(Db.clear_call_inbound_transfer_and_admin_data)
context.invoke(Db.clear_queues)
@click.command()
@click.option("--config-file-path", prompt="Path to holiday queue hour config file?", type=click.STRING)
def create_holiday_hours(self, config_file_path):
"""
:param config_file_path: "/path/to/config.json"
Example Config File:
[
{
"name": "TestHoliday1",
"date": "2021-05-27",
"queue_configs": [
{
"queues": [
"AFC.LN.CUS"
],
"message": "It is the 27th of May 2021 and we are closed after 2PM.",
"start_time": "09:00",
"end_time": "14:00"
},
{
"queues": [
"AFC.LN.ORIG"
],
"message": "It is the 27th of May 2021 originations is closed all day."
}
]
},
{
"name": "TestHoliday2",
"date": "2021-05-28",
"queue_configs": [
{
"queues": [
"AFC.LN.CUS"
],
"message": "It is the 27th of May 2021 and we are closed after 2PM.",
"start_time": "09:00",
"end_time": "14:00"
},
{
"queues": [
"AFC.LN.ORIG"
],
"message": "It is the 27th of May 2021 originations is closed all day."
}
]
}
]
:return:
"""
with open(config_file_path) as config_file:
holiday_queue_configs = json.load(config_file)
holiday_hours_service = HolidayHoursService(self.db_session)
for holiday_queue_config in holiday_queue_configs:
click.echo(f"Creating holiday hours for {holiday_queue_config.get('name')}")
holiday_hours_service.create_holiday_hours_from_config(holiday_queue_config)
click.echo(f"Holiday hours for {holiday_queue_config.get('name')} created")
click.echo("All holiday hours successfully created.")
@click.command()
@click.option("--config-file-path", prompt="Path to the config file?", type=click.STRING)
@click.option("--upsert", prompt="Overwrite existing inbound routings? (set all existing routings that match the "
"inbound target to inactive)", is_flag=True)
def create_inbound_routings(self, config_file_path, upsert):
# TODO add ability to upsert routings; make sure to set existing routing "active=False"
with open(config_file_path) as config_file:
call_routing_configs = json.load(config_file)
route_configs = [call_routing_config["routes"] for call_routing_config in call_routing_configs]
inbound_targets = [route["inbound_target"] for route_config in route_configs for route in route_config]
call_service = CallService(self.db_session)
existing_inbound_routings = [inbound_routing for inbound_routing in
call_service.get_routings_for_numbers_in_list(inbound_targets)]
existing_inbound_routings_numbers = [routing.inbound_target for routing in existing_inbound_routings]
if len(existing_inbound_routings) > 0:
click.echo(
f"There are inbound routings that exist for the following numbers: {existing_inbound_routings_numbers}")
click.echo("You can add the '--upsert' flag to update these existing inbound routings.")
if upsert:
call_service.set_active_routings_inactive(existing_inbound_routings)
else:
return
for call_routing_config in call_routing_configs:
click.echo(f"Creating inbound routing config for: {call_routing_config}")
for route in call_routing_config["routes"]:
try:
self.create_inbound_routing_with_params(
contact_type=route.get('contact_type'),
inbound_target=route.get('inbound_target'),
greeting_message=call_routing_config.get('greeting_message'),
workflow_name=call_routing_config.get('workflow_name'),
active=route.get('active', True),
admin=route.get('admin', False),
queue_name=route.get('queue_name')
)
except KeyError as key_error:
click.echo("Invalid Key Error")
click.echo(key_error)
except InvalidRoutingConfigException as invalid_config_error:
click.echo("Invalid Config Error")
click.echo(invalid_config_error)
click.echo("Inbound routing configs created.")
@click.command()
@click.option("--contact-type", prompt="What is the contact type associated with the inbound routing?",
type=click.Choice(['IVR', 'SMS', 'CHAT'], case_sensitive=False))
@click.option("--inbound-target", prompt="What is the target associated with the inbound routing?",
type=click.STRING)
@click.option("--greeting-message", prompt="Enter the greeting message to associate with the inbound routing.",
type=click.STRING)
@click.option("--workflow-name",
prompt="Enter a workflow name to associate with the inbound routing (press enter if none).",
default="", type=click.STRING)
@click.option("--is-active", prompt="Should this inbound routing be set as active?", type=click.BOOL, default=True)
@click.option("--is-admin", prompt="Is this an admin inbound routing?", type=click.BOOL, default=False)
@click.option("--initial-queue-name", prompt="Enter the name of the initial queue (if none, press enter).",
default="")
@click.option("--upsert", prompt="Overwrite existing inbound routing? (set any existing routing that match the "
"inbound target to inactive)", is_flag=True)
def create_inbound_routing(self, contact_type: str, inbound_target: str, greeting_message: str,
workflow_name: str = None, is_active=True, is_admin=False,
initial_queue_name: str = None, upsert: bool = False) -> None:
call_service = CallService(self.db_session)
existing_inbound_routings = call_service.get_routings_for_number(inbound_target)
if len(existing_inbound_routings) > 0:
click.echo(f"An inbound routing already exists for {inbound_target}.")
click.echo("You can add the '--upsert' flag to update this existing inbound routing.")
if upsert:
call_service.set_active_routings_inactive(existing_inbound_routings)
else:
return
click.echo("Setting up inbound routing.")
self.create_inbound_routing_with_params(contact_type, inbound_target, greeting_message, workflow_name,
is_active, is_admin, initial_queue_name)
click.echo("Inbound routing setup successfully.")
@click.command()
@click.option("--main-menu-phone-number", prompt="What is your main menu phone number? (e.g. 14432351191)",
type=click.STRING)
@click.option("--admin-routing-phone-number", prompt="What is your admin routing phone number? (e.g. 14432351191)",
type=click.STRING)
@click.option("--queue-config-file", default="./commands/configs/queue_config.json")
def setup_dev(self, main_menu_phone_number, admin_routing_phone_number, queue_config_file) -> None:
workflows_in_database = self.db_session.query(Workflow).count() > 0
if workflows_in_database:
click.echo("There was an error with your request.")
click.echo(
"Please clear the database of workflow runs and call configuration using the flask scaffold delete-all-dev-data command before running setup-dev.")
sys.exit(2)
with open(queue_config_file) as config_file:
initial_queues = json.load(config_file)
for queue_dict in initial_queues:
self.configure_queue(queue_dict)
click.echo("Initial queues and their routings are set up.")
workflows_dict: Dict[str, Workflow] = {}
# TODO: We should probably version these step trees once we get stable and allow loading
# from a configured filepath including version
for workflow_name in workflow_step_tree_registry:
workflows_dict[workflow_name] = self.workflow_service.create_workflow(
workflow_name,
step_tree=workflow_step_tree_registry[workflow_name], tag="1.0.0"
)
greeting = self._create_Iivr_greeting()
self.add_inbound_routing(
contact_type=ContactType.IVR,
inbound_target=main_menu_phone_number,
workflow=workflows_dict["Iivr.ingress"],
greeting=greeting
)
# self.add_call_routing(main_menu_phone_number, None, greeting)
click.echo("Inbound routings set up.")
admin_greeting = Greeting(message="This number is for authorized personal only")
self.db_session.add(admin_greeting)
self.add_inbound_routing(
contact_type=ContactType.IVR,
inbound_target=admin_routing_phone_number,
workflow=None,
greeting=admin_greeting,
admin=True
)
self.add_dnis_shortcut("9", main_menu_phone_number)
click.echo("Admin inbound routings set up.")
@click.command()
@click.option("--call-routing-config-file", default="./commands/configs/inbound_routing_config.json")
@click.option("--queue-config-file", default="./commands/configs/queue_config.json")
def setup_dev_from_config_files(self, call_routing_config_file, queue_config_file) -> None:
workflows_in_database = self.db_session.query(Workflow).count() > 0
if workflows_in_database:
click.echo("There was an error with your request.")
click.echo(
"Please clear the database of workflow runs and call configuration using the flask scaffold "
"delete-all-dev-data command before running setup-dev.")
sys.exit(2)
queues = {}
with open(queue_config_file) as config_file:
initial_queues = json.load(config_file)
for queue_dict in initial_queues:
queue = self.configure_queue(queue_dict)
queues[queue.name] = queue
click.echo("Initial queues and their routings are set up.")
workflows_dict: Dict[str, Workflow] = {}
for workflow_name in workflow_step_tree_registry:
workflows_dict[workflow_name] = self.workflow_service.create_workflow(
workflow_name,
step_tree=workflow_step_tree_registry[workflow_name], tag="1.0.0"
)
with open(call_routing_config_file) as config_file:
initial_call_routes = json.load(config_file)
for call_routing_config in initial_call_routes:
click.echo(f"Creating inbound routing config for: {call_routing_config}")
for route in call_routing_config["routes"]:
self.create_inbound_routing_with_params(
contact_type=route.get('contact_type'),
inbound_target=route.get('inbound_target'),
greeting_message=call_routing_config.get('greeting_message'),
workflow_name=call_routing_config.get('workflow_name'),
active=route.get('active', True),
admin=route.get('admin', False),
queue_name=route.get('queue_name')
)
short_number = route.get("short_number")
if short_number is not None:
self.add_dnis_shortcut(short_number, route.get('inbound_target'))
click.echo("setup finished")
@click.command()
@click.option("--workflow-name", prompt="Name of the workflow to turn into a graph", type=click.STRING)
def setup_graph_from_workflow(self, workflow_name: str) -> None:
workflow_service = WorkflowService(self.db_session)
workflows = workflow_service.get_workflows()
workflow_names = [workflow.workflow_name for workflow in workflows]
if workflow_name in workflow_names:
workflow = workflow_service.get_workflow_by_name(workflow_name)
workflow_config = workflow_service.get_config_for_workflow(workflow)
step_tree_graph = StepTreeGraph(workflow, workflow_config)
step_tree_graph.create_graph()
click.echo("Graph Created Successfully")
else:
click.echo("Invalid Workflow Name")
def configure_queue(self, queue_dict: Dict) -> Queue:
queue = Queue(name=queue_dict["name"], active=True, partner=Partner(queue_dict["partner"]),
past_due_cents_amount=queue_dict.get("past_due_cents_amount", 0),
closed_message=queue_dict.get("closed_message", None))
self.db_session.add(queue)
self.db_session.commit()
if "hours_of_operation" in queue_dict:
hours_of_op_arr = queue_dict["hours_of_operation"]
for day_num in range(7):
for hours_of_op_dict in hours_of_op_arr[day_num]:
self.add_hours_of_operation_to_queue(queue, day_num, hours_of_op_dict)
for transfer_routing_dict in queue_dict.get("transfer_routings"):
type = transfer_routing_dict.get("type")
priority = transfer_routing_dict.get("priority")
if type == "pstn":
number = transfer_routing_dict.get("pstn_number")
system = transfer_routing_dict.get("phone_system")
self.add_pstn_routing(queue, priority, number, system)
elif type == "flex":
task_sid = transfer_routing_dict.get("workflow_sid")
self.add_flex_routing(queue, priority, task_sid)
elif type == "queue":
queue_name = transfer_routing_dict.get("queue_name")
self.add_queue_transfer_routing(queue, priority, queue_name)
return queue
def add_hours_of_operation_to_queue(self, queue, day, hours_of_operation_dict):
queue_service = QueueService(self.db_session)
queue_service.add_hours_of_operations_for_day(
queue,
day,
hours_of_operation_dict["start"],
hours_of_operation_dict["end"]
)
def create_inbound_routing_with_params(self, contact_type: str = None, inbound_target: str = None,
greeting_message: str = None, workflow_name: str = None, active=True,
admin=False, queue_name: str = None):
call_service = CallService(self.db_session)
greeting = call_service.create_greeting_if_not_exists(greeting_message)
queue = None
if queue_name:
queue_service = QueueService(self.db_session)
queue = queue_service.get_queue_by_name(queue_name)
if queue is None:
raise InvalidRoutingConfigException("invalid queue name")
if workflow_name is None:
raise InvalidRoutingConfigException("admin mismatch")
workflow = None
if workflow_name:
workflow_service = WorkflowService(self.db_session)
workflow = workflow_service.get_workflow_by_name(workflow_name)
if workflow is None:
raise InvalidRoutingConfigException("invalid workflow name")
if workflow.partner is not None and queue is not None:
if workflow.partner != queue.partner:
raise InvalidRoutingConfigException("queue and workflow partner mismatch")
self.add_inbound_routing(
contact_type=ContactType[contact_type],
inbound_target=inbound_target,
workflow=workflow,
greeting=greeting,
active=active,
admin=admin,
initial_queue=queue
)
def add_inbound_routing(self, contact_type: ContactType, inbound_target: str, workflow: Optional[Workflow],
greeting: Greeting, active: bool = True, admin: bool = False,
initial_queue: Queue = None) -> InboundRouting:
call_routing = InboundRouting(
contact_type=contact_type,
inbound_target=inbound_target,
workflow=workflow,
active=active,
admin=admin,
greeting=greeting,
operating_mode="normal",
initial_queue=initial_queue
)
self.db_session.add(call_routing)
self.db_session.commit()
return call_routing
def add_pstn_routing(self, queue: Queue, priority: int, phone_number: str, phone_system: str) -> TransferRouting:
return self.add_transfer_routing(queue, priority, TransferType.PSTN, phone_number, phone_system)
def add_sip_routing(self, queue: Queue, priority: int, sip_address: str, phone_system: str) -> TransferRouting:
return self.add_transfer_routing(queue, priority, TransferType.SIP, sip_address, phone_system)
def add_flex_routing(self, queue: Queue, priority: int, task_sid: str) -> TransferRouting:
return self.add_transfer_routing(queue, priority, TransferType.INTERNAL, task_sid, "twilio")
def add_queue_transfer_routing(self, queue: Queue, priority: int, destination_queue_name: str):
return self.add_transfer_routing(queue, priority, TransferType.QUEUE, destination_queue_name, "ivr-gateway")
def add_transfer_routing(self, queue: Queue, priority: int, transfer_type: str, destination: str,
system: str) -> TransferRouting:
transfer_routing = TransferRouting(
transfer_type=transfer_type,
destination=destination,
destination_system=system,
operating_mode="normal",
queue=queue,
priority=priority
)
self.db_session.add(transfer_routing)
self.db_session.commit()
return transfer_routing
def add_ani_shortcut_to_db(self, phone_number: str, shortcut_number: str, name: str = None,
customer: str = None) -> AdminCallFrom:
admin_call_from = AdminCallFrom(
full_number=phone_number,
short_number=shortcut_number,
name=name,
customer=customer
)
self.db_session.add(admin_call_from)
self.db_session.commit()
return admin_call_from
def add_dnis_shortcut(self, short_number: str, full_number: str) -> AdminCallTo:
admin_call_from_lookup = self.admin_service.find_shortcut_dnis(short_number)
if admin_call_from_lookup is not None:
return
dnis_shortcut = AdminCallTo(
short_number=short_number,
full_number=full_number
)
self.db_session.add(dnis_shortcut)
self.db_session.commit()
return dnis_shortcut
def _create_Iivr_greeting(self):
message = 'Thank you for calling <phoneme alphabet="ipa" ph="əˈvɑnt">Avant</phoneme>. ' \
'Please be advised that your call will be monitored or recorded for quality and training purposes.'
call_service = CallService(self.db_session)
return call_service.create_greeting_if_not_exists(message)
@click.command()
@click.option('--phone_number', prompt="Enter phone number (e.g. 14432351191)")
@click.option('--short_number', prompt="Short number the phone number should map to")
@click.option('--name', prompt="Name of phone number")
@click.option('--customer', prompt="Customer name or id")
def add_ani_shortcut(self, phone_number, short_number, name, customer) -> None:
"""
flask admin add-phone-number
:param phone_number:
:param short_id:
:param name:
:param customer:
:return:
"""
"""Creates an admin phone number"""
admin_call_from_lookup = self.admin_service.find_shortcut_ani(short_number)
if admin_call_from_lookup is not None:
click.echo(
f"Short id {admin_call_from_lookup.short_number} is already used for {admin_call_from_lookup.full_number}")
return
admin_call_from = self.add_ani_shortcut_to_db(phone_number, short_number, name=name,
customer=customer)
click.echo(
f"Your shortcut for {admin_call_from.short_number} to {admin_call_from.full_number} has been created.")
@click.command()
@click.option("--workflow-name", prompt="What workflow would you like to update? (e.g. Iivr.workflow_name)",
type=click.STRING)
@click.option("--workflow-tag", prompt="What would you like to tag this workflow config? (e.g. 1.0.0)",
type=click.STRING)
@click.option("--partner", type=click.STRING)
def add_workflow(self, workflow_name, workflow_tag, partner) -> None:
step_tree = workflow_step_tree_registry.get(workflow_name)
if step_tree is None:
click.echo("Step tree for specified workflow does not exist")
return
workflow = self.workflow_service.get_workflow_by_name(workflow_name)
if workflow is not None:
click.echo("Specified workflow already exists")
return
workflow = self.workflow_service.create_workflow(workflow_name, step_tree, tag=workflow_tag, partner=partner)
click.echo(f"Added {workflow}")
@click.command()
@click.option("--queue-config-file", prompt="Config file to use?")
def setup_queues_from_config_file(self, queue_config_file) -> None:
with open(queue_config_file) as config_file:
queues = json.load(config_file)
for queue_dict in queues:
queue = self.configure_queue(queue_dict)
click.echo(f"Added queue: {queue}")
@click.command()
@click.option("--greeting-message", prompt="Enter the greeting message to associate with the inbound routing.",
type=click.STRING)
@click.option("--inbound-target", prompt="What is the target associated with the inbound routing?",
type=click.STRING)
def update_greeting_message(self, greeting_message: str, inbound_target: str):
call_service = CallService(self.db_session)
routing = call_service.get_routing_for_number(inbound_target)
if not routing:
raise MissingInboundRoutingException(f"Resource not found for inbound-target: {inbound_target}")
current_greeting = routing.greeting
if current_greeting.message != greeting_message:
new_greeting = call_service.create_greeting_if_not_exists(greeting_message)
routing.greeting = new_greeting
self.db_session.add(routing)
self.db_session.commit()
click.echo(f"Set greeting message for {inbound_target} to: {greeting_message}")
else:
click.echo(f"The greeting message for {inbound_target} is already set to: {greeting_message}")
@click.command()
@click.option("--config-file-path", prompt="Path to the updated message config file?", type=click.STRING)
def update_greeting_message_from_config(self, config_file_path: str):
call_service = CallService(self.db_session)
with open(config_file_path) as config_file:
message_updates = json.load(config_file)
for message_update in message_updates:
greeting_message = message_update.get("greeting_message", None)
new_greeting = call_service.create_greeting_if_not_exists(greeting_message)
if not greeting_message:
click.echo(f"No greeting message found in config file at {config_file_path}")
return
routes = message_update.get("routes", [])
for inbound_target in routes:
routing = call_service.get_routing_for_number(inbound_target)
if not routing:
raise MissingInboundRoutingException(f"Resource not found for inbound-target: {inbound_target}")
routing.greeting = new_greeting
self.db_session.add(routing)
self.db_session.commit()
click.echo("Greeting message configs updated.")
|
# frozen_string_literal: true
##
# Retrieve weather data from OpenWeather API
#
class OpenWeather
HEADERS = { 'Content-type' => 'application/json; charset=UTF-8' }.freeze
URI = URI('https://api.openweathermap.org').freeze
class Error < StandardError; end
attr_reader :location
def initialize(location)
@location = location
end
def weather_data_str
case response
when Net::HTTPSuccess
response.body
else
raise Error, response
end
end
private
def api_key
Rails.application.credentials.open_weather_api_key
end
def response
@response ||= Net::HTTP.start(URI.host, use_ssl: true) do |http|
# https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&exclude={part}&appid={API key}
path = "/data/2.5/weather?lat=#{@location.latitude}&lon=#{@location.longitude}&appid=#{api_key}"
http.get(path, HEADERS)
end
end
end
|
package main
import (
"fmt"
"os"
"time"
"github.com/go-resty/resty/v2"
"github.com/rs/zerolog"
"github.com/urfave/cli/v2"
)
var (
restyClient = resty.New()
logger = zerolog.New(zerolog.ConsoleWriter{
Out: os.Stdout,
TimeFormat: time.RFC3339,
}).With().Timestamp().Logger()
)
func main() {
app := cli.App{
Name: "dkv_cli",
Version: "1.0.0",
Usage: "CLI to operate with distributed KV storage",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "endpoint",
Usage: "Endpoint of DKV to operate with",
Value: "localhost:8001",
},
},
Commands: []*cli.Command{
{
Name: "get",
Aliases: []string{"g"},
Usage: "Get KV for specified key",
Action: get,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "key",
Aliases: []string{"k"},
Required: true,
},
},
},
{
Name: "put",
Aliases: []string{"p"},
Usage: "Put/update KV",
Action: put,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "key",
Aliases: []string{"k"},
Required: true,
},
&cli.StringFlag{
Name: "value",
Aliases: []string{"val", "v"},
Required: true,
},
},
},
},
}
if err := app.Run(os.Args); err != nil {
logger.Fatal().
Err(fmt.Errorf("running CLI: %w", err)).
Send()
}
}
|
/*
* Copyright 2015-2020 OpenCB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opencb.commons.monitor;
public class HealthCheckDependency {
// 'Url of the service'
private String url;
private HealthCheckResponse.Status status;
// 'Type of dependency. For example: `REST API`'
private String type;
// 'Description of the dependency. For example: `Exomiser`'
private String description;
private Object additionalProperties;
public HealthCheckDependency(String url, HealthCheckResponse.Status status, String type, String description,
Object additionalProperties) {
this.url = url;
this.status = status;
this.type = type;
this.description = description;
this.additionalProperties = additionalProperties;
}
public String getUrl() {
return url;
}
public HealthCheckDependency setUrl(String url) {
this.url = url;
return this;
}
public HealthCheckResponse.Status getStatus() {
return status;
}
public HealthCheckDependency setStatus(HealthCheckResponse.Status status) {
this.status = status;
return this;
}
public String getType() {
return type;
}
public HealthCheckDependency setType(String type) {
this.type = type;
return this;
}
public String getDescription() {
return description;
}
public HealthCheckDependency setDescription(String description) {
this.description = description;
return this;
}
public Object getAdditionalProperties() {
return additionalProperties;
}
public HealthCheckDependency setAdditionalProperties(Object additionalProperties) {
this.additionalProperties = additionalProperties;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("HealthCheckDependency{");
sb.append("url='").append(url).append('\'');
sb.append(", status='").append(status).append('\'');
sb.append(", type='").append(type).append('\'');
sb.append(", description='").append(description).append('\'');
sb.append(", additionalProperties=").append(additionalProperties);
sb.append('}');
return sb.toString();
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Boonchai Security - Main</title>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script> -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.10.1/dist/sweetalert2.all.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Kanit&display=swap');
body {
background-color: #F6F9FE;
font-family: 'Kanit', sans-serif;
}
#door-container,
#door-status {
text-align: center;
padding: 20px;
margin: 10px;
/* border: 1px solid #b3b3b3; */
border-radius: 5px;
background-color: #ffffff;
}
#activity-container {
padding: 20px;
margin: 10px;
border: 1px solid #b3b3b3;
border-radius: 5px;
background-color: #ffffff;
}
#topic {
text-align: center;
}
hr.rounded {
border-top: 4px solid #000000;
border-radius: 2px;
}
.card {
border-radius: 8px;
box-shadow: 0 15px 15px rgba(0, 0, 0, 0.1);
margin: 10px;
}
.backdrop {
padding: 20px;
background-color: #003f66;
color: #ffffff;
border-radius: 0px 0px 10px 10px;
box-shadow: 0 19px 17px rgba(0, 0, 0, 0.1);
}
</style>
</head>
<body onload="login_status()">
<nav class="navbar navbar-expand-lg navbar-dark backdrop">
<div class="container-fluid">
<a class="navbar-brand" href="#"><img src="https://cdn-icons-png.flaticon.com/512/1160/1160312.png"
width="40" height="40"> Boonchai Security</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav"
aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse justify-content-end" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="tables" id="tables">Tables</a>
</li>
<li class="nav-item">
<a class="nav-link" id="logout">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container mt-4">
<div class="row justify-content-center">
<div class="col-md">
<h1>Welcome: <span id="fname"></span> <span id="lname"></span> <img
src="https://cdn-icons-png.flaticon.com/512/219/219986.png" width="40" height="40"></h1>
<div style="background-color: #444c52; color: white; border-radius: 8px; width: 400px; height: 30px;">
<h4> Current Time: <span id="currentTime"> </span></h4>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<hr class="rounded">
</div>
<div class="container mt-4">
<div
style="background: linear-gradient(to right, hsl(203, 100%, 20%), #0074bc); color: white; border-radius: 10px; width: 370px; height: 50px;">
<h1> Room Management </h1>
</div><br />
<div class="row justify-content-center align-items-stretch">
<div class="col-md-5 card">
<div id="door-container">
<h2><img src="https://icons.veryicon.com/png/o/miscellaneous/admin-dashboard-flat-multicolor/setting-19.png"
width="35" height="40">Control Door</h2><br>
<button class="btn btn-primary" style="font-size: large;" onclick="showSuccessAlert()">Open
Door</button>
<button class="btn btn-danger" style="font-size: large;" onclick="showcloseAlert()">Close
Door</button>
</div>
</div>
<div class="col-md-5 card">
<div id="door-status">
<h2><img src="https://cdn-icons-png.flaticon.com/512/4785/4785997.png" width="40" height="40">Door
Status</h2>
<h4><span id="doorStatus" class="text-danger"></span></h4>
<h6>Occupied By: <span id="occupiedBy"></span></h6>
</div>
</div>
</div>
</div>
<div class="container mt-4">
<div
style="background: linear-gradient(to right, #003f66, #0074bc); color: white; border-radius: 10px; width: 300px; height: 50px;">
<h1> Lastest Activity</h1>
</div><br />
<div class="row justify-content-center align-items-stretch">
<div class="col-md-5 card">
<div id="door-container">
<h2><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSUGmGx6vSNGJl2x1mk0zgIGNdq5PDucvETav0tTRB8TACQU5PXy7GLm5boc53yIVZP0Vc&usqp=CAU"
width="35" height="40">Last Open History</h2>
<h4>Last Time: <span id="openTime"></span></h4>
<h6>Occupied By: <span id="openBy"></span></h6>
</div>
</div>
<div class="col-md-5 card">
<div id="door-container">
<h2><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQDZFxZQJux0D1iYi_4OEFixmm7rlCWHca3SQ&usqp=CAU"
width="35" height="40">Last Close History</h2>
<h4>Last Time: <span id="closeTime"></span></h4>
<h6>Occupied By: <span id="closeBy"></span></h6>
</div>
</div>
</div>
</div>
<script>
// Assume door is initially closed
var isDoorOpen = false;
const url = "http://192.168.182.37:5000"
function showSuccessAlert() {
Swal.fire({
title: "Do you want open the door?",
showCancelButton: true,
confirmButtonText: "Open",
confirmButtonColor: "#19b33d",
icon: "question",
allowOutsideClick: false
}).then((result) => {
console.log(sessionStorage.getItem('uid'));
if (result.isConfirmed) {
fetch(url + '/toggle_door', {
method: "POST",
body: JSON.stringify({
"uid": sessionStorage.getItem('uid'),
"state": true
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => {
response.json()
if (response.status == 200) {
Swal.fire("Door Opened!", "", "success");
setTimeout(function () {
location.reload()
}, 2000)
} else {
Swal.fire("Error!", "", "error")
setTimeout(function () {
location.reload()
}, 2000)
}
})
.then(json => {
console.log(json)
})
}
});
}
function showcloseAlert() {
Swal.fire({
title: "Do you want close the door?",
showCancelButton: true,
confirmButtonText: "Close",
confirmButtonColor: "#d92121",
icon: "question"
}).then((result) => {
console.log(sessionStorage.getItem('uid'));
if (result.isConfirmed) {
fetch(url + '/toggle_door', {
method: "POST",
body: JSON.stringify({
"uid": sessionStorage.getItem('uid'),
"state": false
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => {
response.json()
if (response.status == 200) {
Swal.fire("Door Closed!", "", "success");
setTimeout(function () {
location.reload()
}, 2000)
} else {
Swal.fire("Error!", "", "error");
setTimeout(function () {
location.reload()
}, 2000)
}
})
.then(json => {
console.log(json)
})
}
// }
});
}
// Function to open the door
function openDoor() {
var doorElement = document.getElementById('door');
doorElement.textContent = 'Open';
doorElement.classList.remove('text-danger');
doorElement.classList.add('text-success');
isDoorOpen = true;
console.log('Door opened');
}
// Function to close the door
function closeDoor() {
var doorElement = document.getElementById('door');
doorElement.textContent = 'Closed';
doorElement.classList.remove('text-success');
doorElement.classList.add('text-danger');
isDoorOpen = false;
console.log('Door closed');
}
// // Event handlers for the buttons
// document.getElementById('open-door-btn').addEventListener('click', function () {
// if (!isDoorOpen) {
// openDoor();
// }
// });
// document.getElementById('close-door-btn').addEventListener('click', function () {
// if (isDoorOpen) {
// closeDoor();
// }
// });
document.getElementById('logout').addEventListener('click', function () {
sessionStorage.clear();
window.location.href = "/loginform";
});
var fname = sessionStorage.getItem('fname');
var lname = sessionStorage.getItem('lname');
document.getElementById('fname').textContent = fname;
document.getElementById('lname').textContent = lname;
function getCurrentTime() {
const currentTime = new Date();
document.getElementById('currentTime').textContent = currentTime.toLocaleString();
}
let get_last = () => {
let url = "http://192.168.182.37:5000/loglast";
fetch(url)
.then(response => response.json())
.then(json => {
console.log(json);
if (json.message != 'Internal Server Error') {
let entry = json;
let open = entry.open;
let opened_by = entry.opened_by;
let close = entry.close;
let close_by = entry.closed_by;
document.getElementById("openTime").textContent = open;
document.getElementById("openBy").textContent = opened_by;
document.getElementById("closeTime").textContent = close;
document.getElementById("closeBy").textContent = close_by;
} else {
console.log("No entries in the JSON array");
document.getElementById("openTime").textContent = "No Activity Recorded."
document.getElementById("openBy").textContent = "No Activity Recorded."
document.getElementById("closeTime").textContent = "No Activity Recorded."
document.getElementById("closeBy").textContent = "No Activity Recorded."
}
})
};
let doorStatus = () => {
let url = "http://192.168.182.37:5000/door_status";
fetch(url)
.then(response => response.json())
.then(json => {
let entry = json;
let status = entry.status;
let occupied_by = entry.occupied_by;
document.getElementById("doorStatus").textContent = status;
document.getElementById("occupiedBy").textContent = occupied_by;
})
};
function login_status() {
if (sessionStorage.getItem('fname') == null) {
window.location.href = "/loginform";
}
console.log();
}
getCurrentTime();
setInterval(getCurrentTime, 1000);
get_last();
doorStatus();
</script>
</body>
</html>
|
// Copyright 2020 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "dawn_native/D3D12Backend.h"
#include "dawn_native/d3d12/BufferD3D12.h"
#include "dawn_native/d3d12/DeviceD3D12.h"
#include "dawn_native/d3d12/ResidencyManagerD3D12.h"
#include "tests/DawnTest.h"
#include "utils/WGPUHelpers.h"
#include <vector>
constexpr uint32_t kRestrictedBudgetSize = 100000000; // 100MB
constexpr uint32_t kDirectlyAllocatedResourceSize = 5000000; // 5MB
constexpr uint32_t kSuballocatedResourceSize = 1000000; // 1MB
constexpr uint32_t kSourceBufferSize = 4; // 4B
constexpr wgpu::BufferUsage kMapReadBufferUsage =
wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
constexpr wgpu::BufferUsage kMapWriteBufferUsage =
wgpu::BufferUsage::CopySrc | wgpu::BufferUsage::MapWrite;
constexpr wgpu::BufferUsage kNonMappableBufferUsage = wgpu::BufferUsage::CopyDst;
class D3D12ResidencyTests : public DawnTest {
protected:
void TestSetUp() override {
DAWN_SKIP_TEST_IF(UsesWire());
// Restrict Dawn's budget to create an artificial budget.
dawn_native::d3d12::Device* d3dDevice =
reinterpret_cast<dawn_native::d3d12::Device*>(device.Get());
d3dDevice->GetResidencyManager()->RestrictBudgetForTesting(kRestrictedBudgetSize);
// Initialize a source buffer on the GPU to serve as a source to quickly copy data to other
// buffers.
constexpr uint32_t one = 1;
mSourceBuffer =
utils::CreateBufferFromData(device, &one, sizeof(one), wgpu::BufferUsage::CopySrc);
}
std::vector<wgpu::Buffer> AllocateBuffers(uint32_t bufferSize,
uint32_t numberOfBuffers,
wgpu::BufferUsage usage) {
std::vector<wgpu::Buffer> buffers;
for (uint64_t i = 0; i < numberOfBuffers; i++) {
buffers.push_back(CreateBuffer(bufferSize, usage));
}
return buffers;
}
bool CheckIfBufferIsResident(wgpu::Buffer buffer) const {
dawn_native::d3d12::Buffer* d3dBuffer =
reinterpret_cast<dawn_native::d3d12::Buffer*>(buffer.Get());
return d3dBuffer->CheckIsResidentForTesting();
}
bool CheckAllocationMethod(wgpu::Buffer buffer,
dawn_native::AllocationMethod allocationMethod) const {
dawn_native::d3d12::Buffer* d3dBuffer =
reinterpret_cast<dawn_native::d3d12::Buffer*>(buffer.Get());
return d3dBuffer->CheckAllocationMethodForTesting(allocationMethod);
}
bool IsUMA() const {
return reinterpret_cast<dawn_native::d3d12::Device*>(device.Get())->GetDeviceInfo().isUMA;
}
wgpu::Buffer CreateBuffer(uint32_t bufferSize, wgpu::BufferUsage usage) {
wgpu::BufferDescriptor descriptor;
descriptor.size = bufferSize;
descriptor.usage = usage;
return device.CreateBuffer(&descriptor);
}
static void MapReadCallback(WGPUBufferMapAsyncStatus status,
const void* data,
uint64_t,
void* userdata) {
ASSERT_EQ(WGPUBufferMapAsyncStatus_Success, status);
ASSERT_NE(nullptr, data);
static_cast<D3D12ResidencyTests*>(userdata)->mMappedReadData = data;
}
static void MapWriteCallback(WGPUBufferMapAsyncStatus status,
void* data,
uint64_t,
void* userdata) {
ASSERT_EQ(WGPUBufferMapAsyncStatus_Success, status);
ASSERT_NE(nullptr, data);
static_cast<D3D12ResidencyTests*>(userdata)->mMappedWriteData = data;
}
void TouchBuffers(uint32_t beginIndex,
uint32_t numBuffers,
const std::vector<wgpu::Buffer>& bufferSet) {
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
// Perform a copy on the range of buffers to ensure the are moved to dedicated GPU memory.
for (uint32_t i = beginIndex; i < beginIndex + numBuffers; i++) {
encoder.CopyBufferToBuffer(mSourceBuffer, 0, bufferSet[i], 0, kSourceBufferSize);
}
wgpu::CommandBuffer copy = encoder.Finish();
queue.Submit(1, ©);
}
wgpu::Buffer mSourceBuffer;
void* mMappedWriteData = nullptr;
const void* mMappedReadData = nullptr;
};
// Check that resources existing on suballocated heaps are made resident and evicted correctly.
TEST_P(D3D12ResidencyTests, OvercommitSmallResources) {
// Create suballocated buffers to fill half the budget.
std::vector<wgpu::Buffer> bufferSet1 = AllocateBuffers(
kSuballocatedResourceSize, ((kRestrictedBudgetSize / 2) / kSuballocatedResourceSize),
kNonMappableBufferUsage);
// Check that all the buffers allocated are resident. Also make sure they were suballocated
// internally.
for (uint32_t i = 0; i < bufferSet1.size(); i++) {
EXPECT_TRUE(CheckIfBufferIsResident(bufferSet1[i]));
EXPECT_TRUE(
CheckAllocationMethod(bufferSet1[i], dawn_native::AllocationMethod::kSubAllocated));
}
// Create enough directly-allocated buffers to use the entire budget.
std::vector<wgpu::Buffer> bufferSet2 = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kNonMappableBufferUsage);
// Check that everything in bufferSet1 is now evicted.
for (uint32_t i = 0; i < bufferSet1.size(); i++) {
EXPECT_FALSE(CheckIfBufferIsResident(bufferSet1[i]));
}
// Touch one of the non-resident buffers. This should cause the buffer to become resident.
constexpr uint32_t indexOfBufferInSet1 = 5;
TouchBuffers(indexOfBufferInSet1, 1, bufferSet1);
// Check that this buffer is now resident.
EXPECT_TRUE(CheckIfBufferIsResident(bufferSet1[indexOfBufferInSet1]));
// Touch everything in bufferSet2 again to evict the buffer made resident in the previous
// operation.
TouchBuffers(0, bufferSet2.size(), bufferSet2);
// Check that indexOfBufferInSet1 was evicted.
EXPECT_FALSE(CheckIfBufferIsResident(bufferSet1[indexOfBufferInSet1]));
}
// Check that resources existing on directly allocated heaps are made resident and evicted
// correctly.
TEST_P(D3D12ResidencyTests, OvercommitLargeResources) {
// Create directly-allocated buffers to fill half the budget.
std::vector<wgpu::Buffer> bufferSet1 = AllocateBuffers(
kDirectlyAllocatedResourceSize,
((kRestrictedBudgetSize / 2) / kDirectlyAllocatedResourceSize), kNonMappableBufferUsage);
// Check that all the allocated buffers are resident. Also make sure they were directly
// allocated internally.
for (uint32_t i = 0; i < bufferSet1.size(); i++) {
EXPECT_TRUE(CheckIfBufferIsResident(bufferSet1[i]));
EXPECT_TRUE(CheckAllocationMethod(bufferSet1[i], dawn_native::AllocationMethod::kDirect));
}
// Create enough directly-allocated buffers to use the entire budget.
std::vector<wgpu::Buffer> bufferSet2 = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kNonMappableBufferUsage);
// Check that everything in bufferSet1 is now evicted.
for (uint32_t i = 0; i < bufferSet1.size(); i++) {
EXPECT_FALSE(CheckIfBufferIsResident(bufferSet1[i]));
}
// Touch one of the non-resident buffers. This should cause the buffer to become resident.
constexpr uint32_t indexOfBufferInSet1 = 1;
TouchBuffers(indexOfBufferInSet1, 1, bufferSet1);
EXPECT_TRUE(CheckIfBufferIsResident(bufferSet1[indexOfBufferInSet1]));
// Touch everything in bufferSet2 again to evict the buffer made resident in the previous
// operation.
TouchBuffers(0, bufferSet2.size(), bufferSet2);
// Check that indexOfBufferInSet1 was evicted.
EXPECT_FALSE(CheckIfBufferIsResident(bufferSet1[indexOfBufferInSet1]));
}
// Check that calling MapReadAsync makes the buffer resident and keeps it locked resident.
TEST_P(D3D12ResidencyTests, AsyncMappedBufferRead) {
// Create a mappable buffer.
wgpu::Buffer buffer = CreateBuffer(4, kMapReadBufferUsage);
uint32_t data = 12345;
buffer.SetSubData(0, sizeof(uint32_t), &data);
// The mappable buffer should be resident.
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
// Create and touch enough buffers to use the entire budget.
std::vector<wgpu::Buffer> bufferSet = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kMapReadBufferUsage);
TouchBuffers(0, bufferSet.size(), bufferSet);
// The mappable buffer should have been evicted.
EXPECT_FALSE(CheckIfBufferIsResident(buffer));
// Calling MapReadAsync should make the buffer resident.
buffer.MapReadAsync(MapReadCallback, this);
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
while (mMappedReadData == nullptr) {
WaitABit();
}
// Touch enough resources such that the entire budget is used. The mappable buffer should remain
// locked resident.
TouchBuffers(0, bufferSet.size(), bufferSet);
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
// Unmap the buffer, allocate and touch enough resources such that the entire budget is used.
// This should evict the mappable buffer.
buffer.Unmap();
std::vector<wgpu::Buffer> bufferSet2 = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kMapReadBufferUsage);
TouchBuffers(0, bufferSet2.size(), bufferSet2);
EXPECT_FALSE(CheckIfBufferIsResident(buffer));
}
// Check that calling MapWriteAsync makes the buffer resident and keeps it locked resident.
TEST_P(D3D12ResidencyTests, AsyncMappedBufferWrite) {
// Create a mappable buffer.
wgpu::Buffer buffer = CreateBuffer(4, kMapWriteBufferUsage);
// The mappable buffer should be resident.
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
// Create and touch enough buffers to use the entire budget.
std::vector<wgpu::Buffer> bufferSet1 = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kMapReadBufferUsage);
TouchBuffers(0, bufferSet1.size(), bufferSet1);
// The mappable buffer should have been evicted.
EXPECT_FALSE(CheckIfBufferIsResident(buffer));
// Calling MapWriteAsync should make the buffer resident.
buffer.MapWriteAsync(MapWriteCallback, this);
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
while (mMappedWriteData == nullptr) {
WaitABit();
}
// Touch enough resources such that the entire budget is used. The mappable buffer should remain
// locked resident.
TouchBuffers(0, bufferSet1.size(), bufferSet1);
EXPECT_TRUE(CheckIfBufferIsResident(buffer));
// Unmap the buffer, allocate and touch enough resources such that the entire budget is used.
// This should evict the mappable buffer.
buffer.Unmap();
std::vector<wgpu::Buffer> bufferSet2 = AllocateBuffers(
kDirectlyAllocatedResourceSize, kRestrictedBudgetSize / kDirectlyAllocatedResourceSize,
kMapReadBufferUsage);
TouchBuffers(0, bufferSet2.size(), bufferSet2);
EXPECT_FALSE(CheckIfBufferIsResident(buffer));
}
// Check that overcommitting in a single submit works, then make sure the budget is enforced after.
TEST_P(D3D12ResidencyTests, OvercommitInASingleSubmit) {
// Create enough buffers to exceed the budget
constexpr uint32_t numberOfBuffersToOvercommit = 5;
std::vector<wgpu::Buffer> bufferSet1 = AllocateBuffers(
kDirectlyAllocatedResourceSize,
(kRestrictedBudgetSize / kDirectlyAllocatedResourceSize) + numberOfBuffersToOvercommit,
kNonMappableBufferUsage);
// Touch the buffers, which creates an overcommitted command list.
TouchBuffers(0, bufferSet1.size(), bufferSet1);
// Ensure that all of these buffers are resident, even though we're exceeding the budget.
for (uint32_t i = 0; i < bufferSet1.size(); i++) {
EXPECT_TRUE(CheckIfBufferIsResident(bufferSet1[i]));
}
// Allocate another set of buffers that exceeds the budget.
std::vector<wgpu::Buffer> bufferSet2 = AllocateBuffers(
kDirectlyAllocatedResourceSize,
(kRestrictedBudgetSize / kDirectlyAllocatedResourceSize) + numberOfBuffersToOvercommit,
kNonMappableBufferUsage);
// Ensure the first <numberOfBuffersToOvercommit> buffers in the second buffer set were evicted,
// since they shouldn't fit in the budget.
for (uint32_t i = 0; i < numberOfBuffersToOvercommit; i++) {
EXPECT_FALSE(CheckIfBufferIsResident(bufferSet2[i]));
}
}
TEST_P(D3D12ResidencyTests, SetExternalReservation) {
// Set an external reservation of 20% the budget. We should succesfully reserve the amount we
// request.
uint64_t amountReserved = dawn_native::d3d12::SetExternalMemoryReservation(
device.Get(), kRestrictedBudgetSize * .2, dawn_native::d3d12::MemorySegment::Local);
EXPECT_EQ(amountReserved, kRestrictedBudgetSize * .2);
// If we're on a non-UMA device, we should also check the NON_LOCAL memory segment.
if (!IsUMA()) {
amountReserved = dawn_native::d3d12::SetExternalMemoryReservation(
device.Get(), kRestrictedBudgetSize * .2, dawn_native::d3d12::MemorySegment::NonLocal);
EXPECT_EQ(amountReserved, kRestrictedBudgetSize * .2);
}
}
DAWN_INSTANTIATE_TEST(D3D12ResidencyTests, D3D12Backend());
|
import React, { useState } from "react";
import "./Mega.css";
// eslint-disable-next-line import/no-anonymous-default-export
export default props => {
function gerarNumero(qtd) {
const numeros = Array(qtd)
.fill(0)
.reduce((nums) => {
const novoNumero = gerarNumeroNaoContido(1, 60, nums)
return [...nums, novoNumero]
}, [])
.sort((n1, n2) => n1 - n2)
return numeros
}
console.log(gerarNumero(7))
function gerarNumeroNaoContido(min, max, array) {
const aleatorio = parseInt(Math.random() * (max + 1 - min) + min)
return array.includes(aleatorio) ? gerarNumeroNaoContido(min, max, array) : aleatorio
}
const [qtd, setQtd] = useState(props.qtd || 6)
const numerosIniciais = gerarNumero(qtd)
const [numeros, setNumeros] = useState(numerosIniciais)
return (
<div className="Mega">
<h2>Mega</h2>
<h3>{numeros.join(' ')}</h3>
<div>
<label>Quantidade de Números</label>
<input type="number" value={qtd}
min="6"
max="15"
onChange={(e) => {
setQtd(+e.target.value)
setNumeros(gerarNumero(+e.target.value))
}
} />
</div>
<button onClick={_ => setNumeros(gerarNumero(qtd))}>Gerar Números</button>
</div>
)
}
|
/*
* @lc app=leetcode.cn id=334 lang=java
*
* [334] 递增的三元子序列
*
* https://leetcode.cn/problems/increasing-triplet-subsequence/description/
*
* algorithms
* Medium (43.29%)
* Likes: 610
* Dislikes: 0
* Total Accepted: 103.4K
* Total Submissions: 238.7K
* Testcase Example: '[1,2,3,4,5]'
*
* 给你一个整数数组 nums ,判断这个数组中是否存在长度为 3 的递增子序列。
*
* 如果存在这样的三元组下标 (i, j, k) 且满足 i < j < k ,使得 nums[i] < nums[j] < nums[k] ,返回
* true ;否则,返回 false 。
*
*
*
* 示例 1:
*
*
* 输入:nums = [1,2,3,4,5]
* 输出:true
* 解释:任何 i < j < k 的三元组都满足题意
*
*
* 示例 2:
*
*
* 输入:nums = [5,4,3,2,1]
* 输出:false
* 解释:不存在满足题意的三元组
*
* 示例 3:
*
*
* 输入:nums = [2,1,5,0,4,6]
* 输出:true
* 解释:三元组 (3, 4, 5) 满足题意,因为 nums[3] == 0 < nums[4] == 4 < nums[5] == 6
*
*
*
*
* 提示:
*
*
* 1 <= nums.length <= 5 * 10^5
* -2^31 <= nums[i] <= 2^31 - 1
*
*
*
*
* 进阶:你能实现时间复杂度为 O(n) ,空间复杂度为 O(1) 的解决方案吗?
*
*/
// @lc code=start
class Solution {
public boolean increasingTriplet(int[] nums) {
int first = nums[0];
int second = Integer.MAX_VALUE;
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
if (num > second) {
return true;
} else if (num > first) {
second = num;
} else {
first = num;
}
}
return false;
}
}
// @lc code=end
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form 에 대해서 알아봅니다.-1</title>
<style type="text/css">
div#container {
border: solid 0px gray;
width: 30%;
margin: 0 auto;
}
form {
margin-top: 100px;
}
legend {
font-size: 20pt;
}
label {
display: inline-block;
width : 150px;
}
ul {
/* border: solid 1px red; */
list-style-type: none;
padding-left: 0;
}
li {
line-height: 30px;
}
input.btn {
width: 100px;
height: 40px;
margin: 20px 0 0 40px;
font-size: 16pt;
cursor: pointer;
color: #fff;
}
input[type="submit"] {
background-color: #001a66;
}
/* input태그인데 속성값이 submit인 거 */
input[type="reset"] {
background-color: #990000;
}
</style>
</head>
<body>
<div id="container">
<form action="">
<!-- <fieldset> 태그는 폼을 그룹핑(묶어주는 것)하는 역할 -->
<fieldset>
<!-- <legend> 태그는 fieldset 에 대한 제목을 지정하는 것이다. -->
<legend>프로젝트 정보</legend>
<ul>
<li>
<label for="prjname">프로젝트명</label>
<input type="text" id="prjname" size="20" maxlength="30" autofocus placeholder="예: 인사관리프로젝트" required/>
<!-- autofocus : 페이지로드시 자동 포커스 지정
placeholder="예: 인사관리프로젝트" 은 예시로 미리 적어주는 것-->
</li>
<li>
<label for="priority">중요도</label>
<input type="range" id="priority" size="20" min="0" max="10" step="1" value="5"/>
<!-- 최소 0 최대 10 단계별수치1 기본값5 지정 -->
</li>
<li>
<label for="estimatehours">완료예상시간</label>
<input type="number" id="estimatehours" min="1" max="1000" step="1" value="10" />
<!-- number : 숫자필드 -->
</li>
<li>
<label for="startdate">시작날짜</label>
<input type="date" id="startdate" />
<!-- date : 날짜필드 -->
</li>
<li>
<label for="month">월</label>
<input type="month" id="month" />
<!-- month : 월단위 날짜필드 -->
</li>
<li>
<label for="week">주</label>
<input type="week" id="week" />
<!-- week : 주단위 날짜필드 -->
</li>
<li>
<label for="starttime">시작시간</label>
<input type="time" id="starttime" />
<!-- time : 시간필드 -->
</li>
<li>
<label for="email">이메일</label>
<input type="email" id="email" required/>
<!-- email : 이메일필드 -->
</li>
<li>
<label for="url">URL</label>
<input type="url" id="url" required/>
<!-- url : url 필드 -->
</li>
<li>
<label for="search">검색</label>
<input type="search" id="search" />
<!-- search : search 필드 -->
</li>
<li>
<label for="projectcolor">프로젝트 색상</label>
<input type="color" id="projectcolor" />
<!-- color : 색상 필드 -->
</li>
<li>
<input type="submit" value="전송" class="btn" />
<input type="reset" value="취소" class="btn" />
<!-- 반드시 form 태그 안에 써야 함!!!!!!! -->
</li>
</ul>
</fieldset>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>form 에 대해서 알아봅니다.-2</title>
<style type="text/css">
body {
/* border: solid 1px gray; */
margin: 0;
padding: 0;
font-family: Arial, "MS Trebuchet", sans-serif;
word-break: break-all; /* 공백없이 영어로만 되어질 경우 해당구역을 빠져나가므로 이것을 막기위해서 사용한다. */
}
div#container {
border: solid 0px gray;
width: 40%;
margin: 0 auto;
}
form {
margin-top: 100px;
}
legend {
font-size: 20pt;
}
label.title {
display: inline-block;
width : 150px;
color: navy;
font-weight: bold;
}
ul {
/* border: solid 1px red; */
list-style-type: none;
padding-left: 0;
}
li {
line-height: 40px;
}
input.myinput {
height: 20px;
}
input.btn {
width: 100px;
height: 40px;
margin: 20px 0 0 40px;
font-size: 16pt;
cursor: pointer;
color: #fff;
border-radius: 10%; /* 사각형을 깎음 */
}
input[type="radio"] {
margin-right: 20px;
}
/*
input:radio {
margin-right: 100px;
}
*/
/* 라디오 요소에 체크를 했을 경우 라디오 요소의 테두리를 오렌지색으로 주겠다. */
input[type="radio"]:checked {
box-shadow: 0 0 0 3px orange;
}
/* 체크박스 요소에 체크를 했을 경우 체크박스 요소의 테두리를 분홍색으로 주겠다. */
input[type="checkbox"]:checked {
box-shadow: 0 0 0 3px pink;
}
/*
label[for="female"] {
padding-left: 50px;
}
*/
select {
width: 100px;
height: 25px;
}
select.myselect {
height: 25px;
}
input[type="submit"] {
background-color: #001a66;
}
/* input태그인데 속성값이 submit인 거 */
input[type="reset"] {
background-color: #990000;
}
</style>
</head>
<body>
<div id="container">
<form action="register.do">
<!-- <fieldset> 태그는 폼을 그룹핑(묶어주는 것)하는 역할 -->
<fieldset>
<!-- <legend> 태그는 fieldset 에 대한 제목을 지정하는 것이다. -->
<legend>회원가입정보</legend>
<ul>
<li>
<label for="userid" class="title">아이디</label>
<input type="text" id="userid" class="myinput" size="20" maxlength="20" autofocus required />
</li>
<li>
<label for="passwd1" class="title">암호</label>
<input type="password" id="passwd1" class="myinput" size="20" maxlength="20" required />
</li>
<li>
<label for="passwd2" class="title">암호확인</label>
<input type="password" id="passwd2" class="myinput" size="20" maxlength="20" required />
</li>
<li>
<label for="name" class="title">성명</label>
<input type="text" id="name" class="myinput" size="20" maxlength="20" required />
</li>
<li>
<label for="email" class="title">이메일</label>
<input type="email" id="email" class="myinput" size="20" maxlength="40" required placeholder="예:hongkd@gmail.com" />
</li>
<li>
<label class="title">성별</label>
<label for="male">남자</label><input type="radio" name="gender" id="male"/>
<label for="female">여자</label><input type="radio" name="gender" id="female" checked/>
<!-- name을 같은것을 줘야 같은 radio타입일때 택1이 가능 / checked 는 기본 체크설정-->
</li>
<li>
<label class="title">취미</label>
<label for="game">게임</label><input type="checkbox" name="hobby" id="game"/>
<label for="movie">영화감상</label><input type="checkbox" name="hobby" id="movie"/>
<label for="writing">글쓰기</label><input type="checkbox" name="hobby" id="writing"/>
<label for="music">음악감상</label><input type="checkbox" name="hobby" id="music"/>
</li>
<li>
<label class="title">최종학력</label>
<select>
<option>고졸</option>
<option selected>초대졸</option>
<option>대졸</option>
<option>대학원졸</option>
</select>
</li>
<li>
<label class="title">선호음식</label>
<select size="3" multiple> <!-- 3개를 보여주며 multiple로 다중선택 가능 -->
<option>짜장면</option>
<option>파스타</option>
<option>파타이</option>
<option>부대찌개</option>
<option>떡볶이</option>
<option>치킨</option>
</select>
</li>
<li>
<label class="title">선호프로그램</label>
<select>
<optgroup label="데이터베이스">
<option>Oracle</option>
<option>MSSQL</option>
<option>MySql</option>
</optgroup>
<optgroup label="개발언어">
<option>Java</option>
<option>JSP</option>
<option>Spring</option>
<option>C/C++</option>
</optgroup>
</select>
</li>
<li>
<label for="browsername" class="title" >웹브라우저</label>
<input list="browserType" id="browsername" />
<datalist id="browserType">
<option value="Chrome" />
<option value="Internet Explore" />
<option value="Firefox" />
<option value="Opera" />
<option value="Safari" />
</datalist>
</li>
<li>
<label for="addFile" class="title">파일첨부</label>
<input type="file" id="addFile" />
</li>
<li>
<label for="registerComment" class="title">가입인사말</label>
<textarea rows="5" cols="30" id="registerComment" ></textarea> <!-- 가로30 세로 5 초과시 스크롤-->
</li>
<li>
<input type="submit" value="확인" class="btn" />
<input type="reset" value="취소" class="btn" />
<!-- 반드시 form 태그 안에 써야 함!!!!!!! -->
</li>
</ul>
</fieldset>
</form>
</div>
</body>
</html>
|
#include <cw/opengl/GlfwInputTranslator.hpp>
#include <stdexcept>
#include <vector>
#include <algorithm>
#include <GLFW/glfw3.h>
#include <cw/Enforce.hpp>
#include <cw/core/UnifiedInputHandler.hpp>
#include <cw/core/Logger.hpp>
#include <cw/opengl/GlfwWindow.hpp>
namespace
{
const std::vector<int> VALID_SCROLL_KEYS =
{
GLFW_KEY_LEFT,
GLFW_KEY_RIGHT,
GLFW_KEY_UP,
GLFW_KEY_DOWN
};
}
namespace cw
{
namespace opengl
{
GlfwInputTranslator::GlfwInputTranslator(cw::core::UnifiedInputHandler & inputHandler)
: m_inputHandler(inputHandler)
, m_xMouseWheelPos(0)
{}
GlfwInputTranslator::~GlfwInputTranslator()
{}
void GlfwInputTranslator::registerCallbacks(GlfwWindow & window)
{
using namespace std::placeholders;
window.setKeyCallback(
std::bind(&GlfwInputTranslator::keyEvent, this, _1, _2));
window.setMouseButtonCallback(
std::bind(&GlfwInputTranslator::mouseButtonEvent, this, _1, _2));
window.setScrollCallback(
std::bind(&GlfwInputTranslator::mouseWheelEvent, this, _1, _2));
window.setCursorMovedCallback(
std::bind(&GlfwInputTranslator::mouseMoveEvent, this, _1, _2 ));
}
void GlfwInputTranslator::mouseMoveEvent(int x, int y)
{
m_mouseState.posX = x;
m_mouseState.posY = y;
}
void GlfwInputTranslator::mouseButtonEvent(int btn, int action)
{
// if (m_lastMouseX < 0 || m_lastMouseY < 0)
// {
// return;
// }
if ( GLFW_MOUSE_BUTTON_LEFT == btn )
{
if ( GLFW_PRESS == action )
{
m_mouseState.pressed = true;
}
if ( GLFW_RELEASE == action && m_mouseState.pressed )
{
m_inputHandler.clickedAt( m_mouseState.posX, m_mouseState.posY );
//m_mouseState.pressed = false;
}
}
}
void GlfwInputTranslator::mouseWheelEvent(double xOffset, double yOffset)
{
if ( xOffset > m_xMouseWheelPos )
{
m_inputHandler.zoom( core::UnifiedInputHandler::ZoomDir::IN );
}
else if ( xOffset < m_xMouseWheelPos )
{
m_inputHandler.zoom( core::UnifiedInputHandler::ZoomDir::OUT );
}
m_xMouseWheelPos = xOffset;
}
bool isScrollKey(int k)
{
return std::end(VALID_SCROLL_KEYS) !=
std::find( std::begin(VALID_SCROLL_KEYS), std::end(VALID_SCROLL_KEYS), k );
}
void GlfwInputTranslator::keyEvent(int key, int action)
{
if ( !isScrollKey(key) )
{
return;
}
if ( GLFW_PRESS == action )
{
LOG_DEBUG("PRESSED: ", key);
m_inputHandler.startScroll( keyToScrollDir(key) );
}
else if ( GLFW_RELEASE == action )
{
LOG_DEBUG("RELEASED: ", key);
m_inputHandler.stopScroll( keyToScrollDir(key) );
}
}
GlfwInputTranslator::ScrollDir GlfwInputTranslator::keyToScrollDir(int key) const
{
switch(key)
{
case GLFW_KEY_LEFT: return ScrollDir::LEFT;
case GLFW_KEY_RIGHT: return ScrollDir::RIGHT;
case GLFW_KEY_UP: return ScrollDir::UP;
case GLFW_KEY_DOWN: return ScrollDir::DOWN;
}
ENFORCE(false, "Cannot interpret key!");
throw "unreachable";
}
}
}
|
import axios from "../Config/axiosConfig";
import { asyncGetBills } from "./billActions";
import { asyncGetCustomers } from "./customerActions";
import { asyncGetproducts } from "./productActions";
export const LOG_IN = 'LOG_IN'
export const LOG_OUT = 'LOG_OUT'
export const SET_USER = 'SET_USER'
export const asyncUserLogin = (formData, navigate) => {
return (dispatch) => {
axios.post('/users/login', formData)
.then((response) => {
const result = response.data
if(result.hasOwnProperty('errors')){
console.log(result.message)
} else {
alert('Successfully Logged In')
localStorage.setItem('token', result.token)
console.log(result)
userLoggedIn(true)
console.log('isLoggedIn: ',Boolean(userLoggedIn))
navigate('/app/account')
axios.get('/users/account', { headers : { 'Authorization' : `Bearer ${localStorage.getItem('token')}` }})
.then((response) => {
const userDetails = response.data
console.log(userDetails)
dispatch(asyncGetAccountDetails(userDetails))
})
.catch((err) => {
console.log(err.message)
})
axios.get('/customers', { headers : { 'Authorization' : `Bearer ${localStorage.getItem('token')}` }})
.then((response) => {
const customerDetails = response.data
console.log(customerDetails)
dispatch(asyncGetCustomers(customerDetails))
})
.catch((err) => {
console.log(err.message)
})
axios.get('/products', {headers : { 'Authorization' : `Bearer ${localStorage.getItem('token')}`}})
.then((response) => {
const productDetails = response.data
console.log(productDetails)
dispatch(asyncGetproducts(productDetails))
})
.catch((err) => {
console.log(err.message)
})
axios.get('/bills', {headers : {'Authorization' : `Bearer ${localStorage.getItem('token')}`}})
.then((response) => {
const billsDetails = response.data
console.log(billsDetails)
dispatch(asyncGetBills(billsDetails))
})
.catch((err) => {
console.log(err.message)
})
}
})
.catch((err) => {
console.log(err.message)
})
}
}
export const asyncGetAccountDetails = () => {
return (dispatch) => {
axios.get('/users/account', {headers : {'Authorization' : `Bearer ${localStorage.getItem('token')}`}})
.then((response) => {
const result = response.data
dispatch(setUser(result))
})
.catch((err) => {
console.log(err.message)
})
}
}
export const userLoggedOut = () => {
return {
type: LOG_OUT
}
}
export const userLoggedIn = (data) => {
return {
type: LOG_IN,
payload: data
}
}
export const setUser = (data) => {
return {
type: SET_USER,
payload: {...data, isLoggedIn: true}
}
}
|
import 'package:flutter/material.dart';
class DefaultInput extends StatelessWidget {
final TextEditingController controller;
final String placeholder;
final double? height;
const DefaultInput(
{super.key,
required this.controller,
this.placeholder = "Enter...",
this.height});
@override
Widget build(BuildContext context) {
return Container(
height: height,
child: TextField(
minLines: 1,
maxLines: 3,
controller: controller,
style: const TextStyle(
color: Colors.black,
),
decoration: InputDecoration(
filled: true,
fillColor: const Color(0xFFF6F6F6),
hintText: placeholder,
hintStyle: const TextStyle(color: Colors.grey),
contentPadding: const EdgeInsets.fromLTRB(10, 0, 0, 10),
focusedBorder: const OutlineInputBorder(
borderSide: BorderSide.none,
),
enabledBorder: const OutlineInputBorder(
borderSide: BorderSide(color: Color(0xFFE8E8E8), width: 1.0),
borderRadius: BorderRadius.all(Radius.circular(10)),
),
),
),
);
}
}
|
package com.javarush.task.task14.task1408;
/*
Куриная фабрика
*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Solution {
public static void main(String[] args) {
Hen hen = HenFactory.getHen(Country.BELARUS);
System.out.println(hen.getDescription());
}
static class HenFactory {
static Hen getHen(String country) {
if (country.equals(Country.BELARUS)){
return new BelarusianHen();
} else if (country.equals(Country.MOLDOVA)) {
return new MoldovanHen();
} else if (country.equals(Country.RUSSIA)) {
return new RussianHen();
} else if (country.equals(Country.UKRAINE)) {
return new UkrainianHen();
}
return null;
}
}
}
|
package app.salo.przelewetarte.presentation.theme.ui
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import app.salo.przelewetarte.presentation.theme.Shapes
import app.salo.przelewetarte.presentation.theme.Typography
private val DarkColorPalette = darkColors(
primary = Green,
primaryVariant = DarkGreen,
secondary = Orange
)
private val LightColorPalette = lightColors(
primary = Green,
primaryVariant = DarkGreen,
secondary = Orange,
background = Background,
onPrimary = LightGreen,
onSecondary = LightOrange,
error = Error
/* Other default colors to override
surface = Color.White,
onBackground = Color.Black,
onSurface = Color.Black,
*/
)
@Composable
fun PrzelewetarteTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit
) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Typography,
shapes = Shapes,
content = content
)
}
|
// _mixins
// ========
@mixin backImage($image, $divHeight) {
background: url($image) no-repeat 50% 20% ;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
@media (min-width: 801px) {
height: $divHeight;
}
@media (max-width: 800px) {
height: $divHeight;
}
@media (max-width: 300px) {
height: $divHeight;
}
}
//==========
@mixin parlxImage($image, $divHeight) {
background: url($image) no-repeat;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
background-attachment: fixed;
background-position: center;
overflow: hidden;
-webkit-transition: all 0.3s ease-out;
-moz-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out;
@media only screen and (max-device-width: 1024px) {
background-attachment: scroll;
}
@media (min-width: 801px) {
height: $divHeight;
}
@media (max-width: 800px) {
height: $divHeight;
}
@media (max-width: 300px) {
height: $divHeight;
}
}
@mixin clearfix {
&:after {
content: "";
display: table;
clear: both;
}
}
@mixin animBoostrapMenuBttn($showWidth, $barColor) {
-webkit-transition: all 0.4s ease;
-moz-transition: all 0.4s ease;
transition: all 0.4s ease;
opacity: 0;
width: 15px;
height: 15px;
margin-top: 22.5px;
display: none;
user-select: none;
box-sizing: content-box;
cursor: pointer;
@media (max-width: $showWidth) {
opacity: 1;
display: inline-block;
}
.one,
.two,
.three {
width: 100%;
height: 2px;
background: $barColor;
margin-bottom: 3px;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
transition: all 0.3s;
backface-visibility: hidden;
-webkit-transform-style: preserve-3d;
}
.one,
.two {
transform: rotate3d(0, 0, 1, 0deg) translate3d(0, 0, 0);
}
&[aria-expanded="true"] {
.one {
transform: rotate3d(0, 0, 1, 45deg);
-webkit-transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
transform-origin: 0% 0%;
}
.two {
opacity: 0;
}
.three {
transform: rotate3d(0, 0, 1, -45deg);
-webkit-transform-origin: 0% 100%;
-moz-transform-origin: 0% 100%;
transform-origin: 0% 100%;
}
}
}
@mixin dividerSection($Bgc, $FontC) {
background-color: $Bgc;
padding: 8% 5%;
h2 {
color: $FontC;
font-family: $font2;
font-weight: 100;
font-size: 2.5em;
//letter-spacing: 0.1em;
line-height: 1.4em;
text-align: center;
margin-bottom: 1.5em;
span {
color: $lightGreen;
}
}
}
@mixin scrollHidden($color, $bgc, $bgo, $transformation, $transformPer, $transitionDur) {
color: $color;
background-color: rgba($bgc, $bgo);
opacity: 0;
-webkit-transform: $transformation + "(" + $transformPer + ")";
-moz-transform: $transformation + "(" + $transformPer + ")";
-ms-transform: $transformation + "(" + $transformPer + ")";
transform: $transformation + "(" + $transformPer + ")";
-webkit-transition: all $transitionDur;
-moz-transition: all $transitionDur;
-ms-transition: all $transitionDur;
transition: all $transitionDur;
&.showing {
opacity: 1;
-webkit-transform: $transformation + "(" + 0% + ")";
-moz-transform: $transformation + "(" + 0% + ")";
-ms-transform: $transformation + "(" + 0% + ")";
transform: $transformation + "(" + 0% + ")";
}
}
@mixin btnOne($color1, $color2, $breakPoint) {
display: block;
padding: 2% 1%;
width: 40%;
margin: 0 auto;
text-align: center;
text-decoration: none;
color: $color1;
border: 1px solid $color1;
transition: all 0.5s;
&:hover {
background-color: $color1;
color: $color2;
}
@media (max-width: $breakPoint) {
width: 100%;
}
}
|
<!-- -->
<template>
<div class="containerLay">
<h2>Rate 评分</h2>
<p>评分组件</p>
<h3>基础用法</h3>
<div class="demo">
<div class="block">
<span class="demonstration">默认不区分颜色</span>
<el-rate v-model="value1"></el-rate>
</div>
<div class="block">
<span class="demonstration">区分颜色</span>
<el-rate
v-model="value2"
:colors="colors">
</el-rate>
</div>
</div>
<h3>辅助文字</h3>
<p>用辅助文字直接地表达对应分数</p>
<div class="demo">
<el-rate
v-model="value3"
show-text>
</el-rate>
</div>
<h3>其它 icon</h3>
<p>当有多层评价时,可以用不同类型的 icon 区分评分层级</p>
<div class="demo">
<el-rate
v-model="value4"
:icon-classes="iconClasses"
void-icon-class="iconfont icon-shoucang"
:colors="['#99A9BF', '#F7BA2A', '#FF9900']">
</el-rate>
</div>
<h3>只读</h3>
<p>只读的评分用来展示分数,允许出现半星</p>
<div class="demo">
<el-rate
v-model="value5"
disabled
show-score
text-color="#ff9900"
score-template="{value}">
</el-rate>
</div>
</div>
</template>
<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
export default {
//import引入的组件需要注入到对象中才能使用
name:'Rate',
components: {},
data() {
//这里存放数据
return {
value1: null,
value2: null,
colors: ['#99A9BF', '#F7BA2A', '#FF9900'], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
value3: null,
value4: null,
iconClasses: ['icon-rate-face-1', 'icon-rate-face-2', 'icon-rate-face-3'], // 等同于 { 2: 'icon-rate-face-1', 4: { value: 'icon-rate-face-2', excluded: true }, 5: 'icon-rate-face-3' }
value5: 3.7
}
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
},
//生命周期 - 创建完成(可以访问当前this实例)
created() {
},
//生命周期 - 挂载完成(可以访问DOM元素)
mounted() {
},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.container h2 {color: #1f2f3d;font-weight: 400;font-size: 28px;}
.container p {color: #5e6d82;font-size: 14px;line-height: 1.5em;margin: 14px 0;}
.container h3 {color: #1f2f3d;margin: 55px 0 20px; font-size:22px; font-weight:400;}
.container .demo {border: 1px #ebebeb solid;border-radius: 3px;box-sizing: border-box;padding: 24px;}
</style>
|
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Box, Button, CircularProgress } from '@material-ui/core';
import { PeopleAltOutlined } from '@material-ui/icons';
import AddTeamMember from '../components/AddTeamMember';
import SingleMemberCard from '../components/SingleMemberCard';
import { getMembers } from '../redux/actions/members';
import { MemberInterface } from '../interfaces/index';
import {
TeamContainer,
HeaderContainer,
TeamListTitle,
ErrorMessage,
} from '../utils/styles';
interface Props {
setShowMaximumView: (showMaximumView: boolean) => void;
showMaximumView: boolean;
}
function TeamList(props: Props) {
const dispatch: any = useDispatch();
const { selectedData, loading, error } = useSelector(
(state: any) => state.membersReducer,
);
useEffect(() => {
dispatch(getMembers());
}, [dispatch]);
useEffect(() => {
if (selectedData.length > 5) props.setShowMaximumView(true);
if (selectedData.length <= 5) props.setShowMaximumView(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedData]);
if (loading) {
return (
<Box className="loading">
<CircularProgress color="primary" />
</Box>
);
}
if (error) {
return (
<Box className="error">
<ErrorMessage>Error Occured!</ErrorMessage>
</Box>
);
}
return (
<>
<HeaderContainer>
<TeamListTitle>Your team for this test</TeamListTitle>
<Button>
<Box mr={1}>Team page</Box>
<PeopleAltOutlined />
</Button>
</HeaderContainer>
<TeamContainer>
<AddTeamMember />
{selectedData
.slice(props.showMaximumView ? selectedData.length - 5 : 0)
.map((client: MemberInterface) => (
<SingleMemberCard
key={client.id}
id={client.id}
username={client.username}
role={client.role}
picture={client.picture}
/>
))}
</TeamContainer>
</>
);
}
export default TeamList;
|
import * as React from "react";
import "./index.css";
import Datafeed from "./api";
function getLanguageFromURL() {
const regex = new RegExp("[\\?&]lang=([^&#]*)");
const results = regex.exec(window.location.search);
return results === null ? null : decodeURIComponent(results[1].replace(/\+/g, " "));
}
export class TVChartContainer extends React.PureComponent {
static defaultProps = {
symbol: "BTC/USD",
interval: "15",
libraryPath: "/charting_library/",
// chartsStorageUrl: "https://sltv.grizzly.fi",
chartsStorageApiVersion: "1.1",
clientId: "trade.grizzly.fi",
userId: "trade.grizzly.fi",
fullscreen: false,
autosize: true,
studiesOverrides: {},
};
tvWidget = null;
constructor(props) {
super(props);
this.ref = React.createRef();
}
componentDidMount() {
const widgetOptions = {
symbol: this.props.symbol,
datafeed: Datafeed,
interval: this.props.interval,
theme: "dark",
container: this.ref.current,
library_path: this.props.libraryPath,
locale: getLanguageFromURL() || "en",
disabled_features: ["use_localstorage_for_settings", "header_symbol_search"],
// enabled_features: ["study_templates"],
charts_storage_url: this.props.chartsStorageUrl,
charts_storage_api_version: this.props.chartsStorageApiVersion,
client_id: this.props.clientId,
user_id: this.props.userId,
fullscreen: this.props.fullscreen,
autosize: this.props.autosize,
visible_plots_set: "ohlc",
studies_overrides: this.props.studiesOverrides,
custom_css_url: "./themed.css",
overrides: {
// "mainSeriesProperties.showCountdown": true,
"paneProperties.backgroundGradientStartColor": "#1f1f1f",
"paneProperties.backgroundGradientEndColor": "#1f1f1f",
"paneProperties.vertGridProperties.color": "#2b2b2b",
"paneProperties.horzGridProperties.color": "#2b2b2b",
// "symbolWatermarkProperties.transparency": 90,
// "scalesProperties.textColor": "#AAA",
"mainSeriesProperties.candleStyle.wickUpColor": "#0ecc83",
"mainSeriesProperties.candleStyle.wickDownColor": "#fa3c58",
},
time_frames: [
{ text: "1y", resolution: "1D", description: "1 Year" },
{ text: "6m", resolution: "240", description: "6 Months" },
{ text: "3m", resolution: "240", description: "3 Months" },
{ text: "1m", resolution: "60", description: "1 Month" },
{ text: "5d", resolution: "15", description: "5 Days" },
{ text: "1d", resolution: "5", description: "1 Day" },
],
};
const tvWidget = (window.tvWidget = new window.TradingView.widget(widgetOptions));
this.tvWidget = tvWidget;
tvWidget.onChartReady(() => {
tvWidget.headerReady().then(() => {
console.log("Chart has loaded!");
});
});
}
componentWillUnmount() {
if (this.tvWidget !== null) {
this.tvWidget.remove();
this.tvWidget = null;
}
}
render() {
return <div ref={this.ref} className={"TVChartContainer"} />;
}
}
|
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import sqlite3
from askvista.system_message.prompts import SYSTEM_MESSAGE
from sqlite3 import Error
import streamlit as st
import os
from utils.db_connection import *
#----- Handle uploaded File, if file is .db extension, it will create connection with DB to get it's schema. ------#
def handle_file_upload(uploaded_file):
"""Handle the logic for file upload and processing."""
try:
file_name = uploaded_file
print('\n------Inside Handle File Upload\n---------')
if file_name.endswith('.db'):
print('\n------Uploaded File is DB \n---------')
schemas = get_upload_schema(uploaded_file)
message = SYSTEM_MESSAGE.format(schema=schemas)
print('\n------We got the message \n---------')
print(message)
st.success("Database file loaded successfully.")
return message
elif file_name.endswith(('.sql', '.json')):
content = read_other_content(file_name)
if content:
st.success('File loaded successfully.')
return content
else:
st.error("Failed to load file content.")
except Exception as e:
st.error(f"An error occurred: {e}")
#----- Create Connection with Existing Database in Repository -------#
def use_existing_connection():
"""Handle the logic for using an existing database connection."""
schemas = get_schema_representation()
message = SYSTEM_MESSAGE.format(schema=schemas)
st.success("No File Uploaded. Application will use existing DB.")
return message
#---- Create Connection with Uplaoded Database -----#
def create_upload_connection(uploaded_file):
""" Create or connect to an SQLite database """
print('-----------------------------')
conn = None
try:
print(f'Temporary database file created at: {uploaded_file}')
conn = sqlite3.connect(uploaded_file)
print('Connection Successful')
return conn
except sqlite3.Error as e:
print(e)
if conn:
conn.close()
# Optionally remove the temporary file if an error occurred
if os.path.isfile(uploaded_file):
os.remove(uploaded_file)
#--- Get schema of Uploaded Database File ----#
def get_upload_schema(uploaded_file):
""" Retrieve the schema of the SQLite database. """
print('Inside Upload Schema Function')
try:
conn = create_upload_connection(uploaded_file)
cursor = conn.cursor()
cursor.execute("SELECT type, name, sql FROM sqlite_master WHERE type='table'")
tables = cursor.fetchall()
db_schema = {}
for table in tables:
table_name = table[1] # Correct index for the table name
# Query to get column details for each table
cursor.execute(f"PRAGMA table_info('{table_name}');") # Properly quote the table name
columns = cursor.fetchall()
column_details = {}
for column in columns:
column_name = column[1]
column_type = column[2]
column_details[column_name] = column_type
db_schema[table_name] = column_details
if db_schema:
st.success('Schema Loaded')
else:
st.error('Schema Empty')
return db_schema
except Exception as e:
st.error('An error occurred: ' + str(e))
print('An error occurred: ', e)
#------ Read Content of files other than .db extension, such as sql, txt, json.
def read_other_content(file_path):
""" Read the content of a file and return it as a string. """
print('Reading File :: ',file_path)
encodings = ['utf-8', 'utf-16', 'iso-8859-1'] # List of encodings to try
for encoding in encodings:
print(encoding)
try:
with open(file_path, 'r', encoding=encoding) as file:
return file.read()
except UnicodeDecodeError:
print(f"Failed decoding '{file_path}' with {encoding}. Trying next encoding...")
except FileNotFoundError:
print(f"Error: The file '{file_path}' does not exist.")
return None
except Exception as e:
print(f"An error occurred while reading '{file_path}': {e}")
return None
st.write(f"All encodings failed. Unable to read '{file_path}'.")
return None
|
# ThreadPoolExector中的Worker工作者原理
## 1 前言
Java线程池(ThreadPool)是Java中用于管理和调度线程的一种机制。线程池通过重用线程来减少创建和销毁线程的开销,从而提高应用程序的性能。Java线程池的核心组件之一是Worker线程,它负责实际的任务执行。
Worker是线程池内部的工作者,每个Worker内部持有一个线程,addWorker方法创建了一个Worker工作者,并且放入HashSet的容器中,那么这节我们就来看看Worker是如何工作的。
## 2 内部属性
```java
private final class Worker
extends AbstractQueuedSynchronizer
implements Runnable
{
// Worker内部持有的工作线程,就是依靠这个线程来不断运行线程池中的一个个task的
final Thread thread;
// 提交给这个Worker的首个任务
Runnable firstTask;
// 一个统计变量,记录着这个worker总共完成了多少个任务
volatile long completedTasks;
// 构造方法,创建Worker的时候给这个worker传入第一个运行的任务
Worker(Runnable firstTask) {
// 初始化AQS内部的state资源变量为-1
setState(-1);
// 保存一下首个任务
this.firstTask = firstTask;
// 使用线程工厂创建出来一个线程,这个线程负责运行任务
this.thread = getThreadFactory().newThread(this);
}
// 内部的run方法,这个方法执行一个个任务
public void run() {
// runWorker方法,去运行一个个task
runWorker(this);
}
// 实现AQS的互斥锁,这里是否持有互斥锁,不等于0就是持有
protected boolean isHeldExclusively() {
return getState() != 0;
}
// 实现AQS加互斥锁逻辑,就是CAS将state从0设置为1,成功就获取锁
protected boolean tryAcquire(int unused) {
if (compareAndSetState(0, 1)) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
// 是新AQS释放互斥锁逻辑,就是将state变量从1设置为0,成功就释放锁成功
protected boolean tryRelease(int unused) {
setExclusiveOwnerThread(null);
setState(0);
return true;
}
// 加锁
public void lock() { acquire(1); }
// 尝试加锁
public boolean tryLock() { return tryAcquire(1); }
// 解锁
public void unlock() { release(1); }
// 是否持有锁
public boolean isLocked() { return isHeldExclusively(); }
}
```
可以发现:
(1)Worker工作者继承了AQS,是一个同步器
(2)Worker实现了Runnable接口
为什么要这么做呢?我们往下看。
## 3 runWorker方法
```java
final void runWorker(Worker w) {
Thread wt = Thread.currentThread();
// 获取worker的第一个任务firstTask,赋值给task(要运行的任务)
Runnable task = w.firstTask;
// firstTask传给task之后,设置firstTask为null (方便firstTask完成之后垃圾回收)
w.firstTask = null;
// 初始化一下,将w的同步器设置为解锁状态
w.unlock(); // allow interrupts
boolean completedAbruptly = true;
try {
// 这里是重点
// 假如task != null ,是因为上边将firstTask设置给了task,所以优先运行第一个任务firstTask
// 假如task == null,那么调用getTask方法,从线程池的阻塞队列里面取任务出来
while (task != null || (task = getTask()) != null) {
// 运行任务之前需要进行加锁
w.lock();
// 这里就是校验一下线程池的状态
// 如果是STOP、TIDYING、TERMINATED 需要中断一下当前线程wt
if ((runStateAtLeast(ctl.get(), STOP) ||
(Thread.interrupted() &&
runStateAtLeast(ctl.get(), STOP))) &&
!wt.isInterrupted())
wt.interrupt();
try {
// 这里是一个钩子,执行任务前可以做一些自定义操作
beforeExecute(wt, task);
Throwable thrown = null;
try {
// 这里就是运行任务了,调用task的run方法执行task任务
task.run();
} catch (RuntimeException x) {
thrown = x; throw x;
} catch (Error x) {
thrown = x; throw x;
} catch (Throwable x) {
thrown = x; throw new Error(x);
} finally {
// 这里就是一个后置钩子,运行完毕任务之后可以做一些自定义操作
afterExecute(task, thrown);
}
} finally {
// 运行完task之后,需要设置task为null,否则就会死循环不断运行
task = null;
// 将worker完成的任务数+1,
w.completedTasks++;
// 解锁
w.unlock();
}
}
// 如果走到这里,说明跳出了上面的while循环,当前worker需要进行销毁了
completedAbruptly = false;
} finally {
// 销毁当前worker
processWorkerExit(w, completedAbruptly);
}
}
```

上面的核心流程主要是:
(1)在一个while循环里面,不断的运行任务task,task 的来源可能有两种
(2)task可能是创建worker的时候传入的firstTask,或者是调用getTask方法从阻塞队列取出的task
(3)每次调用task.run方法执行任务之前,需要先加锁,然后运行task任务,然后释放锁锁
(4)每次循环前,如果获取运行的task任务为null,则需要跳出while循环,准备销毁这个worker了
## 4 getTask方法
```java
private Runnable getTask() {
boolean timedOut = false; // Did the last poll() time out?
// 在一个循环里面,进行重试
for (;;) {
// 获取当前线程池的控制变量(包含线程池状态、线程数量)
int c = ctl.get();
// 获取当前线程池的状态
int rs = runStateOf(c);
// 如果当前线程池状态是STOP、TIDYING、TERMINATED,则说明线程池关闭了,直接返回null
// 如果当前线程池状态为SHUTDOWN、并且阻塞队列是空,说明线程池即将关闭,并且没有多余要执行的任务了,直接返回ull
if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
decrementWorkerCount();
return null;
}
// 计算当前线程池中线程数量wc
int wc = workerCountOf(c);
// 注意这里的timed控制变量很重要,表示从阻塞队列中获取任务的时候,是一直阻塞还是具有超时时间的阻塞
// (1)当前线程数量 wc > corePoolSize 的时候为true
// 假如corePoolSize = 5, maximumPoolSize = 0, wc = 8
// 当前线程数8 > corePoolSize,那么多出的这3个线程,在keepAliveTime时间内空闲就干掉
// (2) 当allowCoreThreadTimeout 为true,则timed为true
// 这里的意思是,线程池内的线程,只要超过keepAliveTime空闲的全部干掉
boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
// wc > maximumPoolSize 正常情况不可能发生的
// 这里的意思是如果超时了,超时了还取不到任务,就返回null
if ((wc > maximumPoolSize || (timed && timedOut))
&& (wc > 1 || workQueue.isEmpty())) {
if (compareAndDecrementWorkerCount(c))
return null;
continue;
}
try {
// 这的意思就是
// 如果timed == true, 从阻塞队列取任务最多阻塞keepAliveTime时间,如果娶不到返回null
// 如果timed == false。则调用take方法从阻塞队列取任务,一直阻塞,知道取到任务位置
// 这里涉及的一些阻塞队列的知识,我们在上一篇并发容器的时候已经非常深入的分析过了
Runnable r = timed ?
// 调用poll方法,最多阻塞keepAliveTime时间
workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
// 调用take方法,在取到任务之前会一直阻塞
workQueue.take();
// 如果从队列取到任务,直接返回
if (r != null)
return r;
// 否则就是超时了
timedOut = true;
} catch (InterruptedException retry) {
timedOut = false;
}
}
}
```

上面的核心流程主要是:
(1)判断一下当前线程池的状态,如果是STOP、TIDYING、TERMINATED状态中的一种,那么直接返回null,别执行任务了,线程池就要销毁了,赶紧销毁掉所有的worker
(2)如果是SHUTDOWN,并且workerQueue阻塞队列是空,说明线程池即将关闭,并且没有多余的任务了,所以worker也可以被销毁了
(3)如果当前线程数量 wc > corePoolSize,也就是线程数量大于核心线程数,此时多出的这部分线程在keepAliveTimeout时间内没能从阻塞队列取出任务,则返回null,也要销毁这些多出的worker
(4)如果allowCoreThreadTimeout == true,这个表示允许销毁所有线程包括核心线程,就是任意一个线程超过keepAliveTimeout时间内没取到任务,就会被干掉。
## 5 空闲线程被销毁
最后看下Worker是怎么被销毁的:
```java
private void processWorkerExit(Worker w, boolean completedAbruptly) {
// completeAbruptly表示当前线程是否因为被中断而被销毁的
// 如果是正常情况,因为keepAliveTimeout空闲而被销毁,则为false
if (completedAbruptly)
decrementWorkerCount();
final ReentrantLock mainLock = this.mainLock;
// 加锁
mainLock.lock();
try {
// 计算一下线程池完成总的任务数量
completedTaskCount += w.completedTasks;
// 从HashSet容器中移除当前的worker
workers.remove(w);
} finally {
// 释放锁
mainLock.unlock();
}
// 尝试中止线程池,这里我们后面的章节再分析
tryTerminate();
int c = ctl.get();
// 如果当前线程状态为RUNNING、SHUTDOWN
if (runStateLessThan(c, STOP)) {
if (!completedAbruptly) {
// 这就是计算一下当前线程池允许的最小线程数
// 正常情况是min=corePoolSize,但是当allowCoreThreadTimeout为true时候,允许销毁所有线程,则min=0
int min = allowCoreThreadTimeOut ? 0 : corePoolSize;
// 如果min = 0 并且 阻塞队列非空,说明还有任务没执行
// 此时最少要保留1个线程去运行这些任务,不能销毁所有
if (min == 0 && ! workQueue.isEmpty())
min = 1;
// 如果当前线程数量 >= min值,可以了,销毁动作结束了
if (workerCountOf(c) >= min)
return; // replacement not needed
}
// 说明completedAbruptly == true,说明可能是因为线程被中断(interrupted方法)而被销毁
// 此时可能还有很多任务还没执行,需要加会容器里面
addWorker(null, false);
}
}
```
上面主要就是做了:
(1)如果是正常情况keepAliveTimeout空闲时间被销毁,则从HashSet容器里面移除即可
(2)如果当前线程池状态是RUNNING、SHUTDOWN,说明还有一些任务没执行。
从HashSet容器移除当前worker之后,需要判断一下如果worker是因为异常情况被中断,需要新创建worker来继续执行任务
我们这里看到worker继承了AQS,每次worker执行任务之前都需要lock加锁,这是为什么呢?那就需要看下interruptIdleWorker方法了,interruptIdleWorker方法是销毁空闲的线程的意思。
```java
private void interruptIdleWorkers(boolean onlyOne) {
final ReentrantLock mainLock = this.mainLock;
mainLock.lock();
try {
// 遍历容器中的所有worker
for (Worker w : workers) {
Thread t = w.thread;
// 这里核心点就是要调用w.tryLock方法尝试获取锁
if (!t.isInterrupted() && w.tryLock()) {
try {
// 只有获取w工作者的互斥锁之后才能中断它
t.interrupt();
} catch (SecurityException ignore) {
} finally {
// 释放锁
w.unlock();
}
}
if (onlyOne)
break;
}
} finally {
mainLock.unlock();
}
}
```
我们可以发现:
(1)因为Worker执行每个task的之前,都要执行w.lock,对worker进行加锁,然后才能执行task任务。
(2)此时如果有别的线程要中断Worker,也需要获取w的互斥锁,执行w.tryLock()方法。
(3)如果执行tryLock加锁失败,说明当前Worker方法正在执行task,不允许中断,否则可能task执行一半,线程就被中断,导致一些数据异常问题。
所以说加锁就是为了防止Worker正在执行任务的时候,被人直接中断,导致异常。
其实ThreadPoolExecutor方法提供了**直接暴力中断所有线程的方法**,也就是不管当前Worker是否正在执行task任务,都会直接被中止掉的。而interruptIdleWorkers()这个方法是比较优雅的进行中断,中断worker之前,会先获取锁,如果失败则不允许中断。关于暴力中止线程池、以及其它中止线程池的方式,我们后面会说。
|
import {
FormControl,
FormErrorMessage,
FormHelperText,
FormLabel,
Textarea,
TextareaProps,
} from "@chakra-ui/react";
import React from "react";
import { Control, useController } from "react-hook-form";
type Props = {
label: string;
name: string;
control: Control<any>;
helperText?: string;
mask?: string;
} & TextareaProps;
function InputTextarea({ label, name, control, helperText, ...rest }: Props) {
const {
field: { onChange, onBlur, value, ref },
fieldState: { invalid, error },
} = useController({
name,
control,
});
return (
<FormControl isInvalid={invalid}>
<FormLabel htmlFor={name}>{label}</FormLabel>
<Textarea
value={value}
onChange={onChange}
onBlur={onBlur}
ref={ref}
size="sm"
resize="vertical"
bgColor={"#fff"}
{...rest}
/>
{invalid ? (
<FormErrorMessage>{error?.message}</FormErrorMessage>
) : (
<FormHelperText>{helperText}</FormHelperText>
)}
</FormControl>
);
}
export default InputTextarea;
|
using HiloGuessing.Domain.Entities;
using HiLoGuessing.Application.Services;
using HiLoGuessing.Application.Services.Interfaces;
using Moq;
using Serilog;
namespace HiLoGuessing.Tests.Application.Services
{
public class HiLoGuessServiceTest
{
[TestFixture]
public class ComparisonServiceTests
{
private IComparisonService _comparisonService;
private Mock<IHiLoGuessService> _mockHiLoGuessService;
private Mock<ILogger> _loggerMock;
[SetUp]
public void Setup()
{
_loggerMock = new Mock<ILogger>();
_mockHiLoGuessService = new Mock<IHiLoGuessService>();
_comparisonService = new ComparisonService(_mockHiLoGuessService.Object, _loggerMock.Object);
_mockHiLoGuessService.Setup(mock => mock.GetHiLoGuessAsync(It.IsAny<Guid>()))
.ReturnsAsync(new HiLoGuess());
}
[Test]
public async Task CompareNumber_ValidGuess_ReturnsCorrectResponse()
{
// Arrange
var hiloId = Guid.NewGuid();
var mysteryNumber = 10;
var numberGuess = 10;
// Act
var result = await _comparisonService.CompareNumber(hiloId, mysteryNumber, numberGuess);
Assert.Multiple(() =>
{
// Assert
Assert.That(result.GuessResult, Is.EqualTo(GuessResult.Equal));
Assert.That(result.Message, Is.EqualTo("Mystery Number Discovered!"));
Assert.That(result.Data.GeneratedMysteryNumber, Is.EqualTo(0));
});
_mockHiLoGuessService.Verify(mock => mock.ResetHiLoGuessAsync(hiloId), Times.Once);
}
[Test]
public async Task CompareNumber_InvalidGuess_ReturnsNotGeneratedResponse()
{
// Arrange
var hiloId = Guid.NewGuid();
var mysteryNumber = 0;
var numberGuess = 5;
// Act
var result = await _comparisonService.CompareNumber(hiloId, mysteryNumber, numberGuess);
Assert.Multiple(() =>
{
// Assert
Assert.That(result.GuessResult, Is.EqualTo(GuessResult.NotGenerated));
Assert.That(result.Message, Is.EqualTo("Please Generate a new Mystery Number"));
Assert.That(result.Data, Is.Null);
});
_mockHiLoGuessService.Verify(mock => mock.ResetHiLoGuessAsync(It.IsAny<Guid>()), Times.Never);
}
[Test]
public async Task CompareNumber_SmallerGuess_ReturnsSmallerResponse()
{
// Arrange
var hiloId = Guid.NewGuid();
var mysteryNumber = 10;
var numberGuess = 15;
// Act
var result = await _comparisonService.CompareNumber(hiloId, mysteryNumber, numberGuess);
Assert.Multiple(() =>
{
// Assert
Assert.That(result.GuessResult, Is.EqualTo(GuessResult.Smaller));
Assert.That(result.Message, Is.EqualTo("Mystery Number is Smaller than the Player's guess!"));
Assert.That(result.Data, Is.Not.Null);
});
_mockHiLoGuessService.Verify(mock => mock.ResetHiLoGuessAsync(It.IsAny<Guid>()), Times.Never);
}
[Test]
public async Task CompareNumber_GreaterGuess_ReturnsGreaterResponse()
{
// Arrange
var hiloId = Guid.NewGuid();
var mysteryNumber = 15;
var numberGuess = 10;
// Act
var result = await _comparisonService.CompareNumber(hiloId, mysteryNumber, numberGuess);
Assert.Multiple(() =>
{
// Assert
Assert.That(result.GuessResult, Is.EqualTo(GuessResult.Greater));
Assert.That(result.Message, Is.EqualTo("Mystery Number is Greater than the Player's guess!"));
Assert.That(result.Data, Is.Not.Null);
});
_mockHiLoGuessService.Verify(mock => mock.ResetHiLoGuessAsync(It.IsAny<Guid>()), Times.Never);
}
}
}
}
|
#ifndef _COLORS
# define _COLORS
# define BLACK "\033[1;30m"
# define RED "\033[1;31m"
# define GREEN "\033[1;32m"
# define YELLOW "\033[1;33m"
# define BLUE "\033[1;34m"
# define MAGENTA "\033[1;35m"
# define CYAN "\033[1;36m"
# define WHITE "\033[1;37m"
# define NC "\033[0m"
#endif // !_COLORS
// MateriaSource declaration --------------------------------------------------------
#pragma once
#ifndef _MATERIASOURCE_HPP
# define _MATERIASOURCE_HPP
# include <iostream>
# include "IMateriaSource.hpp"
class MateriaSource : public IMateriaSource
{
private:
AMateria *m_known_materias[4];
int pos;
public:
/* Constructors */
MateriaSource(void);
MateriaSource(MateriaSource const &other);
/* Operators */
MateriaSource &operator=(MateriaSource const &other);
/* Metods */
void learnMateria(AMateria* materia_random);
AMateria* createMateria(std::string const & type);
/* Destructor */
~MateriaSource(void);
};
#endif // !_MATERIASOURCE_HPP
|
#ifndef MONTY_H
#define MONTY_H
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#define STACKMODE 0
#define QUEUEMODE 1
/**
* struct stack_s - doubly linked list representation of a stack or queue
* @n: integer
* @prev: points to the previous element of the stack (or queue)
* @next: points to the next element of the stack (or queue)
*
* Description: doubly linked list node structure
* for stack, queues, LIFO, FIFO Holberton project
*/
typedef struct stack_s
{
int n;
struct stack_s *prev;
struct stack_s *next;
} stack_t;
/**
* struct instruction_s - opcoode and its function
* @opcode: the opcode
* @f: function to handle the opcode
*
* Description: opcode and its function
* for stack, queues, LIFO, FIFO Holberton project
*/
typedef struct instruction_s
{
char *opcode;
void (*f)(stack_t **stack, unsigned int line_number);
} instruction_t;
union montyfunctype
{
void (*toponly)(stack_t **front);
void (*pushmode)(stack_t **front, stack_t **rear, int element, int mode);
void (*topbot)(stack_t **front, stack_t **rear);
};
typedef struct optype
{
char *opcode;
union montyfunctype func;
} optype;
typedef struct montyglob
{
char *buffer;
unsigned long linenum;
FILE* script;
} montyglob;
void exit_true(int exitcode, char *existring, stack_t *front);
int is_num(char *s);
void add(stack_t **front);
void sub(stack_t **front);
void mul(stack_t **front);
void _div(stack_t **front);
void mod(stack_t **front);
void push(stack_t **front, stack_t **rear, int element, int mode);
void pop(stack_t **front);
void swap(stack_t **front, stack_t **rear);
void rotl(stack_t **front, stack_t **rear);
void rotr(stack_t **front, stack_t **rear);
void pall(stack_t **front);
void pint(stack_t **front);
void pchar(stack_t **front);
void pstr(stack_t **front);
#endif /* MONTY_H */
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.net.module.util.netlink;
import static com.android.net.module.util.netlink.RtNetlinkAddressMessage.IFA_FLAGS;
import static com.android.net.module.util.netlink.RtNetlinkLinkMessage.IFLA_ADDRESS;
import static com.android.net.module.util.netlink.RtNetlinkLinkMessage.IFLA_IFNAME;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import android.net.MacAddress;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
@SmallTest
public class StructNlAttrTest {
private static final MacAddress TEST_MAC_ADDRESS = MacAddress.fromString("00:11:22:33:44:55");
private static final String TEST_INTERFACE_NAME = "wlan0";
private static final int TEST_ADDR_FLAGS = 0x80;
@Test
public void testGetValueAsMacAddress() {
final StructNlAttr attr1 = new StructNlAttr(IFLA_ADDRESS, TEST_MAC_ADDRESS);
final MacAddress address1 = attr1.getValueAsMacAddress();
assertEquals(address1, TEST_MAC_ADDRESS);
// Invalid mac address byte array.
final byte[] array = new byte[] {
(byte) 0x00, (byte) 0x11, (byte) 0x22, (byte) 0x33,
(byte) 0x44, (byte) 0x55, (byte) 0x66,
};
final StructNlAttr attr2 = new StructNlAttr(IFLA_ADDRESS, array);
final MacAddress address2 = attr2.getValueAsMacAddress();
assertNull(address2);
}
@Test
public void testGetValueAsString() {
final StructNlAttr attr1 = new StructNlAttr(IFLA_IFNAME, TEST_INTERFACE_NAME);
final String str1 = attr1.getValueAsString();
assertEquals(str1, TEST_INTERFACE_NAME);
final byte[] array = new byte[] {
(byte) 0x77, (byte) 0x6c, (byte) 0x61, (byte) 0x6E, (byte) 0x30, (byte) 0x00,
};
final StructNlAttr attr2 = new StructNlAttr(IFLA_IFNAME, array);
final String str2 = attr2.getValueAsString();
assertEquals(str2, TEST_INTERFACE_NAME);
}
@Test
public void testGetValueAsIntger() {
final StructNlAttr attr1 = new StructNlAttr(IFA_FLAGS, TEST_ADDR_FLAGS);
final Integer integer1 = attr1.getValueAsInteger();
final int int1 = attr1.getValueAsInt(0x08 /* default value */);
assertEquals(integer1, new Integer(TEST_ADDR_FLAGS));
assertEquals(int1, TEST_ADDR_FLAGS);
// Malformed attribute.
final byte[] malformed_int = new byte[] { (byte) 0x0, (byte) 0x0, (byte) 0x80, };
final StructNlAttr attr2 = new StructNlAttr(IFA_FLAGS, malformed_int);
final Integer integer2 = attr2.getValueAsInteger();
final int int2 = attr2.getValueAsInt(0x08 /* default value */);
assertNull(integer2);
assertEquals(int2, 0x08 /* default value */);
// Null attribute value.
final byte[] null_int = null;
final StructNlAttr attr3 = new StructNlAttr(IFA_FLAGS, null_int);
final Integer integer3 = attr3.getValueAsInteger();
final int int3 = attr3.getValueAsInt(0x08 /* default value */);
assertNull(integer3);
assertEquals(int3, 0x08 /* default value */);
}
}
|
import {
Button,
Card,
Box,
Grid,
Typography,
useTheme,
styled,
Avatar,
Divider,
alpha,
ListItem,
ListItemText,
List,
ListItemAvatar
} from '@mui/material';
import SettingsApplicationsOutlinedIcon from '@mui/icons-material/SettingsApplicationsOutlined';
import CarRepairIcon from '@mui/icons-material/CarRepair';
import TrendingUp from '@mui/icons-material/TrendingUp';
import Text from 'src/components/Text';
import Chart from 'react-apexcharts';
import type { ApexOptions } from 'apexcharts';
const AvatarSuccess = styled(Avatar)(
({ theme }) => `
background-color: ${theme.colors.success.main};
color: ${theme.palette.success.contrastText};
width: ${theme.spacing(8)};
height: ${theme.spacing(8)};
box-shadow: ${theme.colors.shadows.success};
`
);
const ListItemAvatarWrapper = styled(ListItemAvatar)(
({ theme }) => `
min-width: 0;
display: flex;
align-items: center;
justify-content: center;
margin-right: ${theme.spacing(1)};
padding: ${theme.spacing(0.5)};
border-radius: 60px;
background: ${theme.palette.mode === 'dark'
? theme.colors.alpha.trueWhite[30]
: alpha(theme.colors.alpha.black[100], 0.07)
};
img {
background: ${theme.colors.alpha.trueWhite[100]};
padding: ${theme.spacing(0.5)};
display: block;
border-radius: inherit;
height: ${theme.spacing(4.5)};
width: ${theme.spacing(4.5)};
}
`
);
function AccountBalance() {
const theme = useTheme();
const chartOptions: ApexOptions = {
chart: {
background: 'transparent',
stacked: false,
toolbar: {
show: false
}
},
plotOptions: {
pie: {
donut: {
size: '60%'
}
}
},
colors: ['#ff9900', '#1c81c2', '#333', '#5c6ac0'],
dataLabels: {
enabled: true,
formatter: function (val) {
return val + '%';
},
style: {
colors: [theme.colors.alpha.trueWhite[100]]
},
background: {
enabled: true,
foreColor: theme.colors.alpha.trueWhite[100],
padding: 8,
borderRadius: 4,
borderWidth: 0,
opacity: 0.3,
dropShadow: {
enabled: true,
top: 1,
left: 1,
blur: 1,
color: theme.colors.alpha.black[70],
opacity: 0.5
}
},
dropShadow: {
enabled: true,
top: 1,
left: 1,
blur: 1,
color: theme.colors.alpha.black[50],
opacity: 0.5
}
},
fill: {
opacity: 1
},
labels: ['Bitcoin', 'Ripple', 'Cardano', 'Ethereum'],
legend: {
labels: {
colors: theme.colors.alpha.trueWhite[100]
},
show: false
},
stroke: {
width: 0
},
theme: {
mode: theme.palette.mode
}
};
const chartSeries = [10, 20, 25, 45];
return (
<Card>
<Grid spacing={0} container>
<Grid item xs={12} md={6}>
<Box p={4}>
<Typography
sx={{
pb: 3
}}
variant="h4"
>
Variação do Mês
</Typography>
<Box>
<Typography variant="h1" gutterBottom>
7 m3/h
</Typography>
<Typography
variant="h4"
fontWeight="normal"
color="text.secondary"
>
+10.0459%
</Typography>
<Box
display="flex"
sx={{
py: 4
}}
alignItems="center"
>
<AvatarSuccess
sx={{
mr: 2
}}
variant="rounded"
>
<TrendingUp fontSize="large" />
</AvatarSuccess>
<Box>
<Typography variant="h4">+ 1.9%</Typography>
<Typography variant="subtitle2" noWrap>
Neste Mês
</Typography>
</Box>
</Box>
</Box>
<Grid container spacing={3}>
<Grid sm item>
<Button fullWidth variant="outlined">
Tempo Real
</Button>
</Grid>
<Grid sm item>
<Button fullWidth variant="contained">
Status
</Button>
</Grid>
</Grid>
</Box>
</Grid>
<Grid
sx={{
position: 'relative'
}}
display="flex"
alignItems="center"
item
xs={12}
md={6}
>
<Box
component="span"
sx={{
display: { xs: 'none', md: 'inline-block' }
}}
>
<Divider absolute orientation="vertical" />
</Box>
<Box py={4} pr={4} flex={1}>
<Grid container spacing={0}>
<Grid
xs={12}
sm={5}
item
display="flex"
justifyContent="center"
alignItems="center"
>
<Chart
height={250}
options={chartOptions}
series={chartSeries}
type="donut"
/>
</Grid>
<Grid xs={12} sm={7} item display="flex" alignItems="center">
<List
disablePadding
sx={{
width: '100%'
}}
>
<ListItem disableGutters>
<ListItemAvatarWrapper>
<SettingsApplicationsOutlinedIcon />
</ListItemAvatarWrapper>
<ListItemText
primary="Produção"
primaryTypographyProps={{ variant: 'h5', noWrap: true }}
secondaryTypographyProps={{
variant: 'subtitle2',
noWrap: true
}}
/>
<Box>
<Typography align="right" variant="h4" noWrap>
20%
</Typography>
<Text color="success">+2.54%</Text>
</Box>
</ListItem>
<ListItem disableGutters>
<ListItemAvatarWrapper>
<CarRepairIcon />
</ListItemAvatarWrapper>
<ListItemText
primary="Entrega"
primaryTypographyProps={{ variant: 'h5', noWrap: true }}
secondaryTypographyProps={{
variant: 'subtitle2',
noWrap: true
}}
/>
<Box>
<Typography align="right" variant="h4" noWrap>
80%
</Typography>
<Text color="error">-6.20%</Text>
</Box>
</ListItem>
</List>
</Grid>
</Grid>
</Box>
</Grid>
</Grid>
</Card>
);
}
export default AccountBalance;
|
import { useState, useEffect } from "react";
import axios from "axios";
import { GiphyResponse } from "../interfaces/giphy";
async function searchGiphy(query: string): Promise<string[]> {
try {
return await axios
.get<GiphyResponse>("https://api.giphy.com/v1/gifs/search", {
params: {
api_key: "5Vw5Ns8kZxJxWdlHtGWxUwbmkNulrWiu",
q: query,
limit: 9,
offset: 0,
rating: "g",
lang: "en",
},
})
.then((res) => res.data.data.map((gif) => gif.images.preview.mp4));
} catch (error) {
return [];
}
}
export function useGiphySearch(query: string) {
const [results, setResults] = useState([] as string[]);
useEffect(() => {
if (query !== "") {
searchGiphy(query).then(setResults);
} else {
setResults([]);
}
}, [query]);
return results;
}
|
import 'package:bloc_project/core/theme/app_pallete.dart';
import 'package:bloc_project/features/auth/presentation/screens/welcome_screen.dart';
import 'package:flutter/material.dart';
class DrawerWidget extends StatelessWidget {
const DrawerWidget({super.key});
@override
Widget build(BuildContext context) {
return Drawer(
backgroundColor: AppPallete.gradient1,
child: ListView(
children: [
const DrawerHeader(
child: Center(
child: Text(
'SAPDOS',
style: TextStyle(
color: AppPallete.whiteColor,
fontSize: 30,
letterSpacing: 3,
fontWeight: FontWeight.bold),
),
)),
ListTile(
leading: const Icon(
Icons.category_sharp,
color: AppPallete.whiteColor,
),
title: const Text(
'Categories',
style: TextStyle(color: AppPallete.whiteColor),
),
onTap: () {},
),
ListTile(
leading: const Icon(
Icons.calendar_month_rounded,
color: AppPallete.whiteColor,
),
title: const Text(
'Appointment',
style: TextStyle(color: AppPallete.whiteColor),
),
onTap: () {},
),
ListTile(
leading: const Icon(
Icons.chat_bubble,
color: AppPallete.whiteColor,
),
title: const Text(
'Chat',
style: TextStyle(color: AppPallete.whiteColor),
),
onTap: () {},
),
ListTile(
leading: const Icon(
Icons.settings,
color: AppPallete.whiteColor,
),
title: const Text(
'Settings',
style: TextStyle(color: AppPallete.whiteColor),
),
onTap: () {},
),
ListTile(
leading: const Icon(
Icons.logout_outlined,
color: AppPallete.whiteColor,
),
title: const Text(
'Logout',
style: TextStyle(color: AppPallete.whiteColor),
),
onTap: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: AppPallete.gradient1,
contentPadding: EdgeInsets.all(0),
content: Container(
height: 300,
padding: EdgeInsets.all(16),
child: const Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.logout,
size: 50,
color: AppPallete.whiteColor,
),
SizedBox(height: 20),
Text(
"Do you want to logout?",
style: TextStyle(
color: AppPallete.whiteColor,
fontSize: 18,
),
textAlign: TextAlign.center,
),
],
),
),
actions: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
foregroundColor: AppPallete.gradient1,
backgroundColor: Colors.white,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const MyWelcomePage(),
),
);
},
child: const Text(
"Yes.",
style: TextStyle(color: AppPallete.gradient1),
),
),
],
);
},
);
},
),
],
),
);
}
}
|
import Fsm from '../fsm/fsm.js';
import { IState } from '../interfaces/state.js';
/**
* Lifecycle state machine.
*
* ```typescript
* import { Lifecycle } from '@syster42/core';
* const lifecycle = new Lifecycle();
* lifecycle.onStart = () => {
* console.log('start');
* };
* lifecycle.onStop = () => {
* console.log('stop');
* };
* lifecycle.start();
* // ...
* lifecycle.stop();
* ```
* @class Lifecycle
*/
export class Lifecycle {
/**
* State machine.
*
* @private
* @type {Fsm}
* @memberof Lifecycle
*/
private readonly stateMachine: Fsm;
/**
* Start trigger
*
* @private
* @type {Symbol}
* @memberof Lifecycle
*/
private readonly startTrigger: symbol = Symbol('start');
/**
* Started trigger
*
* @private
* @type {Symbol}
* @memberof Lifecycle
*/
private readonly startedTrigger: symbol = Symbol('started');
/**
* Stopping trigger
*
* @private
* @type {Symbol}
* @memberof Lifecycle
*/
private readonly stoppingTrigger: symbol = Symbol('stopping');
/**
* Stop trigger
*
* @private
* @type {Symbol}
* @memberof Lifecycle
*/
private readonly stopTrigger: symbol = Symbol('stop');
/**
* Starting state.
*
* @private
* @type {IState}
* @memberof Lifecycle
*/
private readonly startingState: IState = {
key: Symbol('starting'),
triggers: new Set([this.startTrigger]),
onEnter: this.onStartInternal.bind(this),
};
/**
* Running state.
*
* @private
* @type {IState}
* @memberof Lifecycle
*/
private readonly runningState: IState = {
key: Symbol('running'),
triggers: new Set([this.startedTrigger]),
// permit: new Set([this.startingState.key]),
};
/**
* Stopping state.
*
* @private
* @type {IState}
* @memberof Lifecycle
*/
private readonly stoppingState: IState = {
key: Symbol('stopping'),
triggers: new Set([this.stopTrigger]),
onEnter: this.onStopInternal.bind(this),
};
/**
* Stopped state.
*
* @private
* @type {IState}
* @memberof Lifecycle
*/
private readonly stoppedState: IState = {
key: Symbol('stopped'),
// permit: new Set([
// this.stoppingState.key,
// ]),
};
/**
* Creates an instance of Lifecycle.
* @memberof Lifecycle
*/
constructor() {
this.stateMachine = new Fsm();
this.stateMachine.addState(this.startingState).addState(this.runningState).addState(this.stoppingState).addState(this.stoppedState);
}
/**
* callback for start
*
* @return {*} {Promise<void>}
* @memberof Lifecycle
*/
// eslint-disable-next-line class-methods-use-this
public onStart(): Promise<void> {
return Promise.reject();
}
/**
* callback for stop
*
* @return {*} {Promise<void>}
* @memberof Lifecycle
*/
// eslint-disable-next-line class-methods-use-this
public onStop(): Promise<void> {
return Promise.reject();
}
/**
* start the lifecycle
*
* @memberof Lifecycle
*/
public start(): void {
this.stateMachine.trigger(this.startTrigger);
}
/**
* set lifecycle to started
*
* @memberof Lifecycle
*/
public started(): void {
this.stateMachine.trigger(this.startedTrigger);
}
/**
* set lifecycle to stopping
*
* @memberof Lifecycle
*/
public stopping(): void {
this.stateMachine.trigger(this.stoppingTrigger);
}
/**
* stop the lifecycle
*
* @memberof Lifecycle
*/
public stop(): void {
this.stateMachine.trigger(this.stopTrigger);
}
/**
* update the lifecycle
*
* @memberof Lifecycle
*/
public update(): void {
this.stateMachine.update(0);
}
/**
* internal handler for start
*
* @private
* @return {*} {Promise<void>}
* @memberof Lifecycle
*/
private async onStartInternal(): Promise<void> {
await this.onStart();
await this.stateMachine.setState(this.runningState.key);
}
/**
* internal handler for stop
*
* @private
* @return {*} {Promise<void>}
* @memberof Lifecycle
*/
private async onStopInternal(): Promise<void> {
await this.onStop();
await this.stateMachine.setState(this.stoppedState.key);
}
}
export default Lifecycle;
|
#include<iostream>
#include<vector>
int longestSubarray(std::vector<int>& nums)
{
int i = 0, j = 0, ans = 0, zero_count = 0, count = 0;
while(i < nums.size())
{
//if the curr number is 0, increment zero_count
if(nums[i] == 0)
zero_count++;
//if more than 1 zero is there, reduce count by 1
if(zero_count > 1)
{
//curr zero is at nums[i], so increment j until previous 0 is not found
zero_count = 1;
//increment j until the previous 0 is reached and then increment it
//again after while loop to 1 num after the previous 0
while(j <= i && nums[j] == 1)
{
j++;
}
//increment again to overcome previous 0
j++;
}
//get max length
ans = std::max(ans,i-j);
i++;
}
return ans;
}
int main()
{
int n = 0;
std::cout<<"Enter the number of elements : "<<std::endl;
std::cin>>n;
std::vector<int> nums(n, 0);
std::cout<<"Enter all the binary elements : "<<std::endl;
for(int i = 0; i < n; i++)
{
std::cin>>nums[i];
}
std::cout<<"Size of the longest subarray containing only 1's : "<<longestSubarray(nums)<<std::endl;
std::cout<<"Note: the longest subarray is calculated by deleting 1 element(0 or 1) within a subarray."<<std::endl;
return 0;
}
|
const mongoose = require('mongoose'); // Erase if already required
// Declare the Schema of the Mongo model
const blogSchema = new mongoose.Schema({
title:{
type: String,
required:true,
},
description:{
type: String,
required:true,
},
category:{
type: String,
required:true,
},
numViews:{
type: Number,
default: 0,
},
isLiked: {
type: Boolean,
default: false,
},
isDisliked: {
type: Boolean,
default: false,
},
likes: [
{
type: mongoose.ObjectId,
ref: "User"
}
],
dislikes: [
{ type: mongoose.ObjectId,
ref: "User"
}
],
image: {
type: String,
default: "https://www.picpedia.org/chalkboard/images/blog.jpg"
},
author: {
type: String,
default: "Admin",
},
images: [],
}, {
toJSON: {
virtuals: true,
},
toObject: {
virtuals: true,
},
timestamps: true,
});
//Export the model
module.exports = mongoose.model('Blog', blogSchema);
|
package com.bob.redwall.tileentity;
import com.bob.redwall.Ref;
import com.bob.redwall.gui.smithing.SlotSmithingFuel;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.inventory.Container;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemHoe;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemSword;
import net.minecraft.item.ItemTool;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntityLockable;
import net.minecraft.util.ITickable;
import net.minecraftforge.items.CapabilityItemHandler;
import net.minecraftforge.items.ItemStackHandler;
public class TileEntityCookingGeneric extends TileEntityLockable implements ITickable {
public static final int SIZE = 10; // Size of the inventory: 9 crafting slots and 1 fuel slot
public static final int FUEL_INDEX = 9; // Index of the fuel slot
public static final int COOKING_TIME = 200; // Time required to cook an item, in ticks; 200 is about 10 seconds
public ItemStack cookStack = ItemStack.EMPTY;
private int fuel = 0;
private int cookTime = -1;
private boolean cookingFinished = false;
private EntityPlayer openPlayer;
private String customName;
private ItemStackHandler itemStackHandler = new ItemStackHandler(SIZE) {
@Override
protected void onContentsChanged(int slot) {
TileEntityCookingGeneric.this.markDirty();
}
};
@Override
public String getName() {
return this.hasCustomName() ? this.customName : "tile.cooking_generic.name";
}
@Override
public boolean hasCustomName() {
return this.customName != null && !this.customName.isEmpty();
}
public void setName(String name) {
this.customName = name;
}
@Override
public int getSizeInventory() {
return this.itemStackHandler.getSlots();
}
@Override
public boolean isEmpty() {
for (int i = 0; i < this.itemStackHandler.getSlots(); i++) {
if (!this.itemStackHandler.getStackInSlot(i).isEmpty()) {
return false;
}
}
return true;
}
@Override
public void update() {
if (this.cookTime > 0) this.cookTime--;
if (this.cookTime == 0) {
this.cookTime = -1;
this.cookingFinished = true;
}
if (this.openPlayer != null && this.openPlayer instanceof EntityPlayerMP) ((EntityPlayerMP) this.openPlayer).connection.sendPacket(this.getUpdatePacket());
}
@Override
public void readFromNBT(NBTTagCompound compound) {
super.readFromNBT(compound);
if (compound.hasKey("CustomName", 8)) this.customName = compound.getString("CustomName");
if (compound.hasKey("items")) this.itemStackHandler.deserializeNBT((NBTTagCompound) compound.getTag("items"));
if (compound.hasKey("fuel")) this.fuel = compound.getInteger("fuel");
if (compound.hasKey("cookTime")) this.cookTime = compound.getInteger("cookTime");
if (compound.hasKey("cookDone")) this.cookingFinished = compound.getBoolean("cookDone");
if (compound.hasKey("cookItem")) this.cookStack = new ItemStack(compound.getCompoundTag("cookItem"));
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
super.writeToNBT(compound);
compound.setTag("items", this.itemStackHandler.serializeNBT());
compound.setInteger("fuel", this.fuel);
compound.setInteger("cookTime", this.cookTime);
compound.setBoolean("cookDone", this.cookingFinished);
compound.setTag("cookItem", this.cookStack.serializeNBT());
if (this.hasCustomName()) {
compound.setString("CustomName", this.customName);
}
return compound;
}
@Override
public ItemStack getStackInSlot(int index) {
return index >= 0 && index < this.itemStackHandler.getSlots() ? (ItemStack) this.itemStackHandler.getStackInSlot(index) : ItemStack.EMPTY;
}
@Override
public ItemStack decrStackSize(int index, int count) {
return this.itemStackHandler.extractItem(index, count, false);
}
@Override
public ItemStack removeStackFromSlot(int index) {
ItemStack stack = this.itemStackHandler.getStackInSlot(index);
this.itemStackHandler.setStackInSlot(index, ItemStack.EMPTY);
return stack;
}
@Override
public void setInventorySlotContents(int index, ItemStack stack) {
if (index == TileEntityCookingGeneric.FUEL_INDEX && !stack.isEmpty() && this.fuel < 8) {
this.fuel += Math.min(8 - this.fuel, this.getFuelForItem(this.itemStackHandler.getStackInSlot(TileEntityCookingGeneric.FUEL_INDEX)));
stack.setCount(stack.getCount() - 1);
}
this.itemStackHandler.setStackInSlot(index, stack);
}
@Override
public int getInventoryStackLimit() {
return 64;
}
@Override
public boolean isUsableByPlayer(EntityPlayer player) {
return this.world.getTileEntity(this.pos) != this ? false : player.getDistanceSq((double) this.pos.getX() + 0.5D, (double) this.pos.getY() + 0.5D, (double) this.pos.getZ() + 0.5D) <= 64.0D;
}
@Override
public void openInventory(EntityPlayer player) {
this.openPlayer = player;
}
@Override
public void closeInventory(EntityPlayer player) {
this.openPlayer = null;
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
return index == TileEntityCookingGeneric.FUEL_INDEX ? SlotSmithingFuel.isValidSmithingFuel(stack) : true;
}
@Override
public String getGuiID() {
return Ref.MODID + ":cooking_generic";
}
@Override
public Container createContainer(InventoryPlayer playerInventory, EntityPlayer playerIn) {
return null;
}
@Override
public int getField(int id) {
return 0;
}
@Override
public void setField(int id, int value) {}
@Override
public <T> T getCapability(net.minecraftforge.common.capabilities.Capability<T> capability, net.minecraft.util.EnumFacing facing) {
if (capability == net.minecraftforge.items.CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {
return CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(this.itemStackHandler);
}
return super.getCapability(capability, facing);
}
@Override
public int getFieldCount() {
return 2;
}
@Override
public void clear() {
for (int i = 0; i < this.itemStackHandler.getSlots(); i++) {
this.itemStackHandler.setStackInSlot(i, ItemStack.EMPTY);
}
}
@Override
public SPacketUpdateTileEntity getUpdatePacket() {
NBTTagCompound nbtTag = new NBTTagCompound();
this.writeToNBT(nbtTag);
return new SPacketUpdateTileEntity(this.getPos(), 1, nbtTag);
}
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity packet) {
this.readFromNBT(packet.getNbtCompound());
}
@Override
public NBTTagCompound getUpdateTag() {
return this.writeToNBT(new NBTTagCompound());
}
public int getFuel() {
return this.fuel;
}
public void useFuel() {
this.fuel--;
if (!this.itemStackHandler.getStackInSlot(TileEntityCookingGeneric.FUEL_INDEX).isEmpty() && this.fuel < 8) {
this.fuel += Math.min(8 - this.fuel, this.getFuelForItem(this.itemStackHandler.getStackInSlot(TileEntityCookingGeneric.FUEL_INDEX)));
this.decrStackSize(TileEntityCookingGeneric.FUEL_INDEX, 1);
}
}
public int getFuelForItem(ItemStack stack) {
if (stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().getDefaultState().getMaterial() == Material.WOOD) {
return 3;
} else if (stack.getItem() instanceof ItemBlock && ((ItemBlock) stack.getItem()).getBlock().getDefaultState().getMaterial() == Material.CLOTH) {
return 1;
} else if (stack.getItem() == Items.STICK) {
return 1;
} else if (stack.getItem() instanceof ItemTool && ((ItemTool) stack.getItem()).getIsRepairable(stack, new ItemStack(Blocks.PLANKS))) {
return 2;
} else if (stack.getItem() instanceof ItemSword && ((ItemSword) stack.getItem()).getIsRepairable(stack, new ItemStack(Blocks.PLANKS))) {
return 2;
} else if (stack.getItem() instanceof ItemHoe && ((ItemHoe) stack.getItem()).getIsRepairable(stack, new ItemStack(Blocks.PLANKS))) {
return 2;
} else if (stack.getItem() == Items.COAL) {
return 8;
} else if (stack.getItem() == Items.BOAT) {
return 3;
} else {
return 1;
}
}
public int getCookingTime() {
return this.cookTime;
}
public void setCookingTime(int i) {
this.cookTime = i;
}
public boolean getCookingFinished() {
return this.cookingFinished;
}
public void setCookingFinished(boolean b) {
this.cookingFinished = b;
}
public boolean isBurning() {
return this.cookTime != -1 && !this.cookingFinished;
}
}
|
import 'dart:math';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:fin_app/products/cart_view_model.dart';
import 'package:fin_app/products/product_model.dart';
import 'package:fin_app/store/application_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:fluttertoast/fluttertoast.dart';
const dummyProductImages = [
"camera.jpg",
"perfume.jpg",
"dummy.jpg",
"watch.jpg",
"placeholder.jpg",
"watches.jpg"
];
int getRandomImageIndex() {
return Random().nextInt(dummyProductImages.length - 1);
}
class ProductItem extends StatelessWidget {
final Product product;
const ProductItem(this.product, {super.key});
@override
Widget build(BuildContext context) {
return Container(
height: 190,
width: 200,
padding: const EdgeInsets.all(2),
child: Card(
elevation: 3,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Align(
alignment: Alignment.center,
child: Icon(
color: Colors.orange.shade500,
Icons.account_balance_wallet_outlined,
size: 65,
)),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
product.name,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 15, fontWeight: FontWeight.w400),
),
),
Align(
alignment: Alignment.bottomRight,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
"R ${product.price}0 p/m",
style: const TextStyle(fontWeight: FontWeight.bold),
),
)),
Padding(
padding: const EdgeInsets.all(8.0),
child: SizedBox(
height: 40,
child: StoreConnector<ApplicationState, CartViewModel>(
converter: (store) => CartViewModel.converter(store),
builder: (context, viewModel) {
return Visibility(
visible: !viewModel.cartContainsProduct(product),
child: OutlinedButton(
onPressed: () {
showProductAddedToast();
viewModel.addToCart(product);
},
style: OutlinedButton.styleFrom(
minimumSize: const Size(100, 40),
side: const BorderSide(
width: 3, color: Colors.orange)),
child: const Text("Add")),
);
},
),
),
)
],
),
),
),
);
}
}
class ProductListTile extends StatelessWidget {
final Product product;
const ProductListTile(this.product, {super.key});
@override
Widget build(BuildContext context) {
return ListTile(
tileColor: Colors.grey.shade200,
leading: Padding(
padding: const EdgeInsets.all(5.0),
child: Image(
image: AssetImage(
'assets/images/carousel/${dummyProductImages[getRandomImageIndex()]}')),
),
title: Text(product.name),
trailing: Text("R ${product.price.toString()}"),
onTap: () => {
Navigator.push(context,
MaterialPageRoute(builder: (context) => ProductDetails(product)))
},
onLongPress: () {
Fluttertoast.showToast(
msg: "Product added",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black,
textColor: Colors.white,
fontSize: 16.0);
},
);
}
}
class ProductDetails extends StatelessWidget {
final Product product;
const ProductDetails(this.product, {super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.primary,
title: Text(product.name)),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(2.0),
child: Container(
color: Colors.grey.shade100,
child: CarouselSlider.builder(
itemCount: dummyProductImages.length,
itemBuilder:
(BuildContext context, int index, int pageViewIndex) =>
Image(
image: AssetImage(
'assets/images/carousel/${dummyProductImages[index]}',
)),
options: CarouselOptions(
viewportFraction: 0.4,
enlargeCenterPage: true,
enlargeFactor: 0.7)),
),
),
const SizedBox(
height: 15,
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
product.description,
style: const TextStyle(fontSize: 16),
),
)
],
),
);
}
}
class CartItemsView extends StatelessWidget {
const CartItemsView({super.key});
@override
Widget build(BuildContext context) {
return StoreConnector<ApplicationState, CartViewModel>(
builder: (context, viewModel) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
centerTitle: true,
title:
Text("${viewModel.getCartItemsCount()} Items in your cart"),
),
body: Column(
children: [
Expanded(
child: ListView.builder(
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 8.0),
shrinkWrap: true,
itemCount: viewModel.getCartItemsCount(),
itemBuilder: (context, index) {
return Card(
color: Colors.grey.shade50,
elevation: 5.0,
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
children: [
Icon(
color: Colors.orange.shade500,
Icons.account_balance_wallet_outlined,
size: 65,
),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
const SizedBox(
height: 5.0,
),
RichText(
overflow: TextOverflow.ellipsis,
maxLines: 2,
text: TextSpan(
text: viewModel.getCartItemsList()[index].name,
style: TextStyle(
color: Colors.blueGrey.shade800,
fontSize: 16.0)
)
),
],
),
),
IconButton(
onPressed: () {
viewModel.removeProductItemFromCart(viewModel.getCartItemsList()[index]);
},
icon: Icon(
Icons.delete,
color: Colors.orange.shade800,
)
),
],
),
),
);
}),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: OutlinedButton(
onPressed: (){
if(viewModel.getCartItemsCount() > 0) {
viewModel.takeUpProducts();
}
},
style: OutlinedButton.styleFrom(
minimumSize: const Size(300, 50),
side: const BorderSide(
width: 3,
color: Colors.orange
)
),
child: const Text("Take Up Items"),
),
)
],
),
);
},
converter: (store) => CartViewModel.converter(store));
}
}
void showProductAddedToast(){
Fluttertoast.showToast(
msg: "Product added to cart",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.black,
textColor: Colors.white,
fontSize: 16.0
);
}
|
# Mini-Compiler
This is a small compiler that outputs C code after implementing a dialect of BASIC. It will support basic operations such as:
- Numerical variables
- Basic arithmetic
- If statements
- While loops
- Print
- Labels and goto
- Comments
## Overview

The compiler follows a three step process consisting of the lexer, parser, and emitter.
- ***Lexer***: responsible for scanning the source code, breaking it down into tokens (keyword, identifier, operator, etc.), and categorizing each token into different types
- ***Parser***: analyzes the stream of tokens from the Lexer and creates a parse tree based on constructs of the language
- ***Emitter***: takes the parsed tokens generated by the Parser and translates them into the output format (C code)
|
namespace CGAL {
/*!
\ingroup PkgSnapRounding2Ref
<span style="display:none">\f$ \def\A{{\cal A}} \f$ \f$ \def\S{{\cal S}} \f$</span>
\tparam Traits must be a model of `SnapRoundingTraits_2`.
\tparam InputIterator must be an iterator with value type `Traits::Segment_2`.
\tparam OutputContainer must be a container with a method `push_back(const OutputContainer::value_type& c)`,
where `OutputContainer::value_type` must be a container with a method `push_back(const Traits::Point_2& p)`
\param begin,end The first two parameters denote the iterator range
of the input segments.
\param output_container is a reference to a
container of the output polylines. Since a polyline is composed of a
sequence of points, a polyline is a container itself.
\param do_isr The fifth parameter determines whether to apply ISR or SR.
\param pixel_size The fourth parameter denotes the pixel size `w`. The plane will be
tiled with square pixels of width `w` such that the origin is the
center of a pixel. `pixel_size` must have a positive value.
\param int_output The sixth parameter denotes the output
representation. If the value of the sixth parameter is `true`
then the centers of pixels constitute the integer grid, and hence the
vertices of the output polylines will be integers. For example, the
coordinates of the center of the pixel to the right of the pixel
containing the origin will be `(1,0)` regardless of the pixel width.
If the value of the sixth parameter is `false`, then the centers
of hot pixels (and hence the vertices of the output polylines) will
bear their original coordinates, which may not necessarily be
integers. In the latter case, the coordinates of the center of the
pixel to the right of the pixel containing the origin, for example,
will be `(w,0)`.
\param number_of_kd_trees The seventh parameter is briefly described later on this page; for a
detailed description see \cgalCite{cgal:hp-isr-02}.
Snap Rounding (SR, for short) is a well known method for converting
arbitrary-precision arrangements of segments into a fixed-precision
representation \cgalCite{gght-srlse-97}, \cgalCite{gm-rad-98}, \cgalCite{h-psifp-99}. In
the study of robust geometric computing, it can be classified as a
finite precision approximation technique. Iterated Snap Rounding (ISR,
for short) is a modification of SR in which each vertex is at least
half-the-width-of-a-pixel away from any non-incident edge
\cgalCite{cgal:hp-isr-02}. This package supports both methods. Algorithmic
details and experimental results are given in \cgalCite{cgal:hp-isr-02}.
Given a finite collection \f$ \S\f$ of segments in the plane, the
arrangement of \f$ \S\f$ denoted \f$ \A(\S)\f$ is the subdivision of the plane
into vertices, edges, and faces induced by \f$ \S\f$. A <I>vertex</I> of the arrangement is either a segment endpoint or
the intersection of two segments. Given an arrangement of segments
whose vertices are represented with arbitrary-precision coordinates,
SR proceeds as follows. We tile the plane
with a grid of unit squares, <I>pixels</I>, each centered at a point
with integer coordinates. A pixel is <I>hot</I> if it contains a
vertex of the arrangement. Each vertex of the arrangement is replaced
by the center of the hot pixel containing it and each edge \f$ e\f$ is
replaced by the polygonal chain through the centers of the hot pixels
met by \f$ e\f$, in the same order as they are met by \f$ e\f$.
In a snap-rounded arrangement, the distance between a vertex and
a non-incident edge can be extremely small compared with the width of a
pixel in the grid used for rounding. ISR is a modification of SR which
makes a vertex and a non-incident edge well separated (the distance
between each is at least half-the-width-of-a-pixel). However, the
guaranteed quality of the approximation in ISR degrades. For more
details on ISR see \cgalCite{cgal:hp-isr-02}.
The traits used here must support (arbitrary-precision) rational number type as
this is a basic requirement of SR.
\cgalHeading{About the Number of kd-Trees}
A basic query used in the algorithm is to report the hot pixels of
size \f$ w\f$ that a certain segment \f$ s\f$ intersects. An alternative way to
do the same is to query the hot pixels' centers contained in a
Minkowski sum of \f$ s\f$ with a pixel of width \f$ w\f$ centered at the origin;
we denote this Minkowski sum by \f$ M(s)\f$. Since efficiently implementing
this kind of query is difficult, we use an orthogonal range-search
structure instead. We query with the bounding box \f$ B(M(s))\f$ of \f$ M(s)\f$
in a two-dimensional kd-tree which stores the centers of hot
pixels. Since \f$ B(M(s))\f$ in general is larger than \f$ M(s)\f$, we still
need to filter out the hot pixels which do not intersect \f$ s\f$.
While this approach is easy to implement with CGAL, it may incur
considerable overhead since the area of \f$ B(M(s))\f$ may be much larger
than the area of \f$ M(s)\f$, possibly resulting in many redundant hot pixels
to filter out. Our heuristic solution, which we describe next, is to
use a cluster of kd-trees rather than just one. The cluster includes
several kd-trees, each has the plane, and hence the centers of hot
pixels, rotated by a different angle in the first quadrant of the
plane; for our purpose, a rotation by angles outside this quadrant
is symmetric to a rotation by an angle in the first quadrant.
Given a parameter \f$ c\f$, the angles of rotation are \f$ (i - 1)
\frac{\pi}{2c}, i=1,\ldots,c\f$, and we construct a kd-tree
corresponding to each of these angles. Then for a query segment \f$ s\f$,
we choose the kd-tree for which the area of \f$ B(M(s))\f$ is the smallest,
in order to (potentially) get less hot pixels to filter out. Since
constructing many kd-trees may be costly, our algorithm avoids
building a kd-tree which it expects to be queried a relatively small
number of times (we estimate this number in advance). How many
kd-trees should be used? It is difficult to provide a simple
answer for that. There are inputs for which the time to build more
than one kd-tree is far greater than the time saved by having to
filter out less hot pixels (sparse arrangements demonstrate this
behavior), and there are inputs which benefit from using several
kd-trees. Thus, the user can control the number of kd-trees
with the parameter `number_of_kd_trees`. Typically, but not
always, one kd-tree (the default) is sufficient.
*/
template < class Traits, class InputIterator, class OutputContainer >
void
snap_rounding_2(
InputIterator begin,
InputIterator end,
OutputContainer& output_container,
typename Traits::FT pixel_size,
bool do_isr = true,
bool int_output = true,
unsigned int number_of_kd_trees = 1);
} /* namespace CGAL */
|
import React from "react";
import Header from "./Header";
import Footer from "./Footer";
import { useTheme } from "next-themes";
import { useState, useEffect } from "react";
const Layout = ({ children }: { children: React.ReactNode }) => {
const [mounted, setMounted] = useState(false);
const { theme, setTheme } = useTheme();
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return null;
}
const setSiteTheme = () => {
if (theme === "dark") {
setTheme("light");
} else {
setTheme("dark");
}
};
return (
<div
className={`${
theme == "dark" ? "dark" : ""
} min-h-screen container font-raleway`}
>
<div className="dark:text-white">
<Header triggerDarkMode={setSiteTheme} />
<main>{children}</main>
<Footer />
</div>
</div>
);
};
export default Layout;
|
package network_test
import (
"context"
"fmt"
"testing"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/network/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)
type NetworkAdminRuleCollectionResource struct{}
func testAccNetworkManagerAdminRuleCollection_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_network_manager_admin_rule_collection", "test")
r := NetworkAdminRuleCollectionResource{}
data.ResourceSequentialTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}
func testAccNetworkManagerAdminRuleCollection_requiresImport(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_network_manager_admin_rule_collection", "test")
r := NetworkAdminRuleCollectionResource{}
data.ResourceSequentialTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.RequiresImportErrorStep(r.requiresImport),
})
}
func testAccNetworkManagerAdminRuleCollection_complete(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_network_manager_admin_rule_collection", "test")
r := NetworkAdminRuleCollectionResource{}
data.ResourceSequentialTest(t, r, []acceptance.TestStep{
{
Config: r.complete(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}
func testAccNetworkManagerAdminRuleCollection_update(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_network_manager_admin_rule_collection", "test")
r := NetworkAdminRuleCollectionResource{}
data.ResourceSequentialTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
{
Config: r.update(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep(),
})
}
func (r NetworkAdminRuleCollectionResource) Exists(ctx context.Context, clients *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.NetworkManagerAdminRuleCollectionID(state.ID)
if err != nil {
return nil, err
}
client := clients.Network.ManagerAdminRuleCollectionsClient
resp, err := client.Get(ctx, id.ResourceGroup, id.NetworkManagerName, id.SecurityAdminConfigurationName, id.RuleCollectionName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return utils.Bool(false), nil
}
return nil, fmt.Errorf("retrieving %s: %+v", id, err)
}
return utils.Bool(resp.AdminRuleCollectionPropertiesFormat != nil), nil
}
func (r NetworkAdminRuleCollectionResource) template(data acceptance.TestData) string {
return fmt.Sprintf(`
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "test" {
name = "acctestRG-network-manager-%d"
location = "%s"
}
data "azurerm_subscription" "current" {
}
resource "azurerm_network_manager" "test" {
name = "acctest-nm-%d"
resource_group_name = azurerm_resource_group.test.name
location = azurerm_resource_group.test.location
scope {
subscription_ids = [data.azurerm_subscription.current.id]
}
scope_accesses = ["SecurityAdmin"]
}
resource "azurerm_network_manager_network_group" "test" {
name = "acctest-nmng-%d"
network_manager_id = azurerm_network_manager.test.id
}
resource "azurerm_network_manager_security_admin_configuration" "test" {
name = "acctest-nmsac-%d"
network_manager_id = azurerm_network_manager.test.id
}
`, data.RandomInteger, data.Locations.Primary, data.RandomInteger, data.RandomInteger, data.RandomInteger)
}
func (r NetworkAdminRuleCollectionResource) basic(data acceptance.TestData) string {
template := r.template(data)
return fmt.Sprintf(`
%s
resource "azurerm_network_manager_admin_rule_collection" "test" {
name = "acctest-nmarc-%d"
security_admin_configuration_id = azurerm_network_manager_security_admin_configuration.test.id
network_group_ids = [azurerm_network_manager_network_group.test.id]
}
`, template, data.RandomInteger)
}
func (r NetworkAdminRuleCollectionResource) requiresImport(data acceptance.TestData) string {
config := r.basic(data)
return fmt.Sprintf(`
%s
resource "azurerm_network_manager_admin_rule_collection" "import" {
name = azurerm_network_manager_admin_rule_collection.test.name
security_admin_configuration_id = azurerm_network_manager_admin_rule_collection.test.security_admin_configuration_id
network_group_ids = azurerm_network_manager_admin_rule_collection.test.network_group_ids
}
`, config)
}
func (r NetworkAdminRuleCollectionResource) complete(data acceptance.TestData) string {
template := r.template(data)
return fmt.Sprintf(`
%s
resource "azurerm_network_manager_network_group" "test2" {
name = "acctest-nmng2-%d"
network_manager_id = azurerm_network_manager.test.id
}
resource "azurerm_network_manager_admin_rule_collection" "test" {
name = "acctest-nmarc-%d"
security_admin_configuration_id = azurerm_network_manager_security_admin_configuration.test.id
description = "test admin rule collection"
network_group_ids = [azurerm_network_manager_network_group.test.id, azurerm_network_manager_network_group.test2.id]
}
`, template, data.RandomInteger, data.RandomInteger)
}
func (r NetworkAdminRuleCollectionResource) update(data acceptance.TestData) string {
template := r.template(data)
return fmt.Sprintf(`
%s
resource "azurerm_network_manager_admin_rule_collection" "test" {
name = "acctest-nmarc-%d"
security_admin_configuration_id = azurerm_network_manager_security_admin_configuration.test.id
network_group_ids = [azurerm_network_manager_network_group.test.id]
}
`, template, data.RandomInteger)
}
|
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../services/api';
import '../styles/EmployerDashboard.css'
const EmployerDashboard = () => {
const [employer, setEmployer] = useState(null);
const [jobs, setJobs] = useState([]);
useEffect(() => {
// Fetch employer details from the API
const fetchEmployerDetails = async () => {
try {
const response = await api.get('/employers/me');
setEmployer(response.data);
} catch (error) {
console.error('Error fetching employer details:', error);
}
};
// Fetch jobs posted by the employer
const fetchEmployerJobs = async () => {
try {
const response = await api.get('/jobs/employer');
setJobs(response.data);
} catch (error) {
console.error('Error fetching employer jobs:', error);
}
};
fetchEmployerDetails();
fetchEmployerJobs();
}, []);
return (
<div className="employer-dashboard">
{employer ? (
<>
<h2>Welcome, {employer.companyName}!</h2>
<p>Email: {employer.email}</p>
<h3>Your Job Postings</h3>
{jobs.length === 0 ? (
<p>No jobs posted yet.</p>
) : (
<ul>
{jobs.map((job) => (
<li key={job.id}>
<Link to={`/job/${job.id}`}>{job.title}</Link>
</li>
))}
</ul>
)}
<Link to="/post-job">
<button>Post a New Job</button>
</Link>
</>
) : (
<p>Loading employer details...</p>
)}
</div>
);
};
export default EmployerDashboard;
|
use unicode_segmentation::UnicodeSegmentation;
use super::helpers::{
multi_spaces_regex, new_line_regex,
password_validator::password_validator,
regexes::{email_regex, jwt_regex, name_regex},
};
pub fn format_name(name: &str) -> String {
let mut title = name.trim().to_lowercase();
title = new_line_regex().replace_all(&title, " ").to_string();
title = multi_spaces_regex().replace_all(&title, " ").to_string();
let mut c = title.chars();
match c.next() {
None => title,
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
pub fn validate_email(email: &str) -> Result<(), String> {
let len = email.graphemes(true).count();
if len < 5 {
return Err("Email needs to be at least 5 characters long".to_string());
}
if len > 200 {
return Err("Email needs to be at most 200 characters long".to_string());
}
if !email_regex().is_match(email) {
return Err("Invalid email".to_string());
}
Ok(())
}
pub fn validate_name(name: &str) -> Result<(), String> {
let len = name.graphemes(true).count();
if len < 3 || len > 50 {
return Err("Name needs to be between 3 and 50 characters.".to_string());
}
if !name_regex().is_match(name) {
return Err("Invalid name".to_string());
}
Ok(())
}
pub fn validate_passwords(password1: &str, password2: &str) -> Result<(), String> {
if password1.is_empty() {
return Err("Password is required".to_string());
}
if password2.is_empty() {
return Err("Confirmation Password is required".to_string());
}
if password1 != password2 {
return Err("Passwords do not match".to_string());
}
let len = password1.graphemes(true).count();
if len < 8 || len > 40 {
return Err("Password needs to be between 8 and 40 characters.".to_string());
}
if !password_validator(password1) {
return Err("Password needs to have at least one lowercase letter, one uppercase letter, one number and one symbol.".to_string());
}
Ok(())
}
pub fn validate_jwt(jwt: &str) -> Result<(), String> {
let len = jwt.chars().count();
if len < 20 || len > 500 {
return Err("JWT needs to be between 20 and 500 characters.".to_string());
}
if !jwt_regex().is_match(jwt) {
return Err("Invalid JWT".to_string());
}
Ok(())
}
fn create_error_vec(validations: &[Result<(), String>]) -> Vec<&str> {
let mut errors = Vec::<&str>::new();
for error in validations {
if let Err(e) = error {
errors.push(e);
}
}
errors
}
pub fn error_handler(validations: &[Result<(), String>]) -> Result<(), String> {
let errors = create_error_vec(validations);
if errors.is_empty() {
Ok(())
} else {
Err(errors.join("\n"))
}
}
|
import React, { useState, useRef } from 'react';
import Counter from '../Counter/Counter';
const MainComponent = () => {
const [startValues, setStartValues] = useState([]);
const counterStartInputRef = useRef()
const onFormSubmitHandler = (e) => {
e.preventDefault()
setStartValues(prev => [...prev, +counterStartInputRef.current.value])
}
const handleCounterDelete = (counterId) => {
const tempArray = [...startValues.slice(0, counterId), ...startValues.slice(counterId + 1)]
setStartValues(tempArray)
}
return (
<div className='container my-3'>
<div className='row'>
<div className='col-6 offset-3 bg-dark text-light p-3 rounded'>
<h1>MainComponent</h1>
<hr />
<form onSubmit={onFormSubmitHandler}>
<div className='mb-3'>
<label htmlFor="counterStartValue" className='form-label'>Start value : </label>
<input type="number" id='CounterStartValue' className='form-control' min={0}
ref={counterStartInputRef} required/>
</div>
<button className='d-block ms-auto btn btn-outline-light'>Add a counter</button>
</form>
<div>
<h3>Counters</h3>
<hr />
{startValues.length === 0 && <p>Merci d'ajouter un compteur</p>}
{startValues.length > 0 && startValues.map((v,i) => <Counter startValue={v} key={i}
deleteCounter={() => handleCounterDelete(i)} />)}
</div>
</div>
</div>
</div>
);
}
export default MainComponent;
|
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Elzero</title>
<!-- Main Template file css -->
<link rel="stylesheet" href="css/normlaze.css">
<!-- Render All Element Normally -->
<link rel="stylesheet" href="css/master.css">
<!-- font awesome library -->
<link rel="stylesheet" href="css/all.min.css">
<!-- Google Font -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Josefin+Sans:ital,wght@0,100;0,200;0,400;0,500;0,600;0,700;1,100;1,200&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;1,100;1,200;1,300;1,400;1,500&family=Work+Sans:wght@200;300;500;700;800&display=swap"
rel="stylesheet">
</head>
<body>
<!-- start header -->
<div class="header">
<div class="container">
<a href="#" class="logo">Elzero</a>
<div class="main-nav">
<ul class="main-nav">
<li><a href="#">Articles</a></li>
<li><a href="#">Gallery</a></li>
<li><a href="#">Features</a></li>
<li class="active">
<a href="#">Other links</a>
<!-- start megamenu -->
<div class="mega-menu">
<div class="image">
<img src="image/megamenu.png" alt="">
</div>
<ul class="links">
<li><a href="#"><i class="far fa-comments fa-fw"></i>Testimonilsa</a></li>
<li> <a href="#"> <i class="far fa-user fa-fw"></i>Team Members</a></li>
<li> <a href="#"> <i class="far fa-building fa-fw"></i> Services</a></li>
<li> <a href="#"> <i class="far fa-check-circle fa-fw"></i>Our skills</a></li>
<li> <a href="#"> <i class="far fa-clipboard fa-fw"></i>How it Works</a></li>
</ul>
<ul class="links">
<li> <a href="#"> <i class="far fa-envelope fa-fw"></i>Events</a></li>
<li> <a href="#"> <i class="fas fa-plane-slash fa-fw"></i>Pricing Plans</a></li>
<li> <a href="#"> <i class="fas fa-video fa-fw"></i>Top Video</a></li>
<li> <a href="#"> <i class="fas fa-steam fa-fw"></i>Stats</a></li>
<li> <a href="#"> <i class="fas fa-dashboard fa-fw"></i>Request A Discount</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
<!-- end header -->
<!-- start landing -->
<div class="landing">
<div class="container">
<div class="text">
<h1>Welcome, To Elzero Worlds </h1>
<p>Here I am Gonna Share Everything My Life. Book I am Reading. Games Playing. Stories and Events </p>
</div>
<div class="image">
<img src="image/landing-image.png" alt="">
</div>
</div>
<a href="#" class="go-down">
<i class="fas fa-angle-double-down fa-2x"></i>
</a>
</div>
<!-- end landing -->
<!-- start article -->
<div class="article">
<h2 class="main-title">Article</h2>
<div class="container">
<div class="box">
<img src="image/cat-01.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-02.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-03.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-04.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-05.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-06.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-07.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
<div class="box">
<img src="image/cat-08.jpg" alt="">
<div class="content-box">
<h3>Test Title</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Earum harum </p>
</div>
<div class="info">
<a href="#">Read More</a>
<i class="fas fa-long-arrow-alt-right"></i>
</div>
</div>
</div>
</div>
<!-- end article -->
<!-- start gallery -->
<div class="gallery">
<h2 class="main-title">Gallery</h2>
<div class="container">
<div class="box">
<div class="image">
<img src="image/gallery-01.png" alt="">
</div>
</div>
<div class="box">
<div class="image">
<img src="image/gallery-02.png" alt="">
</div>
</div>
<div class="box">
<div class="image">
<img src="image/gallery-03.jpg" alt="">
</div>
</div>
<div class="box">
<div class="image">
<img src="image/gallery-04.png" alt="">
</div>
</div>
<div class="box">
<div class="image">
<img src="image/gallery-05.jpg" alt="">
</div>
</div>
<div class="box">
<div class="image">
<img src="image/gallery-06.png" alt="">
</div>
</div>
</div>
</div>
<!-- end gallery -->
<!-- start feature -->
<div class="feature">
<h2 class="main-title">Features</h2>
<div class="container">
<div class="box quality">
<div class="img-holder">
<img src="image/features-01.jpg" alt="">
</div>
<h3>Quality</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente necessitatibus, </p>
<a href="#">More</a>
</div>
<div class="box time">
<div class="img-holder">
<img src="image/features-02.jpg" alt="">
</div>
<h3>Time</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente necessitatibus, </p>
<a href="#">More</a>
</div>
<div class="box passion">
<div class="img-holder">
<img src="image/features-03.jpg" alt="">
</div>
<h3>passion</h3>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Sapiente necessitatibus, </p>
<a href="#">More</a>
</div>
</div>
</div>
<!-- end feature -->
<!-- start TESTIMONIALS -->
<div class="testimonials">
<h2 class="main-title">TESTIMONIALS</h2>
<div class="container">
<div class="card">
<div class="card-img">
<img src="image/avatar-01.png" alt="">
</div>
<h2>Adem Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
<div class="card">
<div class="card-img">
<img src="image/avatar-02.png" alt="">
</div>
<h2>Omer Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="far fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
<div class="card">
<div class="card-img">
<img src="image/avatar-03.png" alt="">
</div>
<h2>Ismail Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="far fa-star"></i>
<i class="far fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
<div class="card">
<div class="card-img">
<img src="image/avatar-04.png" alt="">
</div>
<h2>Ahmed Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="far fa-star"></i>
<i class="far fa-star"></i>
<i class="far fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
<div class="card">
<div class="card-img">
<img src="image/avatar-05.png" alt="">
</div>
<h2>Hamza Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="far fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
<div class="card">
<div class="card-img">
<img src="image/avatar-06.png" alt="">
</div>
<h2>khalid Amin</h2>
<p>Full Stack Developer </p>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<i class="fas fa-star"></i>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Pariatur provident quis </p>
</div>
</div>
</div>
<!-- end TESTIMONIALS -->
<!-- start team members -->
<div class="team">
<h2 class="main-title">Team Members</h2>
<div class="container">
<div class="box">
<div class="data">
<img src="image/team-02.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-03.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-04.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-05.png" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-06.png" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-07.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-01.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
<div class="box">
<div class="data">
<img src="image/team-08.jpg" alt="">
<div class="social">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-linkedin"></i></a>
<a href="#"><i class="fab fa-whatsapp"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
</div>
</div>
<div class="info">
<h2>khalid</h2>
<p>simple short description</p>
</div>
</div>
</div>
</div>
<!-- end team -->
<!-- start services -->
<div class="services">
<h2 class="main-title">services</h2>
<div class="container">
<div class="box">
<i class="fas fa-user-shield fa-4x"></i>
<h3>security</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
<div class="box">
<i class="fas fa-store-alt fa-4x"></i>
<h3>Fixing issues</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
<div class="box">
<i class="fas fa-location fa-4x"></i>
<h3>location</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
<div class="box">
<i class="fas fa-code fa-4x"></i>
<h3>coding</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
<div class="box">
<i class="fas fa-school-circle-check fa-4x"></i>
<h3>security</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
<div class="box">
<i class="fas fa-marker fa-4x"></i>
<h3>marketing</h3>
<div class="info">
<a href="#">Details</a>
</div>
</div>
</div>
</div>
<!-- end services -->
<!-- start our-skills -->
<div class="our-skills">
<h2 class="main-title">our-skills</h2>
<div class="container">
<img src="image/skills.png" alt="">
<div class="skills">
<div class="skill">
<h3>Html <span>80%</span></h3>
<div class="the-progress">
<span style="width: 80%"> </span>
</div>
</div>
<div class="skill">
<h3>css <span>70%</span></h3>
<div class="the-progress">
<span style="width: 70%"> </span>
</div>
</div>
<div class="skill">
<h3>JavaScript <span>60%</span></h3>
<div class="the-progress">
<span style="width: 60%"> </span>
</div>
</div>
<div class="skill">
<h3>PHP <span>40%</span></h3>
<div class="the-progress">
<span style="width: 40%"> </span>
</div>
</div>
</div>
</div>
</div>
<!-- end our-skills -->
<!-- start works -->
<div class="work-step">
<h2 class="main-title">HOW IT WORKS</h2>
<div class="container">
<img src="image/work-steps.png" alt="" class="image">
<div class="into">
<div class="box">
<img src="image/work-steps-1.png" alt="">
<div class="text">
<h3> Business Analysis</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam voluptate quae obcaecati
suscipit quisquam </p>
</div>
</div>
<div class="box">
<img src="image/work-steps-2.png" alt="">
<div class="text">
<h3>Architecture</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam voluptate quae obcaecati
suscipit quisquam </p>
</div>
</div>
<div class="box">
<img src="image/work-steps-3.png" alt="">
<div class="text">
<h3>Development</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quam voluptate quae obcaecati
suscipit quisquam </p>
</div>
</div>
</div>
</div>
</div>
<!-- end works -->
<!-- start LATEST EVENTS-->
<div class="event">
<h2 class="main-title">LATEST EVENTS</h2>
<div class="container">
<img src="image/events.png" alt="">
<div class="info-ev">
<div class="time">
<div class="unit">
<span>15</span>
<span>Days</span>
</div>
<div class="unit">
<span>08</span>
<span>Hour</span>
</div>
<div class="unit">
<span>45</span>
<span>Minute</span>
</div>
<div class="unit">
<span>55</span>
<span>Second</span>
</div>
</div>
<h2 class="title">Tech Master Event 2023</h2>
<p class="description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Asperiores facilis
dolorum voluptates ea ipsam nesciunt sint mollitia minima incidunt velit, quae magni quibusdam
recusandae optio quo? Iusto, ex. Modi, nulla?</p>
</div>
<div class="subscribe">
<form action="">
<input type="email" placeholder="Enter Your Email">
<input type="submit" value="subscribe">
</form>
</div>
</div>
</div>
<!-- end LATEST EVENTS -->
<!-- start pricing -->
<div class="pricing">
<h2 class="main-title">PRICING PLANS</h2>
<div class="container">
<div class="box-pr">
<h3 class="title">Basic</h3>
<img src="image/hosting-basic.png" alt="">
<div class="price">
<span class="amount">$15</span>
<span class="time">per month</span>
</div>
<ul>
<li>10GB HDD Space</li>
<li>5 Email Addresses</li>
<li>2 Subdomains</li>
<li>4 Databases</li>
<li>Basic Support</li>
</ul>
<a href="#">choose plan</a>
</div>
<div class="box-pr popular">
<div class="label">Most Popular</div>
<div class="title">Advanced</div>
<img src="image/hosting-advanced.png" alt="">
<div class="price">
<span class="amount">$30</span>
<span class="time">per month</span>
</div>
<ul>
<li>15GB HDD Space</li>
<li>10 Email Addresses</li>
<li>3 Subdomains</li>
<li>8 Databases</li>
<li>Advance Support</li>
</ul>
<a href="#">choose plan</a>
</div>
<div class="box-pr">
<div class="title">Professional</div>
<img src="image/hosting-advanced.png" alt="">
<div class="price">
<span class="amount">$45</span>
<span class="time">per month</span>
</div>
<ul>
<li>30GB HDD Space</li>
<li>15 Email Addresses</li>
<li>9 Subdomains</li>
<li>14 Databases</li>
<li>Professional Support</li>
</ul>
<a href="#">choose plan
</div>
</div>
</div>
</div>
<!-- start pricing -->
<!-- start video -->
<div class="videos">
<h2 class="main-title">TOP VIDEOS</h2>
<div class="container">
<div class="holder">
<div class="list">
<div class="name">
Top videos
<i class="fas fa-random"></i>
</div>
<ul>
<li>How to Create Sub Domain <span>05:18</span></li>
<li>Playing with The DNS<span>03:25</span></li>
<li>Everything About The Virtual Hosts<span>05:32</span></li>
<li>How To Monitor Your Website<span>04:41</span></li>
<li>Uncharted Beating The Last Overview<span>07:45</span></li>
<li>Ys Series All Games Ending<span>08:25</span></li>
</ul>
</div>
<div class="preview">
<img src="image/video-preview.jpg" alt="">
<div class="info-ved">Everything About The Virtual Hosts</div>
</div>
</div>
</div>
</div>
<!-- end video -->
<!-- start stats -->
<div class="stats">
<h2>Our Awesome Stats</h2>
<div class="container">
<div class="box-stat">
<i class="far fa-user fa-2x fa-fw"></i>
<span class="number">57</span>
<span class="text">Clients</span>
</div>
<div class="box-stat">
<i class="fas fa-percent fa-2x fa-fw"></i>
<span class="number">93</span>
<span class="text">Projects</span>
</div>
<div class="box-stat">
<i class="fas fa-code fa-2x fa-fw"></i>
<span class="number">125</span>
<span class="text">Countries</span>
</div>
<div class="box-stat">
<i class="fas fa-money-bill fa-2x fa-fw"></i>
<span class="number">150</span>
<span class="text">Mony</span>
</div>
</div>
</div>
<!-- end stats -->
<!-- start discount -->
<div class="discount">
<div class="image">
<div class="content-dis">
<h2>We Have A Discount</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam cum quas excepturi aspernatur fugiat.
Sint dolores asperiores dolorum repellendus! Perferendis voluptate natus eum perspiciatis assumenda
unde dicta officiis repellendus adipisci!</p>
</div>
</div>
<div class="form">
<div class="content-dis">
<h2>Request A Discount</h2>
<form action="">
<input type="text" class="input" placeholder="Your Name" name="name">
<input type="email" class="input" name="email" placeholder="Your Email">
<input type="text" class="input" name="mobile" placeholder="Your Phone">
<textarea class="input" name="message" placeholder="Tell Us About Needs"></textarea>
<input type="submit" value="send">
</form>
</div>
</div>
</div>
<!-- end discount -->
<!-- start footer -->
<div class="footer">
<div class="container">
<div class="box-foot">
<h3>Elzero</h3>
<div class="social">
<ul>
<li> <a href="#" class="facebook"> <i class="fab fa-twitter"> </i> </a> </li>
<li> <a href="#" class="twitter"> <i class="fab fa-facebook-f"> </i> </a> </li>
<li> <a href="#" class="youtube"> <i class="fab fa-youtube"> </i> </a> </li>
</ul>
</div>
<p class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Amet necessitatibus ab, minus molestiae
iste quia sequi excepturi! Neque voluptatem quas vel alias et
</p>
</div>
<div class="box-foot">
<div class="links">
<li><a href="#">Important link 1</a></li>
<li><a href="#">Important link 2</a></li>
<li><a href="#">Important link 3</a></li>
<li><a href="#">Important link 4</a></li>
<li><a href="#">Important link 5</a></li>
</div>
</div>
<div class="box-foot">
<div class="line">
<i class="fas fa-map-marked-alt fa-fw"></i>
<div class="info-foot">Sudan , Omdurman , Inside The Bank , Room Number +249</div>
</div>
<div class="line">
<i class="fas fa-clock fa-fw"></i>
<div class="info-foot">Business Hours: From 10:00 To 18:00</div>
</div>
<div class="line">
<i class="fas fa-phone-volume fa-fw"></i>
<div class="info-foot">
<span>+24992375460</span>
<span>+249115818480</span>
</div>
</div>
</div>
<div class="box-foot footer-gallery">
<img src="image/gallery-01.png" alt="">
<img src="image/gallery-02.png" alt="">
<img src="image/gallery-03.jpg" alt="">
<img src="image/gallery-04.png" alt="">
<img src="image/gallery-05.jpg" alt="">
<img src="image/gallery-06.png" alt="">
</div>
</div>
<p class="copyright">Mead With <3 By Elzero</p>
</div>
<!-- emd footer -->
</body>
</html>
|
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import logging
import os
from typing import Any, Dict, List, Optional, Tuple
from loguru import logger
from utils.config_utils import (
create_agent_config,
create_env_config,
get_habitat_config,
get_omega_config,
)
from utils.env_utils import create_ovmm_env_fn
from home_robot.agent.multitask import get_parameters
from home_robot.agent.multitask.robot_agent import RobotAgent
from home_robot.perception import create_semantic_sensor
from home_robot.utils.rpc import get_vlm_rpc_stub
from home_robot_sim.ovmm_sim_client import OvmmSimClient, SimGraspPlanner
os.environ["OPENBLAS_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["MKL_NUM_THREADS"] = "1"
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--num_episodes", type=int, default=None)
parser.add_argument(
"--habitat_config_path",
type=str,
default="ovmm/ovmm_eval.yaml",
help="Path to config yaml",
)
parser.add_argument(
"--env_config_path",
type=str,
default="projects/habitat_ovmm/configs/env/hssd_demo_robot_agent.yaml",
help="Path to config yaml",
)
parser.add_argument(
"--agent_parameters",
type=str,
default="src/home_robot_sim/configs/default.yaml",
help="path to parameters file for agent",
)
parser.add_argument(
"--device_id",
type=int,
default=0,
help="GPU device id",
)
parser.add_argument(
"--rate",
type=int,
default=5,
help="rate?",
)
parser.add_argument(
"--vlm_server_addr",
default="cortex-robot-elb-57c549656770fe85.elb.us-east-1.amazonaws.com",
help="ip address or domain name of vlm server.",
)
parser.add_argument(
"--vlm_server_port",
default="50054",
help="port of vlm server.",
)
parser.add_argument(
"--manual_wait",
type=bool,
default=False,
help="manual_wait?",
)
parser.add_argument(
"--navigate_home",
type=bool,
default=False,
help="manual_wait?",
)
parser.add_argument(
"--verbose",
type=bool,
default=True,
help="verbose output",
)
parser.add_argument(
"--show_intermediate_maps",
type=bool,
default=True,
help="verbose output",
)
parser.add_argument(
"overrides",
default=None,
nargs=argparse.REMAINDER,
help="Modify config options from command line",
)
args = parser.parse_args()
# get habitat config
habitat_config, _ = get_habitat_config(
args.habitat_config_path, overrides=args.overrides
)
# get env config
env_config = get_omega_config(args.env_config_path)
# merge habitat and env config to create env config
env_config = create_env_config(habitat_config, env_config, evaluation_type="local")
logger.info("Creating OVMM simulation environment")
env = create_ovmm_env_fn(env_config)
robot = OvmmSimClient(sim_env=env, is_stretch_robot=True)
print("- Create semantic sensor based on detic")
config, semantic_sensor = create_semantic_sensor(
device_id=args.device_id, verbose=args.verbose
)
grasp_client = SimGraspPlanner(robot)
parameters = get_parameters(args.agent_parameters)
print(parameters)
object_to_find, location_to_place = robot.get_task_obs()
stub = get_vlm_rpc_stub(
vlm_server_addr=args.vlm_server_addr, vlm_server_port=args.vlm_server_port
)
demo = RobotAgent(
robot, semantic_sensor, parameters, rpc_stub=stub, grasp_client=grasp_client
)
demo.start(goal=object_to_find, visualize_map_at_start=args.show_intermediate_maps)
matches = demo.get_found_instances_by_class(object_to_find)
# demo.robot.navigate_to([-0.1, 0, 0], relative=True)
# demo.update()
# import numpy as np
# demo.robot.navigate_to([0, 0, np.pi / 4], relative=True)
# demo.update()
# demo.robot.navigate_to([0, 0, np.pi / 4], relative=True)
# demo.update()
breakpoint()
print("rotate in place for a bit")
demo.rotate_in_place(steps=12)
demo.run_exploration(
args.rate,
args.manual_wait,
explore_iter=parameters["exploration_steps"],
task_goal=object_to_find,
go_home_at_end=args.navigate_home,
)
print("Done collecting data (exploration).")
matches = demo.get_found_instances_by_class(object_to_find)
print("-> Found", len(matches), f"instances of class {object_to_find}.")
demo.execute_vlm_plan()
print(f"- Move to any instance of {object_to_find}")
try:
smtai = demo.move_to_any_instance(matches)
if not smtai:
print("Moving to instance failed!")
else:
print(f"- Grasp {object_to_find} using FUNMAP")
res = demo.grasp(object_goal=object_to_find)
print(f"- Grasp result: {res}")
matches = demo.get_found_instances_by_class(location_to_place)
if len(matches) == 0:
print(f"!!! No location {location_to_place} found. Exploring !!!")
demo.run_exploration(
rate,
manual_wait,
explore_iter=explore_iter,
task_goal=location_to_place,
go_home_at_end=navigate_home,
)
print(f"- Move to any instance of {location_to_place}")
smtai2 = demo.move_to_any_instance(matches)
if not smtai2:
print(f"Going to instance of {location_to_place} failed!")
else:
print(f"- Placing on {location_to_place} using FUNMAP")
if not no_manip:
# run_grasping(
# robot,
# semantic_sensor,
# to_grasp=None,
# to_place=location_to_place,
# )
pass
except RuntimeError as e:
raise (e)
finally:
demo.voxel_map.write_to_pickle("test.pkl")
# breakpoint()
# # create evaluator
# evaluator = OVMMEvaluator(env_config)
# # evaluate agent
# metrics = evaluator.evaluate(
# agent=agent,
# evaluation_type=args.evaluation_type,
# num_episodes=args.num_episodes,
# )
# print("Metrics:\n", metrics)
|
/*
Assignment #3: Finding Prime Numbers
Author: Steve Defendre
due date: 10/04/2023
Description: This program takes a range of integers as input from the user and
finds all the prime numbers within that range.
*/
import java.util.Scanner;
public class PrimeNumberFinder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Main loop to repeatedly ask for a range and find primes.
while (true) {
// Ask the user for the range
System.out.print("Enter the lower bound of the range: ");
int lowerBound = scanner.nextInt();
System.out.print("Enter the upper bound of the range: ");
int upperBound = scanner.nextInt();
System.out.printf("Computing prime numbers between %d and %d:\n", lowerBound, upperBound);
int sequenceNumber = 1;
// Loop through all odd integers > 1 in the given range
for (int candidate = Math.max(2, lowerBound); candidate <= upperBound; candidate++) {
if (isPrime(candidate)) {
System.out.printf("%d. %d\n", sequenceNumber, candidate);
sequenceNumber++;
}
}
System.out.println("Do you want to continue? (y/n)");
String response = scanner.next();
if (response.equalsIgnoreCase("n")) {
break;
}
}
scanner.close();
} //main
/**
* Check if a number is prime.
* @param n The number to check.
* @return true if the number is prime, false otherwise.
*/
public static boolean isPrime(int n) {
if (n <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(n); i++) { // No need to go beyond sqrt(n)
if (n % i == 0) {
return false;
}
}
return true;
}
} //class PrimeNumberFinder
|
use cosmwasm_std::{to_binary, Deps};
use crate::{
core::{aliases::ProvQueryResponse, msg::QueryOwnerResponse},
storage,
};
/// Performs the logic for the QueryOwner message and obtains the contract's owner.
///
/// # Arguments
///
/// * `deps` - A non mutable version of the dependencies. The API, Querier, and storage can all be accessed from it.
///
/// # Examples
/// ```
/// let res = handle(deps)?;
/// ```
pub fn handle(deps: Deps) -> ProvQueryResponse {
let res = QueryOwnerResponse {
owner: storage::state::get_owner(deps.storage)?,
};
Ok(to_binary(&res)?)
}
#[cfg(test)]
mod tests {
use cosmwasm_std::{from_binary, Addr};
use provwasm_mocks::mock_provenance_dependencies;
use crate::{
core::msg::QueryOwnerResponse,
testing::{constants::OWNER, setup},
};
use super::handle;
#[test]
fn test_query_owner_has_correct_response() {
let mut deps = mock_provenance_dependencies();
setup::mock_contract(deps.as_mut());
let bin = handle(deps.as_ref()).unwrap();
let response: QueryOwnerResponse = from_binary(&bin).unwrap();
assert_eq!(Addr::unchecked(OWNER), response.owner);
}
}
|
import API from "./Api";
/**
* Create table reservation with the provided details object using the provided authentication token
* @param {Object} putTableDetails the table reservation details object
* @param {string} token the authentication token
* @returns {Promise<any>} promise that resolves to the updated table reservation details
* @throws {Error} error if the API request fails
*/
export const putTableReservation = async (putTableDetails: Object, token: string): Promise<any> => {
try {
const response = await API.put(`/table`, token, putTableDetails);
return response;
} catch (error) {
console.error(error);
}
};
/**
* Updates specific properties of the table reservation details with the provided details object using the provided authentication token
* @param {Object} putTableDetails the table reservation details object containing the properties to be updated
* @param {string} token the authentication token
* @returns {Promise<any>} promise that resolves to the updated table reservation details
* @throws {Error} error if the API request fails
*/
export const patchTableReservation = async (putTableDetails: Object, token: string): Promise<any> => {
try {
const response = await API.patch(`/table`, token, putTableDetails);
return response;
} catch (error) {
console.error(error);
}
};
/**
* Deletes the table reservation with the provided details object using the provided authentication token
* @param {Object} putTableDetails the table reservation details object identifying the reservation to be deleted
* @param {string} token the authentication token
* @returns {Promise<any>} promise that resolves to the result of the deletion operation
* @throws {Error } error if the API request fails
*/
export const deleteTableReservation = async (putTableDetails: Object, token: string): Promise<any> => {
try {
const response = await API.delete(`/table`, token, putTableDetails);
return response;
} catch (error) {
console.error(error);
}
};
|
/**
@file Color4.cpp
Color class.
@author Morgan McGuire, http://graphics.cs.williams.edu
@cite Portions by Laura Wollstadt, graphics3d.com
@cite Portions based on Dave Eberly's Magic Software Library at http://www.magic-software.com
@created 2002-06-25
@edited 2009-11-10
*/
#include <stdlib.h>
#include "G3D/Color4.h"
#include "G3D/Color4uint8.h"
#include "G3D/Vector4.h"
#include "G3D/format.h"
#include "G3D/BinaryInput.h"
#include "G3D/BinaryOutput.h"
#include "G3D/Any.h"
#include "G3D/stringutils.h"
namespace G3D {
Color4::Color4(const Any& any) {
*this = Color4::zero();
any.verifyName("Color4");
if (any.type() == Any::TABLE) {
for (Any::AnyTable::Iterator it = any.table().begin(); it.hasMore(); ++it) {
const std::string& key = toLower(it->key);
if (key == "r") {
r = it->value;
} else if (key == "g") {
g = it->value;
} else if (key == "b") {
b = it->value;
} else if (key == "a") {
a = it->value;
} else {
any.verify(false, "Illegal key: " + it->key);
}
}
} else if (toLower(any.name()) == "color4") {
r = any[0];
g = any[1];
b = any[2];
a = any[3];
} else {
any.verifyName("Color4::fromARGB");
*this = Color4::fromARGB((int)any[0].number());
}
}
Color4::operator Any() const {
Any any(Any::ARRAY, "Color4");
any.append(r, g, b, a);
return any;
}
const Color4& Color4::one() {
const static Color4 x(1.0f, 1.0f, 1.0f, 1.0f);
return x;
}
const Color4& Color4::zero() {
static Color4 c(0.0f, 0.0f, 0.0f, 0.0f);
return c;
}
const Color4& Color4::inf() {
static Color4 c((float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf(), (float)G3D::finf());
return c;
}
const Color4& Color4::nan() {
static Color4 c((float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan(), (float)G3D::fnan());
return c;
}
const Color4& Color4::clear() {
return Color4::zero();
}
Color4::Color4(const Vector4& v) {
r = v.x;
g = v.y;
b = v.z;
a = v.w;
}
Color4::Color4(const Color4uint8& c) : r(c.r), g(c.g), b(c.b), a(c.a) {
*this /= 255.0f;
}
size_t Color4::hashCode() const {
unsigned int rhash = (*(int*)(void*)(&r));
unsigned int ghash = (*(int*)(void*)(&g));
unsigned int bhash = (*(int*)(void*)(&b));
unsigned int ahash = (*(int*)(void*)(&a));
return rhash + (ghash * 37) + (bhash * 101) + (ahash * 241);
}
Color4 Color4::fromARGB(uint32 x) {
return Color4(
(float)((x >> 16) & 0xFF),
(float)((x >> 8) & 0xFF),
(float)(x & 0xFF),
(float)((x >> 24) & 0xFF)) / 255.0;
}
Color4::Color4(BinaryInput& bi) {
deserialize(bi);
}
void Color4::deserialize(BinaryInput& bi) {
r = bi.readFloat32();
g = bi.readFloat32();
b = bi.readFloat32();
a = bi.readFloat32();
}
void Color4::serialize(BinaryOutput& bo) const {
bo.writeFloat32(r);
bo.writeFloat32(g);
bo.writeFloat32(b);
bo.writeFloat32(a);
}
//----------------------------------------------------------------------------
Color4 Color4::operator/ (float fScalar) const {
Color4 kQuot;
if (fScalar != 0.0f) {
float fInvScalar = 1.0f / fScalar;
kQuot.r = fInvScalar * r;
kQuot.g = fInvScalar * g;
kQuot.b = fInvScalar * b;
kQuot.a = fInvScalar * a;
return kQuot;
} else {
return Color4::inf();
}
}
//----------------------------------------------------------------------------
Color4& Color4::operator/= (float fScalar) {
if (fScalar != 0.0f) {
float fInvScalar = 1.0f / fScalar;
r *= fInvScalar;
g *= fInvScalar;
b *= fInvScalar;
a *= fInvScalar;
} else {
r = (float)G3D::finf();
g = (float)G3D::finf();
b = (float)G3D::finf();
a = (float)G3D::finf();
}
return *this;
}
//----------------------------------------------------------------------------
std::string Color4::toString() const {
return G3D::format("(%g, %g, %g, %g)", r, g, b, a);
}
//----------------------------------------------------------------------------
}; // namespace
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.