<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<fieldset id = 'bonobo_fieldset'>
<label>Text eingeben:</label>
<textarea id='input'></textarea><br>
<button type="button" id="btn">Text verschlüsseln</button><br> <br>
<p id='text'></p>
<script>
var fieldset = document.getElementById('bonobo_fieldset');
var h4 = document.createElement('h4');
h4.innerHTML = '';
h4.textContent = '';
fieldset.appendChild(h4);
var btn = document.getElementById('btn');
btn.addEventListener('click', verschlüsseln);
var p_text = document.getElementById('text');
var Arr = new Array(
['a', 1],
['b', 2],
['c', 3],
['d', 4],
['e', 5],
['f', 6],
['g', 7],
['h', 8],
['i', 9],
['j', 10],
['k', 11],
['l', 12],
['m', 13],
['n', 14],
['o', 15],
['p', 16],
['q', 17],
['r', 18],
['s', 19],
['t', 20],
['u', 21],
['v', 22],
['w', 23],
['x', 24],
['y', 25],
['z', 26]
);
function verschlüsseln()
{
var input = document.getElementById('input').value;
input = input.toLowerCase
var rex = /[A-z]/;
for (i = 0; i < input.length; i++)
{
if (rex.test(input.charAt(i))) {
Arr.forEach(convert_to_number);
function convert_to_number(value) {
console.log(input.charAt(i));
console.log(value[0].toUpperCase());
if (input.charAt(i) === value[0]) {
input = input.replace(input.charAt(i), value[1]);
}
}
}
}
document.getElementById('text').textContent = input;
}
</script>
</fieldset>
</div>
</body>
</html>
So i´m still quite new to coding , and today i came up with this very simple encryption , the letters you put into the input textarea , simply become their index number in the Alphabet (1-26)
so for example (a = 1 , b = 2, c = 3, g = 7... and so on)
now since this encryption really is pretty simple and straight forward , i just cant think of a way to decode it , yet these are the things im interested the most in.
the problem is a = 1 , while j-s = 10-19. so how can i write a code , that lets the program decide on wether its an a , or a j-s?
thanks to anyone helping me out
wish you a good one!
Related
I am wanting to add application insights sdk into a blazor web assembly project. I came across multiple articles such as Application Insights for web pages and stackoverflow that has the exact thing I am looking for. However, after adding the snippet of code from the microsoft link and using connectionString over instrumentationKey to the index.html page and injecting IJSRuntime in order to call JavaScript methods from .NET code then calling Application Inisghts methods... when running the application at the top of the home page I will see #inject IJSRuntime _jsRuntime.
Am I not properly setting up the injecting? Also, do I need to add these lines of code into each razor component (page folder) or just having it in the index.html will cover everything from the start to end no matter what I click and what page is rendered?
Index.html
#inject IJSRuntime _jsRuntime
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
!function (T, l, y) { var S = T.location, k = "script", D = "connectionString", C = "ingestionendpoint", I = "disableExceptionTracking", E = "ai.device.", b = "toLowerCase", w = "crossOrigin", N = "POST", e = "appInsightsSDK", t = y.name || "appInsights"; (y.name || T[e]) && (T[e] = t); var n = T[t] || function (d) { var g = !1, f = !1, m = { initialize: !0, queue: [], sv: "5", version: 2, config: d }; function v(e, t) { var n = {}, a = "Browser"; return n[E + "id"] = a[b](), n[E + "type"] = a, n["ai.operation.name"] = S && S.pathname || "_unknown_", n["ai.internal.sdkVersion"] = "javascript:snippet_" + (m.sv || m.version), { time: function () { var e = new Date; function t(e) { var t = "" + e; return 1 === t.length && (t = "0" + t), t } return e.getUTCFullYear() + "-" + t(1 + e.getUTCMonth()) + "-" + t(e.getUTCDate()) + "T" + t(e.getUTCHours()) + ":" + t(e.getUTCMinutes()) + ":" + t(e.getUTCSeconds()) + "." + ((e.getUTCMilliseconds() / 1e3).toFixed(3) + "").slice(2, 5) + "Z" }(), iKey: e, name: "Microsoft.ApplicationInsights." + e.replace(/-/g, "") + "." + t, sampleRate: 100, tags: n, data: { baseData: { ver: 2 } } } } var h = d.url || y.src; if (h) { function a(e) { var t, n, a, i, r, o, s, c, u, p, l; g = !0, m.queue = [], f || (f = !0, t = h, s = function () { var e = {}, t = d.connectionString; if (t) for (var n = t.split(";"), a = 0; a < n.length; a++) { var i = n[a].split("="); 2 === i.length && (e[i[0][b]()] = i[1]) } if (!e[C]) { var r = e.endpointsuffix, o = r ? e.location : null; e[C] = "https://" + (o ? o + "." : "") + "dc." + (r || "services.visualstudio.com") } return e }(), c = s[D] || d[D] || "", u = s[C], p = u ? u + "/v2/track" : d.endpointUrl, (l = []).push((n = "SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details)", a = t, i = p, (o = (r = v(c, "Exception")).data).baseType = "ExceptionData", o.baseData.exceptions = [{ typeName: "SDKLoadFailed", message: n.replace(/\./g, "-"), hasFullStack: !1, stack: n + "\nSnippet failed to load [" + a + "] -- Telemetry is disabled\nHelp Link: https://go.microsoft.com/fwlink/?linkid=2128109\nHost: " + (S && S.pathname || "_unknown_") + "\nEndpoint: " + i, parsedStack: [] }], r)), l.push(function (e, t, n, a) { var i = v(c, "Message"), r = i.data; r.baseType = "MessageData"; var o = r.baseData; return o.message = 'AI (Internal): 99 message:"' + ("SDK LOAD Failure: Failed to load Application Insights SDK script (See stack for details) (" + n + ")").replace(/\"/g, "") + '"', o.properties = { endpoint: a }, i }(0, 0, t, p)), function (e, t) { if (JSON) { var n = T.fetch; if (n && !y.useXhr) n(t, { method: N, body: JSON.stringify(e), mode: "cors" }); else if (XMLHttpRequest) { var a = new XMLHttpRequest; a.open(N, t), a.setRequestHeader("Content-type", "application/json"), a.send(JSON.stringify(e)) } } }(l, p)) } function i(e, t) { f || setTimeout(function () { !t && m.core || a() }, 500) } var e = function () { var n = l.createElement(k); n.src = h; var e = y[w]; return !e && "" !== e || "undefined" == n[w] || (n[w] = e), n.onload = i, n.onerror = a, n.onreadystatechange = function (e, t) { "loaded" !== n.readyState && "complete" !== n.readyState || i(0, t) }, n }(); y.ld < 0 ? l.getElementsByTagName("head")[0].appendChild(e) : setTimeout(function () { l.getElementsByTagName(k)[0].parentNode.appendChild(e) }, y.ld || 0) } try { m.cookie = l.cookie } catch (p) { } function t(e) { for (; e.length;)!function (t) { m[t] = function () { var e = arguments; g || m.queue.push(function () { m[t].apply(m, e) }) } }(e.pop()) } var n = "track", r = "TrackPage", o = "TrackEvent"; t([n + "Event", n + "PageView", n + "Exception", n + "Trace", n + "DependencyData", n + "Metric", n + "PageViewPerformance", "start" + r, "stop" + r, "start" + o, "stop" + o, "addTelemetryInitializer", "setAuthenticatedUserContext", "clearAuthenticatedUserContext", "flush"]), m.SeverityLevel = { Verbose: 0, Information: 1, Warning: 2, Error: 3, Critical: 4 }; var s = (d.extensionConfig || {}).ApplicationInsightsAnalytics || {}; if (!0 !== d[I] && !0 !== s[I]) { var c = "onerror"; t(["_" + c]); var u = T[c]; T[c] = function (e, t, n, a, i) { var r = u && u(e, t, n, a, i); return !0 !== r && m["_" + c]({ message: e, url: t, lineNumber: n, columnNumber: a, error: i }), r }, d.autoExceptionInstrumented = !0 } return m }(y.cfg); function a() { y.onInit && y.onInit(n) } (T[t] = n).queue && 0 === n.queue.length ? (n.queue.push(a), n.trackPageView({})) : a() }(window, document, {
src: "https://js.monitor.azure.com/scripts/b/ai.2.min.js", // The SDK URL Source
// name: "appInsights", // Global SDK Instance name defaults to "appInsights" when not supplied
// ld: 0, // Defines the load delay (in ms) before attempting to load the sdk. -1 = block page load and add to head. (default) = 0ms load after timeout,
// useXhr: 1, // Use XHR instead of fetch to report failures (if available),
crossOrigin: "anonymous", // When supplied this will add the provided value as the cross origin attribute on the script tag
// onInit: null, // Once the application insights instance has loaded and initialized this callback function will be called with 1 argument -- the sdk instance (DO NOT ADD anything to the sdk.queue -- As they won't get called)
cfg: { // Application Insights Configuration
connectionString: "CONNECTIONSTRING_KEY_GOES_HERE"
/* ...Other Configuration Options... */
}
});
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>BlazorWeb</title>
<base href="/" />
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="css/app.css" rel="stylesheet" />
<link href="BlazorWeb.styles.css" rel="stylesheet" />
</head>
<body>
<div id="app">Loading...</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
Reload
<a class="dismiss">🗙</a>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
await _jsRuntime.InvokeVoidAsync("appInsights.trackPageView");
</html>
Injecting the Application Insights for Blazor web applications. Steps to be followed
Add BlazorApplicationInsights
Nuget
dotnet add package BlazorApplicationInsights
Add call to Program.cs
builder.Services.AddBlazorApplicationInsights();
Add using statement to _Imports.razor
#using BlazorApplicationInsights;
Add component to App.razor
<ApplicationInsightsComponent />
Add Application Insights JS to head in index.html
Source
Set 'ld: -1' so that the page will be blocked until the JS is loaded and enter your instrumentationKey
Add the Source like below screenshot
Add JS Interop to the bottom of body in index.html
I can see the Track Event button which I was used.
Also, I can see the custom Event in Application Insights.
Refer here
So I want to draw directory structures as tree graphs. I'm using NetworkLayout.jl. I'm stuck on Step 1, but I can do Step 2 and Step 3.
Build a list of links between files and folders, to produce something like this (hand-made) one:
links = Pair[
"/" => "System",
"/" => "Library",
"/" => "Users",
"System" => "sys1",
"System" => "sys2",
"System" => "sys3",
"Library" => "lib1",
"Library" => "lib2",
"Library" => "lib3",
"Users" => "u1",
"Users" => "u2",
"Users" => "u3",
"Users" => "u4",
"Users" => "u5",
"u5" => "MyFolder"]
Create an adjacency list. This is easy enough if all the links are unique (also handmade):
adjlist = [
[2, 3, 4],
[5, 6, 7],
[8, 9, 10],
[],
[11],
[],
[],
[11, 12, 13, 14],
[],
[],
[15],
[],
[],
[],
[]]
Make a layout. This is the easy bit, because NetworkLayout.jl does it all for you:
using NetworkLayout
NetworkLayout.Buchheim.layout(adjlist)
...>
GeometryTypes.Point{2,Float64}[[0.0, -0.0], [-2.0, -2.0], [1.0, -2.0],
[2.0, -2.0], [-3.0, -4.0], [-2.0, -4.0], [-1.0, -4.0], [0.0, -4.0],
[1.0, -4.0], [2.0, -4.0], [-1.5, -6.0], [-0.5, -6.0], [0.5, -6.0],
[1.5, -6.0], [-1.5, -8.0]]
So my question is, in Step 1, how to build the initial list of links between files. Some files may have identical names?
# get links with full path
function read_sub_dirs(path::AbstractString)
try # avoid access issue
a = readdir(path)
return a[isdir.((path*"/").*a)]
catch
return String[]
end
end
function deepreaddir_raw(working_dir_path::AbstractString,search_depth::Int=2)
links = Array{Pair,1}()
previous_dirs = [working_dir_path]
for i in 1:search_depth
if length(previous_dirs) > 0
next_dirs = String[]
for each_dir in previous_dirs
if each_dir[end] == '/'
sub_dirs = each_dir.*read_sub_dirs(each_dir)
else
sub_dirs = (each_dir*"/").*read_sub_dirs(each_dir)
end
append!(links,each_dir.=>sub_dirs)
append!(next_dirs,sub_dirs)
end
deleteat!(previous_dirs,1:length(previous_dirs))
append!(previous_dirs,next_dirs)
else
break
end
end
return links
end
# generate list of links
function deepreaddir(working_dir_path::AbstractString,search_depth::Int=2)
links_raw = deepreaddir_raw(working_dir_path,2)
links = Pair[]
for each_p in links_raw
a = split(each_p[1],"/")[end]; b = split(each_p[2],"/")[end];
a == "" ? a = working_dir_path : nothing
push!(links,a=>b)
end
links
end
links = deepreaddir(".")
# construct relationships
tree_dic = Dict{String,Array}()
[tree_dic[x] = String[] for x in map(x->x[1],links)]
for p in links
push!(tree_dic[p[1]],p[2])
end
# "System" ==> 1
str2id_dic = Dict{String,Int64}()
[str2id_dic[links[i][2]] = i for i in 1:length(links)]
# loop through col2 of `links`, guess it's the output you want?
str_res = map(xx->haskey(tree_dic,xx) ? tree_dic[xx] : String[], map(x->x[2],links))
# to ids
res = [map(k->str2id_dic[k],x) for x in str_res]
julia> res = [map(k->str2id_dic[k],x) for x in str_res]
15-element Array{Array{T,1} where T,1}:
[4, 5, 6]
[7, 8, 9]
[10, 11, 12, 13, 14]
Any[]
Any[]
Any[]
Any[]
Any[]
Any[]
Any[]
Any[]
Any[]
Any[]
[15]
Any[]
I’m biased here, but why not use MetaGraphs.jl instead of rolling your own graph structure? Also, for files with the same name, a combination of file system ID and inode should be globally unique at a given point in time.
I would create the Metagraph and populate it with output from stat: https://docs.julialang.org/en/v1/base/file/#Base.stat
In order to avoid displaying empty graph axes when no information is available to plot, I replaced a dcc.Graph return object with a html.Div() which gets an Output callback of either [] or [dcc.Graph(...)].
Now, I'd like to enable other actions on the selectedData (if the Div has a child Graph). Previously I could do this like:
#app.callback(Output('something', 'children'),
[Input('graph', 'selectedData')])
def do_stuff(selectedData):
pass
Now that I've changed the layout item from a dcc.Graph(...) to a html.Div([dcc.Graph(...)]), I can't figure out how to access the selectedData:
#app.callback(Output('something', 'children'),
[Input('graph_div', 'children')])
def do_stuff(children):
if len(children) > 0:
graph = children[0]
# wheres the selectedData now?
Alternatively, it might be easier if there's a way to get the Input id directly to nested dcc.Graph's id? When I try this I get an error saying no components with this id exist in the app's layout.
For each component, it should be possible to register a callback in Dash,
Here is a simple example which replicates what you are trying to do,
import dash
import dash_core_components as dcc
from dash.dependencies import Input, Output
app = dash.Dash(__name__)
app.layout = html.Div([
html.Div(id="graph-div",
children=[
dcc.Graph(
id='graph',
figure={
'data': [
{
'x': [1, 2, 3, 4],
'y': [4, 1, 3, 5],
'text': ['a', 'b', 'c', 'd'],
'customdata': ['c.a', 'c.b', 'c.c', 'c.d'],
'name': 'Trace 1',
'mode': 'markers',
'marker': {'size': 12}
},
{
'x': [1, 2, 3, 4],
'y': [9, 4, 1, 4],
'text': ['w', 'x', 'y', 'z'],
'customdata': ['c.w', 'c.x', 'c.y', 'c.z'],
'name': 'Trace 2',
'mode': 'markers',
'marker': {'size': 12}
}
],
'layout': {
'clickmode': 'event+select'
}
}
),
]
),
html.Div(id="output")
])
#app.callback(Output('output', 'children'),
[Input('graph', 'selectedData')])
def do_stuff(selectedData):
print(selectedData)
if __name__ == '__main__':
app.run_server(debug=True)
If you can post a simple re-creatable code it will be easier to debug.
Update:
If you are dynamically trying to load the component you might face the mentioned issue,
https://community.plot.ly/t/dcc-tabs-filling-tabs-with-dynamic-content-how-to-organize-the-callbacks/6377/2
One easy way to solve it would be to set this app configuration,
app.config['suppress_callback_exceptions']=True
Here is the working example,
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
#
#https://stackoverflow.com/questions/57580240/access-selecteddata-from-html-div-children
#
graph_layout = dcc.Graph(
id='graph',
figure={
'data': [
{
'x': [1, 2, 3, 4],
'y': [4, 1, 3, 5],
'text': ['a', 'b', 'c', 'd'],
'customdata': ['c.a', 'c.b', 'c.c', 'c.d'],
'name': 'Trace 1',
'mode': 'markers',
'marker': {'size': 12}
},
{
'x': [1, 2, 3, 4],
'y': [9, 4, 1, 4],
'text': ['w', 'x', 'y', 'z'],
'customdata': ['c.w', 'c.x', 'c.y', 'c.z'],
'name': 'Trace 2',
'mode': 'markers',
'marker': {'size': 12}
}
],
'layout': {
'clickmode': 'event+select'
}
}
)
app = dash.Dash(__name__)
app.config['suppress_callback_exceptions']=True
app.layout = html.Div([
dcc.Dropdown(id="toggle-graph",
options=[
{'label': 'on', 'value': 'on'},
{'label': 'off', 'value': 'off'},
],
value='on'
) ,
html.Div(id="graph-div",
children=[
]
),
html.Div(id="output")
])
#app.callback(Output('graph-div', 'children'),
[Input('toggle-graph', 'value')])
def do_stuff(value):
if(value == 'on'):
return graph_layout
else:
return []
#app.callback(Output('output', 'children'),
[Input('graph', 'selectedData')])
def do_stuff(selectedData):
print(selectedData)
if __name__ == '__main__':
app.run_server(debug=True)
Looks like what I needed was a way to toggle the graph display rather than conditionally returning the entire graph object:
#app.callback(Output('graph', 'style'), [Input('drop-down', 'value')])
def toggle_container(dropdown_value):
if something
return {'display': 'none'}
else:
return {'display': 'block'}
I have the following code already working well in functions.php - I want to enable mothers day though (12 may 2019) which falls on a Sunday. How to do I add this to the return string?
function custom_adjust_datepicker_range () {
if ( is_checkout() ) {
?>
<script type="text/javascript">
var disabledDays = [
"1-1-2019","1-1-2020","2-1-2019","28-1-2019","27-1-2020","4-3-2019","2-3-2020","19-4-2019","10-4-2020","22-4-2019","13-4-2020","25-4-2019","25-4-2020","27-4-2020","3-6-2019","1-6-2019","30-9-2019","28-9-2020","25-12-2018","25-12-2019","25-12-2020","26-12-2018","26-12-2019","26-12-2020","27-12-2018"
];
jQuery( "#delivery_date" ).datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate('d-m-yy', date);
var isDisabled = (jQuery.inArray(string, disabledDays) != -1);
return [(day != 1 && day != 0 && !isDisabled), ''];
}
});
</script>
<?php
}
} // End custom_adjust_datepicker_range()
add_action( 'wp_footer', 'custom_adjust_datepicker_range', 50 );
Consider the following example.
jQuery(function() {
var disabledDays = [
"1-1-2019", "1-1-2020", "2-1-2019", "28-1-2019", "27-1-2020", "4-3-2019", "2-3-2020", "19-4-2019", "10-4-2020", "22-4-2019", "13-4-2020", "25-4-2019", "25-4-2020", "27-4-2020", "3-6-2019", "1-6-2019", "30-9-2019", "28-9-2020", "25-12-2018", "25-12-2019", "25-12-2020", "26-12-2018", "26-12-2019", "26-12-2020", "27-12-2018"
];
var dtf = 'd-m-yy';
function getMothersDay(y) {
var mayFirst = new Date(y, 4, 1);
var dayOfWeek = mayFirst.getUTCDay();
var firstSunday;
if (dayOfWeek == 0) {
firstSunday = mayFirst;
} else {
firstSunday = new Date(y, 4, 1 + (7 - dayOfWeek));
}
var mothersDay = new Date(y, 4, firstSunday.getDate() + 7);
return mothersDay;
}
function isMothersDay(dt) {
return (jQuery.datepicker.formatDate(dtf, dt) == jQuery.datepicker.formatDate(dtf, getMothersDay(dt.getFullYear())));
}
jQuery("#delivery_date").datepicker({
minDate: 2,
beforeShowDay: function(date) {
var day = date.getDay();
var string = jQuery.datepicker.formatDate(dtf, date);
var isDisabled = jQuery.inArray(string, disabledDays);
var result = [
true,
"",
""
];
switch (true) {
case isMothersDay(date):
// Mother's Day
result = [
true,
"mothers-day",
"Mother's Day"
];
break;
case (isDisabled >= 0):
// Disable Days
result[0] = false;
break;
case (day == 0):
case (day == 6):
// Weekends
result[0] = false;
break;
}
return result;
}
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>Delivery Date: <input type="text" id="delivery_date"></p>
See More: How to calculate Mother’s Day in JavaScript
This example was based on first Google search result I performed. In the future, you may want to search for basic examples.
This is not adjusted for WordPress, so you will need to adapt the code to your needs.
You have 3 basic checks:
Is the date Mother's Day
Is the date in the array of dates
Is the date a weekend day
You might have other scenarios arise so using a switch() might be easier overall. I move from the least common condition to the most common condition. You could add more and only check if it's Mother's Day if the month is May and they day of the month is within the first 2 weeks: (date.getMonth() == 4 && date.getDate() < 15).
Hope this helps.
I have an animal array:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
How do I pass it to the handlebar and iterate it ? Basically, I want to display all animals, with each of animal, display all of its properties.
Thanks
Minh
I have figured it out myself, in order to do what I want. I need to do:
Server.js:
var animals = [new animal("giraffe", false, 4), new animal("zebra", false, 8), new animal("lion", false, 10), new animal("dog", true, 4), new animal("cat", true, 2)];
// Routes:
app.get("/allpets",function(req,res){
res.render("allpets", {pets: animals});
};
app.get("/pets/:id",function(req,res){
var type = req.params.id;
var index = -1
for(var i = 0; i < animals.length; i++){
if(animals[i].type === type){
index = i;
break;
}
res.render("animal", animals[index]);
});
Then, we will need to create 2 handlebar views. One is called allpets.hbs, the other one is called animal.hbs
allpets.hbs:
<ul>
{{#each pets}}
<li>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</li>
{{/each}}
</ul>
============================================================
animal.hbs:
<ul>
<p>Type: {{type}}</p>
<p>Pet: {{pet}}</p>
<p>Fierceness: {{fierceness}}</p>
</ul>