body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I loved Norvig's <a href="http://norvig.com/lispy.html" rel="noreferrer">Lispy</a>, and made the first version of it in Rust, to learn Rust. I would love your thoughts :) </p>
<p>A few specific questions:</p>
<ol>
<li>Is there a way to write <code>ensure_tonicity</code> without a macro? I tried, but was <a href="https://stackoverflow.com/questions/55758511/storing-impl-fn-in-an-enum-type">having trouble typing it</a></li>
<li>What do you think of passing in <code>&mut RispEnv</code> in <code>eval</code>. I needed to do this to implement <code>def</code>, as it mutates env. Is my approach the idiomatic rust way, anything I'm missing?</li>
<li>In my implementation of <code>PartialEq</code> for <code>RispExp</code>, I had to use a default <code>false</code>. This removes the win of exhaustive typechecking, but I had to do it, I think, in order to avoid writing out all the combinations of RispExp a, with RispExp b. Is there some way I can do exhaustive typechecking here, without writing out all combinations? i.e no different enum types (RispExp::Symbol, with RispExp::Number for ex) should ever be equal.</li>
<li>How is my use of references, Rc, etc?</li>
</ol>
<p>And of course, any other thoughts greatly appreciated :) </p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::HashMap;
use std::io;
use std::num::ParseFloatError;
use std::rc::Rc;
/*
Types
*/
#[derive(Clone)]
enum RispExp {
Bool(bool),
Symbol(String),
Number(f64),
List(Vec<RispExp>),
Func(fn(&[RispExp]) -> Result<RispExp, RispErr>),
Lambda(RispLambda)
}
#[derive(Debug)]
enum RispErr {
Reason(String),
}
#[derive(Clone)]
struct RispEnv {
data: HashMap<String, RispExp>,
outer: Option<Rc<RispEnv>>,
}
#[derive(Clone)]
struct RispLambda {
params_exp: Rc<RispExp>,
body_exp: Rc<RispExp>,
}
impl PartialEq for RispExp {
fn eq(&self, other: &RispExp) -> bool {
match (self, other) {
(RispExp::Bool(ref a), RispExp::Bool(ref b)) => a == b,
(RispExp::Symbol(ref a), RispExp::Symbol(ref b)) => a == b,
(RispExp::Number(ref a), RispExp::Number(ref b)) => a == b,
(RispExp::List(ref a), RispExp::List(ref b)) => a == b,
_ => false,
}
}
}
/*
Print
*/
fn to_str(exp: &RispExp) -> String {
match exp {
RispExp::Symbol(s) => s.clone(),
RispExp::Number(n) => n.to_string(),
RispExp::Bool(b) => b.to_string(),
RispExp::List(list) => {
let xs: Vec<String> = list
.iter()
.map(|x| to_str(x))
.collect();
return format!("({})", xs.join(","));
},
RispExp::Func(_) => "Function {}".to_string(),
RispExp::Lambda(_) => "Lambda {}".to_string(),
}
}
/*
Env
*/
fn parse_single_float(exp: &RispExp) -> Result<f64, RispErr> {
match exp {
RispExp::Number(num) => Ok(*num),
_ => Err(
RispErr::Reason(
format!("expected a number, got form='{}'", to_str(exp))
)
),
}
}
fn parse_list_of_floats(args: &[RispExp]) -> Result<Vec<f64>, RispErr> {
return args
.iter()
.map(|x| parse_single_float(x))
.collect::<Result<Vec<f64>, RispErr>>();
}
macro_rules! ensure_tonicity {
($check_fn:expr) => {{
|args: &[RispExp]| -> Result<RispExp, RispErr> {
let floats = parse_list_of_floats(args)?;
let first = floats.first().ok_or(RispErr::Reason("expected at least one number".to_string()))?;
let rest = &floats[1..];
fn f (prev: &f64, xs: &[f64]) -> bool {
match xs.first() {
Some(x) => $check_fn(prev, x) && f(x, &xs[1..]),
None => true,
}
};
return Ok(RispExp::Bool(f(first, rest)));
}
}};
}
fn default_env() -> RispEnv {
let mut data: HashMap<String, RispExp> = HashMap::new();
data.insert(
"+".to_string(),
RispExp::Func(
|args: &[RispExp]| -> Result<RispExp, RispErr> {
let sum = parse_list_of_floats(args)?.iter().fold(0.0, |sum, a| sum + a);
return Ok(RispExp::Number(sum));
}
)
);
data.insert(
"-".to_string(),
RispExp::Func(
|args: &[RispExp]| -> Result<RispExp, RispErr> {
let floats = parse_list_of_floats(args)?;
let first = *floats.first().ok_or(RispErr::Reason("expected at least one number".to_string()))?;
let sum_of_rest = floats[1..].iter().fold(0.0, |sum, a| sum + a);
return Ok(RispExp::Number(first - sum_of_rest));
}
)
);
data.insert(
"=".to_string(),
RispExp::Func(ensure_tonicity!(|a, b| a == b))
);
data.insert(
">".to_string(),
RispExp::Func(ensure_tonicity!(|a, b| a > b))
);
data.insert(
">=".to_string(),
RispExp::Func(ensure_tonicity!(|a, b| a >= b))
);
data.insert(
"<".to_string(),
RispExp::Func(ensure_tonicity!(|a, b| a < b))
);
data.insert(
"<=".to_string(),
RispExp::Func(ensure_tonicity!(|a, b| a <= b))
);
return RispEnv {data: data, outer: None}
}
/*
Eval
*/
fn eval_if_args(arg_forms: &[RispExp], env: &mut RispEnv) -> Result<RispExp, RispErr> {
let test_form = arg_forms.first().ok_or(
RispErr::Reason(
"expected test form".to_string(),
)
)?;
let test_eval = eval(test_form, env)?;
match test_eval {
RispExp::Bool(b) => {
let form_idx = if b { 1 } else { 2 };
let res_form = arg_forms.get(form_idx)
.ok_or(RispErr::Reason(
format!("expected form idx={}", form_idx)
))?;
let res_eval = eval(res_form, env);
return res_eval;
},
_ => Err(
RispErr::Reason(format!("unexpected test form='{}'", to_str(test_form)))
)
}
}
fn eval_def(arg_forms: &[RispExp], env: &mut RispEnv) -> Result<RispExp, RispErr> {
let first_form = arg_forms.first().ok_or(
RispErr::Reason(
"expected first form".to_string(),
)
)?;
let first_str = match first_form {
RispExp::Symbol(s) => Ok(s.clone()),
_ => Err(RispErr::Reason(
"expected first form to be a symbol".to_string(),
))
}?;
let second_form = arg_forms.get(1).ok_or(
RispErr::Reason(
"expected second form".to_string(),
)
)?;
if arg_forms.len() > 2 {
return Err(
RispErr::Reason(
"def can only have two forms ".to_string(),
)
)
}
let second_eval = eval(second_form, env)?;
env.data.insert(first_str, second_eval);
return Ok(first_form.clone());
}
fn eval_lambda(arg_forms: &[RispExp]) -> Result<RispExp, RispErr> {
let params_exp = arg_forms.first().ok_or(
RispErr::Reason(
"expected args form".to_string(),
)
)?;
let body_exp = arg_forms.get(1).ok_or(
RispErr::Reason(
"expected second form".to_string(),
)
)?;
if arg_forms.len() > 2 {
return Err(
RispErr::Reason(
"fn deefinition can only have two forms ".to_string(),
)
)
}
return Ok(
RispExp::Lambda(
RispLambda {
body_exp: Rc::new(body_exp.clone()),
params_exp: Rc::new(params_exp.clone()),
}
)
);
}
fn eval_built_in_symbol(sym: String, arg_forms: &[RispExp], env: &mut RispEnv) -> Result<RispExp, RispErr> {
match sym.as_ref() {
"if" => eval_if_args(arg_forms, env),
"def" => eval_def(arg_forms, env),
"fn" => eval_lambda(arg_forms),
_ => Err(RispErr::Reason(format!("unknown built-in symbol='{}'", sym))),
}
}
fn eval_forms(arg_forms: &[RispExp], env: &mut RispEnv) -> Result<Vec<RispExp>, RispErr> {
return arg_forms
.iter()
.map(|x| eval(x, env))
.collect::<Result<Vec<RispExp>, RispErr>>();
}
fn parse_list_of_symbol_strings(form: Rc<RispExp>) -> Result<Vec<String>, RispErr> {
let list = match form.as_ref() {
RispExp::List(s) => Ok(s.clone()),
_ => Err(RispErr::Reason(
"expected args form to be a list".to_string(),
))
}?;
return list
.iter()
.map(
|x| {
return match x {
RispExp::Symbol(s) => Ok(s.clone()),
_ => Err(RispErr::Reason(
"expected symbols in the argument list".to_string(),
))
}
}
).collect::<Result<Vec<String>, RispErr>>();
}
fn env_for_lambda(
params: Rc<RispExp>,
arg_forms: &[RispExp],
outer_env: &mut RispEnv,
) -> Result<RispEnv, RispErr> {
let ks = parse_list_of_symbol_strings(params)?;
if ks.len() != arg_forms.len() {
return Err(
RispErr::Reason(
format!("expected {} arguments, got {}", ks.len(), arg_forms.len())
)
);
}
let vs = eval_forms(arg_forms, outer_env)?;
let mut data: HashMap<String, RispExp> = HashMap::new();
for (k, v) in ks.iter().zip(vs.iter()) {
data.insert(k.clone(), v.clone());
}
return Ok(
RispEnv {
data: data,
outer: Some(Rc::new(outer_env.clone())),
}
);
}
fn env_get(k: &str, env: &RispEnv) -> Option<RispExp> {
return match env.data.get(k) {
Some(exp) => Some(exp.clone()),
None => {
return match &env.outer {
Some(outer_env) => env_get(k, &outer_env),
None => None
}
}
};
}
fn eval(exp: &RispExp, env: &mut RispEnv) -> Result<RispExp, RispErr> {
match exp {
RispExp::Symbol(k) =>
env_get(k, env)
.or(Some(exp.clone()))
.ok_or(
RispErr::Reason(
format!("unexpected symbol k='{}'", k)
)
)
,
RispExp::Bool(_a) => Ok(exp.clone()),
RispExp::Number(_a) => Ok(exp.clone()),
RispExp::List(list) => {
let first_form = list
.first()
.ok_or(RispErr::Reason("expected a non-empty list".to_string()))?;
let arg_forms = &list[1..];
let first_eval = eval(first_form, env)?;
return match first_eval {
RispExp::Symbol(sym) => eval_built_in_symbol(sym, arg_forms, env),
RispExp::Func(f) => {
return f(&eval_forms(arg_forms, env)?);
},
RispExp::Lambda(lambda) => {
let new_env = &mut env_for_lambda(lambda.params_exp, arg_forms, env)?;
return eval(&lambda.body_exp, new_env);
},
_ => Err(
RispErr::Reason(
format!("first form must be a function, but got form='{}'", to_str(&first_eval))
)
),
}
},
RispExp::Func(_) => Err(
RispErr::Reason(
format!("unexpected form='{}'", to_str(exp))
)
),
RispExp::Lambda(_) => Err(
RispErr::Reason(
format!("unexpected form='{}'", to_str(exp))
)
),
}
}
/*
Parse
*/
fn read_seq(tokens: &[String], start: usize) -> Result<(RispExp, usize), RispErr> {
let mut res: Vec<RispExp> = vec![];
let mut next = start;
loop {
let next_token = tokens
.get(next)
.ok_or(RispErr::Reason("could not find closing `)`".to_string()))
?;
if next_token == ")" {
return Ok((RispExp::List(res), next + 1)) // skip `)`, head to the token after
}
let (exp, new_next) = parse(&tokens, next)?;
res.push(exp);
next = new_next;
}
}
fn parse_atom(token: &str) -> RispExp {
match token.as_ref() {
"true" => RispExp::Bool(true),
"false" => RispExp::Bool(false),
_ => {
let potential_float: Result<f64, ParseFloatError> = token.parse();
return match potential_float {
Ok(v) => RispExp::Number(v),
Err(_) => RispExp::Symbol(token.to_string().clone())
}
}
}
}
fn parse(tokens: &[String], pos: usize) -> Result<(RispExp, usize), RispErr> {
let token = tokens
.get(pos)
.ok_or(
RispErr::Reason(format!("could not get token for pos='{}'", pos))
)?;
let to_match = &token[..];
match to_match {
"(" => read_seq(tokens, pos + 1),
")" => Err(RispErr::Reason("unexpected `)`".to_string())),
_ => Ok(
(parse_atom(token), pos + 1)
),
}
}
fn tokenize(expr: String) -> Vec<String> {
return expr
.replace("(", " ( ")
.replace(")", " ) ")
.split(" ")
.map(|x| x.trim().to_string())
.filter(|x| !x.is_empty())
.collect();
}
/*
REPL
*/
fn parse_eval_print(expr: String, env: &mut RispEnv) -> Result<String, RispErr> {
let (parsed_exp, _) = parse(&tokenize(expr), 0)?;
let evaled_exp = eval(&parsed_exp, env)?;
return Ok(to_str(&evaled_exp));
}
fn slurp_expr() -> String {
let mut expr = String::new();
io::stdin().read_line(&mut expr)
.expect("Failed to read line");
return expr;
}
fn main() {
let env = &mut default_env();
loop {
println!("risp >");
let expr = slurp_expr();;
match parse_eval_print(expr, env) {
Ok(res) => println!("// => {}", res),
Err(e) => match e {
RispErr::Reason(msg) => println!("// => {}", msg),
},
}
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "\n<h1>Organization</h1>\n<p>Let's first take a look at the organization of the code. The gigantic\ncode block is stored in one file, with comments like <code>/* Types */</code> and\n<code>/* Print */</code> separating different logical blocks and names that start\nwith the relevant prefixes.</p>\n<p>Instead, take advantage of Rust's powerful <a href=\"https://doc.rust-lang.org/stable/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html\" rel=\"nofollow noreferrer\">module system</a>:</p>\n<pre><code>// main.rs\n\npub mod core;\npub mod eval;\npub mod parse;\n// etc.\n</code></pre>\n<pre><code>// core.rs\n\n#[derive(Clone, Debug)]\npub enum Expr {\n // ...\n}\n\n#[derive(Clone, Debug)]\npub struct Error(String);\n\n// ...\n</code></pre>\n<p>and so on.</p>\n<h1><code>cargo fmt</code> and <code>cargo clippy</code></h1>\n<p><code>cargo fmt</code> automatically formats your code according to the official\n<a href=\"https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/guide.md\" rel=\"nofollow noreferrer\">Rust Style Guide</a>.</p>\n<p><code>cargo clippy</code> reported a lot of issues (1 error and 34 warnings).\nHere are some typical examples:</p>\n<pre><code>warning: unneeded `return` statement\n --> src\\main.rs:82:5\n |\n82 | / return args\n83 | | .iter()\n84 | | .map(|x| parse_single_float(x))\n85 | | .collect::<Result<Vec<f64>, RispErr>>();\n | |________________________________________________^\n |\n = note: `#[warn(clippy::needless_return)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_return\nhelp: remove `return`\n |\n82 | args\n83 | .iter()\n84 | .map(|x| parse_single_float(x))\n85 | .collect::<Result<Vec<f64>, RispErr>>()\n |\n</code></pre>\n<pre><code>warning: redundant field names in struct initialization\n --> src\\main.rs:152:9\n |\n152 | data: data,\n | ^^^^^^^^^^ help: replace it with: `data`\n |\n = note: `#[warn(clippy::redundant_field_names)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_field_names\n</code></pre>\n<pre><code>warning: use of `ok_or` followed by a function call\n --> src\\main.rs:124:18\n |\n124 | .ok_or(RispErr::Reason("expected at least one number".to_string()))?;\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `ok_or_else(|| RispErr::Reason("expected at least one number".to_string()))`\n |\n = note: `#[warn(clippy::or_fun_call)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call\n</code></pre>\n<pre><code>warning: redundant clone\n --> src\\main.rs:369:60\n |\n369 | Err(_) => RispExp::Symbol(token.to_string().clone()),\n | ^^^^^^^^ help: remove this\n |\n = note: `#[warn(clippy::redundant_clone)]` on by default\nnote: this value is dropped without further use\n --> src\\main.rs:369:43\n |\n369 | Err(_) => RispExp::Symbol(token.to_string().clone()),\n | ^^^^^^^^^^^^^^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#redundant_clone\n</code></pre>\n<pre><code>warning: this call to `as_ref` does nothing\n --> src\\main.rs:362:11\n |\n362 | match token.as_ref() {\n | ^^^^^^^^^^^^^^ help: try this: `token`\n |\n = note: `#[warn(clippy::useless_asref)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#useless_asref\n</code></pre>\n<pre><code>warning: single-character string constant used as pattern\n --> src\\main.rs:392:16\n |\n392 | .split(" ")\n | ^^^ help: try using a `char` instead: `' '`\n |\n = note: `#[warn(clippy::single_char_pattern)]` on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#single_char_pattern\n</code></pre>\n<p>You can follow the suggestions given in the <code>help</code> sections to improve\nyour code.</p>\n<p>One of the diagnostics given by <code>clippy</code> is worth noting:</p>\n<pre><code>error: strict comparison of `f32` or `f64`\n --> src\\main.rs:132:47\n |\n132 | RispExp::Func(ensure_tonicity!(|a, b| a == b)),\n | ^^^^^^ help: consider comparing them within some error: `(a - b).abs() < error`\n |\n = note: `#[deny(clippy::float_cmp)]` on by default\n = note: `f32::EPSILON` and `f64::EPSILON` are available for the `error`\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#float_cmp\n</code></pre>\n<p><code>clippy</code> apparently considers testing for strict equality on\nfloating-point numbers to be an oversight, but the exact behavior is\ndesired in this case. I would define a wrapper function that clearly\ncommunicates the intent and turn off the lint for it:</p>\n<pre><code>#[allow(clippy::float_cmp)]\nfn strictly_equal<T, U>(lhs: T, rhs: U) -> bool\nwhere\n T: PartialEq<U>,\n{\n lhs == rhs\n}\n</code></pre>\n<p>Thus, <code>strictly_equal(a, b)</code> can be used in place of <code>a == b</code> to avoid\ntriggering the warning.</p>\n<p>(Technically, the <code>#[allow(clippy::float_cmp)]</code> is redundant here,\nsince <code>clippy::float_cmp</code> ignores functions whose name contains the\nsubstring <code>eq</code>. I decided to include it for clarity.)</p>\n<h1>Built-in functions and <code>ensure_tonicity!</code></h1>\n<p>Instead of storing a function pointer in <code>RispExp</code>, why not simply\nstore a token and define associated operations? For example:</p>\n<pre><code>#[derive(Clone, Debug)]\nenum RispExp {\n Func(Func),\n // ...\n}\n\n#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]\nenum Func {\n Compare(std::cmp::Ordering),\n Add,\n Minus,\n // ...\n}\n\nimpl Func {\n fn eval(args: &[RispExp]) -> RispExp {\n // ...\n }\n}\n</code></pre>\n<h1>Passing environments around</h1>\n<p>Instead of taking <code>&mut Env</code> arguments everywhere, define the\nfunctions as methods on <code>Env</code>.</p>\n<h1><code>match</code>ing on two operands of the same <code>enum</code></h1>\n<blockquote>\n<p>In my implementation of <code>PartialEq</code> for <code>RispExp</code>, I had to use a\ndefault <code>false</code>. This removes the win of exhaustive typechecking,\nbut I had to do it, I think, in order to avoid writing out all the\ncombinations of RispExp a, with RispExp b. Is there some way I can\ndo exhaustive typechecking here, without writing out all\ncombinations? i.e no different enum types (RispExp::Symbol, with\nRispExp::Number for ex) should ever be equal.</p>\n</blockquote>\n<p>Personally, I wouldn't worry about it at all. If you want to ensure\nthat you have handled all homogenenous cases in non-<code>_</code> match arms,\nyou can use <a href=\"https://doc.rust-lang.org/std/mem/fn.discriminant.html\" rel=\"nofollow noreferrer\"><code>std::mem::discriminant</code></a> to perform a runtime check:</p>\n<pre><code>match (lhs, rhs) {\n // ...\n _ => {\n use std::mem::discriminant;\n // ensure that we've handled all homogeneous cases explicitly\n assert_eq!(discriminant(lhs), discriminant(rhs));\n false\n }\n}\n</code></pre>\n<p>I am not aware of a simple compile-time solution, unfortunately.</p>\n<h1>Reference counting</h1>\n<p>To me, reference counting seems like a viable solution for pointing to\nexpressions from multiple places. I would consider using some\n<a href=\"https://doc.rust-lang.org/std/rc/struct.Weak.html\" rel=\"nofollow noreferrer\"><code>Weak</code></a> references to avoid reference cycles, though.</p>\n<hr />\n<p>These should be enough to get you started.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-26T12:52:21.873",
"Id": "251162",
"ParentId": "219253",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T14:26:32.513",
"Id": "219253",
"Score": "12",
"Tags": [
"rust",
"lisp",
"interpreter"
],
"Title": "(Lisp in (Rust))"
} | 219253 |
<p>The problem is from <a href="https://codeforces.com/contest/1157/problem/B" rel="nofollow noreferrer">yesterday's contest from Codeforces</a>.</p>
<p>I have observed that, from the left side (i.e. MSB), for every digit, if we replace the given number with the output of <code>f</code> when after passing the digit - we get a bigger number we will get the desired output. I'm a beginner in programming and have written code with Python 3, which is showing TLE after submission (though it is correct and gives correct output for the sample test cases). I think a better algorithm is needed.</p>
<p>Variables <code>st</code> (start index), <code>flag</code>, <code>cntr</code> (length of <strong>contiguous subsegment</strong> ) are taken for the condition the part where we will replace the digits needs to be <strong>contiguous subsegment</strong>: </p>
<pre><code>n = int(input())
s = input()
f = list(map(int,input().split()))
result = []
st = -1
flag = 1
cntr = 0
for i in range(len(s)):
x=f[int(s[i])-1]
if(x>int(s[i])):
result.append(str(x))
if(flag==1):
st = i
flag = 0
if(flag==0):
cntr+=1
else:
result.append(s[i])
if(st!=-1 and (i-st-1)!=cntr):
break
for j in range(i+1,len(s)):
result.append(s[j])
#print(result)
r = int(''.join(result))
print(r)
</code></pre>
<p>Can anyone make any improvement in my code? I know there is a tutorial on that website, but I want to learn how to develop code which I have written already.</p>
| [] | [
{
"body": "<p>The speed issue can be fixed by using PyPy 3 as it is faster (at least in most codeforces type problems, I don't know in general)</p>\n\n<p>However this will result in a WA verdict. To fix this just modify the break condition as follows and it will work:</p>\n\n<pre><code>if(st!=-1 and x!=int(s[i])):\n</code></pre>\n\n<p>This is because the current version can sometimes break out of the loop prematurely when <span class=\"math-container\">\\$x == int(s[i])\\$</span> because it may be better to make the segment longer.</p>\n\n<p>Finally, I consider you are using too many flag variables, only one is required. Here is how I would change the code:</p>\n\n<pre><code>n = int(input())\ns = input()\nf = list(map(int,input().split()))\nresult = []\nflag = 1 \nfor i in range(len(s)):\n x=f[int(s[i])-1]\n if(x>int(s[i])):\n result.append(str(x)) \n if(flag==1):\n flag = 0\n else:\n result.append(s[i])\n if(flag!=1 and x!=int(s[i])):\n break\nfor j in range(i+1,len(s)):\n result.append(s[j])\n#print(result)\nr = int(''.join(result))\nprint(r)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:53:27.040",
"Id": "423520",
"Score": "0",
"body": "Thank you for helping. Not getting why we need to break the loop when `x!=int(s[i])` given `flag!=1`. In every iteration, `x` will be loaded with `f[int(s[i])-1]`. I used the break statement to check if after starting the replacement we no more have greater number as output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:58:10.790",
"Id": "423523",
"Score": "1",
"body": "I honestly don't understand what the reasoning behind (i-st-1)!=cntr is. But you just need to break as soon as there is a value such that x<int(s[i]) because then it becomes clear that you shouldn't make the segment that you are applying f to any longer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:07:18.723",
"Id": "423524",
"Score": "0",
"body": "Ok, so we can use `x<int(s[i])`. If I use `x!=int(s[i])` there, as, every time `x` is getting updated by `f[int(s[i])-1]`, the loop will break after just replacing one digit, as the `flag=0` at that time already. About my program, I am storing the index of the digit, where first replacement occurs, in `st` variable. Increasing the var. `cntr` everytime when replacement occurs. But when for first time(after replacement has started for `st` th digit) when we get `x<int(s[i])` the `cntr` will not be updated and the value of `(i-st-1)` and `cntr` will be not same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:09:36.577",
"Id": "423526",
"Score": "0",
"body": "well yeah but the cntr variable isn' very usefull, the only part where you use cntr is in the (i-st-1)!=cntr part. But I dont understand that part. Also, notice that the flag variable isnt used , you can just use the st variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:14:45.523",
"Id": "423528",
"Score": "0",
"body": "Thank you. I wish your channel would be in English :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:31:34.747",
"Id": "423534",
"Score": "0",
"body": "There's a lot of better channels in english"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:17:22.203",
"Id": "219263",
"ParentId": "219257",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219263",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T15:46:31.857",
"Id": "219257",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Finding largest number we can make"
} | 219257 |
<p>I've decided to move my rendering code to a separate thread, to help facilitate the move I've created a pipeline system for rendering. With this pipeline I can insert commands into a queue which will be processed later on the rendering thread. Thus far the code has proven to work well, but I would like to know if there is anything I can do better.</p>
<p>There are a few things I would like to know:</p>
<ol>
<li>Does the code have a reasonably fast locking system, if not is there any way I can improve it?</li>
<li>Am I properly locking around data accesses, and should I be using more mutexes?</li>
<li>When I pass parameters for the queue I use a structure than can store 8 parameters (8 64 bit integers) - I only store the data needed for the command in the buffer - is there any way with templates (potentially varargs) that I can make the parameter passing cleaner?</li>
</ol>
<p>I've removed a significant number of commands (rendering functions) for brevity.</p>
<p>The <code>RenderingPipeline</code> class header:</p>
<pre><code>#pragma once
#include <cstdint>
#include <thread>
#include <mutex>
#include <Windows.h>
// The various rending instructions.
// Some have been removed for brevity.
enum class RenderingOpcode : std::uint8_t
{
FINISH_RENDER = 1, // First opcode set to 1 instead of 0 to allow for faster thread locking.
LOAD_SHADER_UNIFORM,
ACTIVATE_SHADER_PROGRAM,
GL_DRAW_ARRAYS,
GL_CLEAR_BUFFERS
};
// The various uniform types.
// Some have been removed for brevity.
enum class ShaderUniformType : std::uint8_t
{
INTEGER,
FLOAT,
MAT4F
};
// Some simple macros to make parameter packing easier
#define PACK_FLOAT(__F) (reinterpret_cast<std::uint32_t&>(__F))
#define PACK_DOUBLE(__D) (reinterpret_cast<std::uint64_t&>(__F))
#define PACK_PTR(__P) (reinterpret_cast<std::uint64_t>(__P))
/**
* A series of parameters for an instruction.
*
* Ideally I would use templates, potentially with varargs.
*/
struct ParameterPack final
{
std::uint64_t p0, p1, p2, p3, p4, p5, p6, p7;
ParameterPack(std::uint64_t _p0 = 0, std::uint64_t _p1 = 0, std::uint64_t _p2 = 0, std::uint64_t _p3 = 0,
std::uint64_t _p4 = 0, std::uint64_t _p5 = 0, std::uint64_t _p6 = 0, std::uint64_t _p7 = 0)
: p0(_p0), p1(_p1), p2(_p2), p3(_p3), p4(_p4), p5(_p5), p6(_p6), p7(_p7)
{ }
~ParameterPack() = default;
ParameterPack(const ParameterPack&) = default;
ParameterPack(ParameterPack&&) = default;
ParameterPack& operator =(const ParameterPack&) = default;
ParameterPack& operator =(ParameterPack&&) = default;
};
class RenderingPipeline final
{
private:
std::uint8_t* _instBuffer;
std::uint32_t _insertPtr;
std::uint32_t _instPtr;
volatile bool _initialReady;
volatile bool _readyForInsert;
volatile bool _running;
std::mutex _mutex;
std::thread _renderThread;
public:
RenderingPipeline(HDC hdc, HGLRC renderingContext, const std::uint32_t bufferSize = 16384);
~RenderingPipeline();
void pushInstruction(const RenderingOpcode opcode, const ParameterPack&& params);
private:
void runRenderingCycle();
void renderThreadFunc(HDC hdc, HGLRC renderingContext);
};
</code></pre>
<p>The <code>RenderingPipeline</code> class implementation:</p>
<pre><code>#include <cstring>
#include <GL/glew.h>
#include "RenderingPipeline.hpp"
RenderingPipeline::RenderingPipeline(HDC hdc, HGLRC renderingContext, const std::uint32_t bufferSize)
: _instBuffer(new std::uint8_t[bufferSize]), _insertPtr(0), _instPtr(0),
_initialReady(false), _readyForInsert(true), _running(true), _renderThread(&RenderingPipeline::renderThreadFunc, this, window)
{
_mutex.lock();
/* Unload context on main thread.
The context will be loaded on the rendering thread.
Not entirely sure if this required.
*/
wglMakeCurrent(nullptr, nullptr);
std::memset(_instBuffer, 0, bufferSize);
_initialReady = true; // Notify the rendering thread that the buffer is cleared.
_mutex.unlock();
}
RenderingPipeline::~RenderingPipeline()
{
_mutex.lock();
_running = false;
_mutex.unlock();
_renderThread.join();
delete[] _instBuffer;
}
void RenderingPipeline::pushInstruction(const RenderingOpcode opcode, const ParameterPack&& params)
{
/*
* After the `RenderingOpcode::FINISH_RENDER` insruction
* is inserted we lock insertion until the rendering thread
* loops through everything.
*
* This will yield the main thread until the rendering thread finishes.
*/
do
{
_mutex.lock();
if(_readyForInsert)
{
_mutex.unlock();
break;
}
_mutex.unlock();
std::this_thread::yield();
} while(true);
_mutex.lock();
_instBuffer[_insertPtr++] = static_cast<std::uint8_t>(opcode);
// Macro to copy data into the instruction buffer.
#define LOAD_VALUE(__VAR) std::memcpy(reinterpret_cast<void*>(_instBuffer + _insertPtr), reinterpret_cast<const void*>(&__VAR), sizeof(__VAR)); \
_insertPtr += sizeof(__VAR);
switch(opcode)
{
case RenderingOpcode::FINISH_RENDER:
{
_readyForInsert = false;
break;
}
case RenderingOpcode::LOAD_SHADER_UNIFORM:
{
const ShaderUniformType uniformType = static_cast<ShaderUniformType>(params.p0);
const std::int32_t uniformID = static_cast<std::int32_t>(params.p1);
_instBuffer[_insertPtr++] = static_cast<std::uint8_t>(uniformType);
LOAD_VALUE(uniformID);
switch(uniformType)
{
case ShaderUniformType::INTEGER:
{
LOAD_VALUE(params.p2);
break;
}
case ShaderUniformType::FLOAT:
{
const std::uint32_t iVal = static_cast<std::uint32_t>(params.p2);
const float fVal = reinterpret_cast<const float&>(iVal);
LOAD_VALUE(fVal);
break;
}
case ShaderUniformType::MAT4F:
{
const float* const mat = reinterpret_cast<const float*>(params.p2);
LOAD_VALUE(mat);
break;
}
default: break;
}
break;
}
case RenderingOpcode::GL_DRAW_ARRAYS:
{
const GLenum drawArraysMode = static_cast<GLenum>(params.p0);
const GLint drawArraysFirst = static_cast<GLint>(params.p1);
const GLsizei drawArraysCount = static_cast<GLsizei>(params.p2);
LOAD_VALUE(drawArraysMode);
LOAD_VALUE(drawArraysFirst);
LOAD_VALUE(drawArraysCount);
break;
}
case RenderingOpcode::GL_CLEAR_BUFFERS:
{
const GLbitfield clearBuffers = static_cast<GLbitfield>(params.p0);
LOAD_VALUE(clearBuffers);
break;
}
default: break;
}
#undef LOAD_VALUE
_mutex.unlock();
}
void RenderingPipeline::runRenderingCycle()
{
// Macro to retrieve values from the instruction buffer.
#define GET_VALUE(__TYPE, __VAR) const __TYPE __VAR = *reinterpret_cast<const __TYPE*>(_instBuffer + _instPtr); \
_instPtr += sizeof(__VAR);
_instPtr = 0;
while(true)
{
std::uint8_t instByte;
/*
* If there is no instruction ready yield the thread.
*
* This is why the first `RenderingOpcode` has a value of 1 instead of 0.
*/
while(true)
{
_mutex.lock();
instByte = _instBuffer[_instPtr];
_mutex.unlock();
if(instByte != 0) { break; }
std::this_thread::yield();
}
++_instPtr;
const RenderingOpcode currOpcode = static_cast<RenderingOpcode>(instByte);
if(currOpcode == RenderingOpcode::FINISH_RENDER) { break; }
switch(currOpcode)
{
case RenderingOpcode::LOAD_SHADER_UNIFORM:
{
GET_VALUE(ShaderUniformType, uniformType);
GET_VALUE(std::int32_t, uniformID);
switch(uniformType)
{
case ShaderUniformType::INTEGER:
{
GET_VALUE(std::uint64_t, iVal);
glUniform1i(uniformID, static_cast<GLint>(iVal));
break;
}
case ShaderUniformType::FLOAT:
{
GET_VALUE(float, fVal);
glUniform1f(uniformID, fVal);
break;
}
case ShaderUniformType::MAT4F:
{
GET_VALUE(float*, mat);
glUniformMatrix4fv(uniformID, 1, GL_FALSE, mat);
break;
}
default: break;
}
break;
}
case RenderingOpcode::ACTIVATE_SHADER_PROGRAM:
{
GET_VALUE(GLuint, shaderProgramID);
glUseProgram(shaderProgramID);
break;
}
case RenderingOpcode::GL_DRAW_ARRAYS:
{
GET_VALUE(GLenum, drawArraysMode);
GET_VALUE(GLint, drawArraysFirst);
GET_VALUE(GLsizei, drawArraysCount);
glDrawArrays(drawArraysMode, drawArraysFirst, drawArraysCount);
break;
}
case RenderingOpcode::GL_CLEAR_BUFFERS:
{
GET_VALUE(GLbitfield, clearBuffers);
glClear(clearBuffers);
break;
}
default: break;
}
}
_mutex.lock();
std::memset(_instBuffer, 0, _instPtr);
_insertPtr = 0;
_readyForInsert = true;
_mutex.unlock();
#undef GET_VALUE
}
void RenderingPipeline::renderThreadFunc(HDC hdc, HGLRC renderingContext)
{
// Wait for instruction buffer to be cleared.
do
{
_mutex.lock();
if(_initialReady)
{
_mutex.unlock();
break;
}
_mutex.unlock();
std::this_thread::yield();
} while(true);
// Re-assign OpenGL rendering context to this rendering thread.
wglMakeCurrent(hdc, renderingContext);
// Some basic OpenGL setup.
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CW);
while(true)
{
_mutex.lock();
if(!_running)
{
_mutex.unlock();
break;
}
_mutex.unlock();
runRenderingCycle();
SwapBuffers(hdc);
}
}
</code></pre>
<p>An example of how it supposed to be used:</p>
<pre><code>void exampleUsage(HDC hdc, HGLRC renderingContex, GLuint shaderProgram)
{
RenderingPipeline rp(hdc, renderingContex);
while(true)
{
rp.pushInstruction(RenderingOpcode::ACTIVATE_SHADER_PROGRAM, ParameterPack(shaderProgram));
// ...
rp.pushInstruction(RenderingOpcode::FINISH_RENDER, ParameterPack());
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:28:39.337",
"Id": "219266",
"Score": "3",
"Tags": [
"c++",
"c++11",
"multithreading",
"windows",
"opengl"
],
"Title": "Multithreaded OpenGL Rendering Pipeline"
} | 219266 |
<p>I have the following ReactJS unordered list which is generated from answers:</p>
<pre><code><ul className="mt-2 col-md-12">{this.state.answers.map((v,i) =>
<li className="list-group-item" style={{"width": "220px"}}
key={i}> {v} </li>) }
</ul>
</code></pre>
<p>I get answers the following way:</p>
<pre><code>handleSubmit(event) {
const url = "api/" + this.state.actionWith + this.state.button + this.state.value;
fetch(url, {
method: this.state.method
})
.then(response => response.json())
.then(data => {
this.setState({answers: data, input: false, actionWith: "", method: "", button: "", placeholder: "", value: ""})
})
}
</code></pre>
<p>Controller looks like this:</p>
<pre><code>[HttpGet]
public IActionResult ListTargets()
{
var answer = _tlConnection.ListTargets();
return Ok(answer);
}
</code></pre>
<p>And it works well, when _tlConnection methods return something like IEnumerable.</p>
<p>The problem is, that some of the methods return UInt for example. Then this.state.answers is not something that can be mapped. I solve this the following way:</p>
<pre><code>[HttpGet("{targetName}")]
public IActionResult getTargetID(string targetName)
{
var answer = new List<string>() { _tlConnection.getTargetID(targetName).ToString() };
return Ok(answer);
}
</code></pre>
<p>But it feels quite hacky. Is there a more eloquent solution? </p>
<p>Is this a correct way to approach JSON response in ReactJS in general?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:42:31.400",
"Id": "423517",
"Score": "0",
"body": "It looks like you should have two different requests and _views_. One requesting a list and the other a specific item. Your current view is doing to much because it's responsible for two different kinds of data. This is why you have to hack the APIs."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T17:40:07.240",
"Id": "219268",
"Score": "1",
"Tags": [
"c#",
"javascript",
"react.js",
"asp.net-web-api"
],
"Title": "Converting IActionResult to something that can be mapped in JS"
} | 219268 |
<p>I implemented binary search tree. What do you think about my code? How could i optimize it? Where are my major mistakes? I am not asking only about BST but about my coding style in general, using of classes, methods, naming...</p>
<pre><code>using System;
using System.Collections.Generic;
/// <summary>
/// My implementation of BST. It has two classes. Node & BSTree.
/// </summary>
namespace BinarySearchTree
{
class Program
{
static void Main(string[] args)
{
BSTree bst = new BSTree(new Node(20));
bst.Insert(15);
bst.Insert(25);
bst.Insert(18);
bst.Insert(10);
bst.Insert(new Node(19));
bst.Insert(new Node(16));
bst.Insert(new Node(17));
/*
20
/ \
15 25
/ \
10 18
/ \
16 19
\
17
*/
bst.PrintTraversedTree(BSTree.TreeTraversalForm.BreathFirstSearch);
bst.Delete(15);
/*
20
/ \
16 25
/ \
10 18
/ \
17 19
*/
bst.PrintTraversedTree(BSTree.TreeTraversalForm.BreathFirstSearch);
Console.WriteLine("Searching for node...");
Node devetnajst = bst.BinarySearch(19);
if (devetnajst != null)
Console.WriteLine($"Node value: {devetnajst.value}");
else
Console.WriteLine("Node not found!");
Console.WriteLine("Searching for node...");
Node stNiVDrevesu = bst.BinarySearch(23);
if(stNiVDrevesu!=null)
Console.WriteLine($"Node value: {stNiVDrevesu.value}");
else
Console.WriteLine("Node not found!");
Console.WriteLine("Searching for node...");
Node someNode = bst.BinarySearchI(17);
if (someNode != null)
Console.WriteLine($"Node value: {someNode.value}");
}
}
/// <summary>
/// class Node represents nodes of the binary three.
/// </summary>
class Node
{
public Node(int value)
{
this.value = value;
}
public int value { get; set; }
public Node left { get; set; } = null;
public Node right { get; set; } = null;
/// <summary>
/// Returns true if node is Leaf
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
public bool isLeaf()
{
if (this.left == null && this.right == null)
return true;
else
return false;
}
/// <summary>
/// Returns true if this is left child of parent
/// </summary>
/// <param name="node"></param>
/// <param name="parent"></param>
/// <returns></returns>
public bool isLeftChildOf(Node parent)
{
if (this == parent.left)
return true;
else
return false;
}
/// <summary>
/// Returns true if this is right child of parent
/// </summary>
/// <param name="node"></param>
/// <param name="parent"></param>
/// <returns></returns>
public bool isRightChildOf(Node parent)
{
if (this == parent.right)
return true;
else
return false;
}
/// <summary>
/// return true if node has only one child
/// </summary>
/// <returns></returns>
public bool hasOnlyOneChild()
{
if (!this.isLeaf() && (this.left == null || this.right == null))
return true;
else
return false;
}
}
/// <summary>
/// class BSTree represent Binary Search Tree.
/// </summary>
class BSTree
{
Node _root=null; // tree root
int[] _treeTraversal; //three traversal -- dynamic programing
int _nodeCounter=0; //nr of nodes - used to declare _treeTraversal size
int _treeTraversalIndex = 0; //used to position node in array _treeTraversal
int _currentTraverseForm = -1; //if -1 -> no valid traverse of tree
/// <summary>
/// Constructor
/// </summary>
/// <param name="root"></param>
public BSTree(Node root) {
_root = root;
_nodeCounter++;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="rootValue"></param>
public BSTree(int rootValue)
{
_root = new Node(rootValue);
_nodeCounter++;
}
/// <summary>
/// Insert value into Tree
/// </summary>
/// <param name="value"></param>
public void Insert(int value)
{
Insert(new Node(value));
}
/// <summary>
/// Insert Node into tree
/// </summary>
/// <param name="node">Node to be inserted.</param>
/// <param name="root"></param>
public void Insert(Node node, Node root=null)
{
if (root == null)
{
root = _root; // if no root is specified use tree root
}
if (node.value == root.value)
{
Console.WriteLine($"Unable to insert! Value {node.value} allready exist!");
return;
}
if (node.value<root.value)
{
if (root.left == null)
{
root.left = node;
_nodeCounter++;
_currentTraverseForm = -1; // when you insert new node current stored traverse is not valid anymore
}
else
{
Insert(node, root.left);
}
}
else
{
if (root.right == null)
{
root.right = node;
_nodeCounter++;
_currentTraverseForm = -1;
}
else
{
Insert(node, root.right);
}
}
}
/// <summary>
/// Binary Search throught the tree for value - recursive
/// </summary>
/// <param name="value">searched value</param>
/// <param name="root"></param>
/// <returns>Node if found, otherwise returns null</returns>
public Node BinarySearch(int value, Node root = null)
{
if (root == null)
{
root = _root;
}
if (value == root.value)
{
return root;
}
if (value < root.value)
{
if (root.left != null)
{
return BinarySearch(value, root.left);
}
else
{
return null;
}
}
else
{
if (root.right != null)
{
return BinarySearch(value, root.right);
}
else
{
return null;
}
}
}
/// <summary>
/// Binary Search Iterative
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public Node BinarySearchI(int value)
{
Node node = _root;
for (int i = 0; i < _nodeCounter;i++) {
if (value == node.value)
{
return node;
}
else if (value < node.value && node.left != null)
{
node = node.left;
}
else if (node.right != null)
{
node = node.right;
}
else
{
Console.WriteLine("Value not found!");
break;
}
}
return null;
}
/// <summary>
/// get Next inorder - smalest from right subtree
/// </summary>
/// <param name="root"></param>
public Node GetNextInorder(Node node)
{
return Smalest(node.right);
}
/// <summary>
/// get smallest from from root - most left in subtree or tree
/// </summary>
/// <param name="root"></param>
private Node Smalest(Node root)
{
Node minNode = root.left;
while (root.left != null)
{
root = root.left;
minNode = root;
}
return minNode;
}
/// <summary>
/// Deletes the node
/// </summary>
/// <param name="node"></param>
/// <param name="root"></param>
public void Delete(Node node, Node root = null)
{
if (node == null) {
Console.WriteLine("Please enter valid node!");
return;
}
if (root == null)
{
root = _root;
Console.WriteLine($"Deleting node: {node.value}");
}
//if node is child of root->we found parents of child
if (node.isLeftChildOf(root) || node.isRightChildOf(root))
{
if (node.isLeaf()) // if is Leaf just remove it - remove reference at parrent
{
if (node.isLeftChildOf(root))
root.left = null;
else
root.right = null;
_currentTraverseForm = -1;
_nodeCounter--;
}
else if (node.hasOnlyOneChild()) // if only one child replace node with child
{
if (node.left == null)
{
node.value = node.right.value;
node.left = node.right.left;
node.right = node.right.right;
}
else
{
node.value = node.left.value;
node.left = node.left.left;
node.right = node.left.right;
}
_currentTraverseForm = -1;
_nodeCounter--;
}
else //else replace node with next in-order.
{
Node tmpNode = GetNextInorder(node);
node.value = tmpNode.value;
Delete(tmpNode, node);
_currentTraverseForm = -1;
}
}
else // else we need to dig deeper to the left or right
{
if (root.left != null && node.value < root.value)
Delete(node, root.left);
else if(root.right!=null)
Delete(node, root.right);
}
}
/// <summary>
/// Deletes the node using value and binary search
/// </summary>
/// <param name="value"></param>
/// <param name="root"></param>
public void Delete(int value, Node root = null)
{
Delete(BinarySearch(value));
}
/// <summary>
/// enum specifaing posible tree traversal forms
/// DFS - Depth-first search
/// </summary>
public enum TreeTraversalForm
{
DFSpreorder,
DFSinorder,
DFSoutorder,
DFSpostorder,
BreathFirstSearch
};
/// <summary>
/// Maps the tree traversal form with appropriate method
/// </summary>
/// <param name="traversalForm"></param>
/// <returns></returns>
public int[] TraverseTree(TreeTraversalForm traversalForm)
{
//if tree is already traversed -> dont do it again
if ((int)traversalForm != _currentTraverseForm)
{
switch (traversalForm)
{
case TreeTraversalForm.DFSinorder:
this.Inorder();
break;
case TreeTraversalForm.DFSoutorder:
this.Outorder();
break;
case TreeTraversalForm.DFSpostorder:
this.Postorder();
break;
case TreeTraversalForm.DFSpreorder:
this.Preorder();
break;
case TreeTraversalForm.BreathFirstSearch:
this.BreathFirstSearch();
break;
default:
Console.WriteLine("Unknown form!");
break;
}
}
return _treeTraversal;
}
/// <summary>
/// Prints traversed tree to Console
/// </summary>
/// <param name="traversalForm"></param>
public void PrintTraversedTree(TreeTraversalForm traversalForm)
{
//if tree is already traversed -> dont do it again
if ((int)traversalForm != _currentTraverseForm)
{
this.TraverseTree(traversalForm);
}
Console.Write(traversalForm.ToString() + ": ");
foreach (int val in _treeTraversal)
{
Console.Write($"{val} ");
}
Console.WriteLine();
}
/// <summary>
/// Creates DFS - Pre-order traverse and stors it in _treeTraversal
/// </summary>
/// <param name="root"></param>
void Preorder(Node root = null)
{
if (root == null)
{
root = _root;
_treeTraversal = new int[_nodeCounter];
_treeTraversalIndex = 0;
_currentTraverseForm = (int)TreeTraversalForm.DFSpreorder;
}
_treeTraversal[_treeTraversalIndex] = root.value;
_treeTraversalIndex++;
if (root.left != null)
Preorder(root.left);
if (root.right != null)
Preorder(root.right);
}
/// <summary>
/// Creates DFS - In-order traverse and stors it in _treeTraversal
/// </summary>
/// <param name="root"></param>
void Inorder(Node root = null)
{
if (root == null)
{
root = _root;
_treeTraversal = new int[_nodeCounter];
_treeTraversalIndex = 0;
_currentTraverseForm = (int)TreeTraversalForm.DFSinorder;
}
if (root.left != null)
Inorder(root.left);
_treeTraversal[_treeTraversalIndex] = root.value;
_treeTraversalIndex++;
if (root.right != null)
Inorder(root.right);
}
/// <summary>
/// Creates DFS - Post-order traverse and stors it in _treeTraversal
/// </summary>
/// <param name="root"></param>
void Postorder(Node root = null)
{
if (root == null)
{
root = _root;
_treeTraversal = new int[_nodeCounter];
_treeTraversalIndex = 0;
_currentTraverseForm = (int)TreeTraversalForm.DFSpostorder;
}
if (root.left != null)
Postorder(root.left);
if (root.right != null)
Postorder(root.right);
_treeTraversal[_treeTraversalIndex] = root.value;
_treeTraversalIndex++;
}
/// <summary>
/// Creates DFS - Out-order traverse and stors it in _treeTraversal
/// </summary>
/// <param name="root"></param>
void Outorder(Node root = null)
{
if (root == null)
{
root = _root;
_treeTraversal = new int[_nodeCounter];
_treeTraversalIndex = 0;
_currentTraverseForm = (int)TreeTraversalForm.DFSoutorder;
}
if (root.right != null)
Outorder(root.right);
_treeTraversal[_treeTraversalIndex] = root.value;
_treeTraversalIndex++;
if (root.left != null)
Outorder(root.left);
}
/// <summary>
/// Creates BFS - BreathFirstSearch traverse and stors it in _treeTraversal
/// </summary>
/// <param name="root"></param>
void BreathFirstSearch(Node root = null)
{
if (root == null)
{
root = _root;
_treeTraversal = new int[_nodeCounter];
_treeTraversalIndex = 0;
_currentTraverseForm = (int)TreeTraversalForm.BreathFirstSearch;
_treeTraversal[_treeTraversalIndex] = root.value;
_treeTraversalIndex++;
}
if (root.left != null)
{
_treeTraversal[_treeTraversalIndex] = root.left.value;
_treeTraversalIndex++;
}
if (root.right != null)
{
_treeTraversal[_treeTraversalIndex] = root.right.value;
_treeTraversalIndex++;
}
if (root.left != null)
BreathFirstSearch(root.left);
if (root.right != null)
BreathFirstSearch(root.right);
}
}
}
</code></pre>
| [] | [
{
"body": "<h2>API</h2>\n\n<p>I really don't like the returning of the cached value as <code>int[]</code>. Anyone who recieves this return value is free to modify it, and there is no indication that it might be returned multiple times. At the very least, this code should be returning an immutable view of the array (e.g. an <code>IReadOnlyList<int></code>), but if you really want to cache the results, then I would probably clone the array every time it was returned.</p>\n\n<p>I don't like that you have public methods which take the root nodes defaulted as <code>null</code> (e.g. <code>Delete</code>). It would be nicer to make these methods private (so they can't be used) and static (so they know the minimum necessary and can't accidently mess with state) without a default parameter, and provide public members which don't take a parameter, and pass the root to the parameterised methods. Of course, you may want to deliberately expose the capability, but in that case, it is possible for one <code>BSTree</code> to operate on another tree's <code>Node</code>s, and that is a receipe for confusion.</p>\n\n<p>Generally, you are opening a serious can of worms when you expose implementation details like your <code>Node</code> class to the world, because anyone can modify a <code>Node</code> from the <code>BST</code> and ruin the data-structure: if you don't need to expose this information, then do not. If you want a data-structure that can support crazy usage, then you need to document it is as such. Any <code>Node</code>s that have been handed out may be invalidated the moment you perform any operation on the <code>BST</code>.</p>\n\n<p>You might consider making your class generic, so that it can store any value, and not just integers.</p>\n\n<h2>Correctness</h2>\n\n<p>The <code>BreathFirstSearch</code> isn't a breadth-first search.</p>\n\n<p>This code in <code>Delete</code> looks suspect:</p>\n\n<pre><code>node.value = node.left.value;\nnode.left = node.left.left;\nnode.right = node.left.right;\n</code></pre>\n\n<p><code>Smalest</code> is over complicated, keeping track of the same piece of state in 2 variables. It looks wrong, since it will return <code>null</code> if the <code>root</code> has no left-child. This causes <code>Delete</code> to crash under some cirsumstances (e.g. replace the first call to <code>Delete</code> in your code with <code>Delete(18)</code>: boom.</p>\n\n<p><code>Delete</code> is also unable to delete the root node.</p>\n\n<h2>Error handling</h2>\n\n<p>If a method is unable to perform it's task, it should be throwing an exception; it shouldn't not print to the console and it should not return cleanly. In <code>Insert</code>, for example, if trying to add the same value twice is explicitly forbidden, it should throw an exception. If it is allowed, and you just want to ignore this, then you should just return cleaning. A general purpose component should not be printing to the console: you have no idea what job it has in an application.</p>\n\n<p>In <code>TraverseTree</code>, an unrecognise traversal method is surely exception worthy: it certainly does not warrant returning whatever <code>_treeTraversal</code> happens to contain. Throwing an exception forces the consuming code to address the problem up-front (which is good, because ignoring it makes no sense), stops there code proceeding under a false pretense (which may lead to data corruption), and gives them lots of useful information about where the program logic went wrong (e.g. stack trace, and more if there is a debugger handy).</p>\n\n<h2>Printing</h2>\n\n<p>Similarly, <code>PrintTraversedTree</code> assumes that the console is a good place to put stuff: much better, if you want to provide this functionality, to have <code>PrintTraversedTree</code> take a <code>TextWriter</code>, so that the caller can decide where the stuff should be printed. I'd question whether this method should be a member of the class: it has no concern with the classes internal state, and could just as well be a static method elsewhere.</p>\n\n<p><code>Delete</code> even tells the console what it is doing: why? If the calling code wants to tell the console that it is delete a node, then it can do that itself: the BST should stick to being a BST.</p>\n\n<h2>Naming and Spelling</h2>\n\n<p>You might consider following microsoft's naming conventions (because everyone else does) for public members and types, which is to use <code>ProperCamelCase</code> for everything. <code>Node.value</code>, for example, would be <code>Node.Value</code>; <code>isLeaf</code> would be <code>IsLeaf</code>, etc.</p>\n\n<p>There are numerous spelling errors in member names, variable names, inline documentation (nice to see, though it could be more useful), and comments.</p>\n\n<p>I would consider renaming <code>Smalest</code> to <code>FindSmallestDescendent</code> or <code>FindLeftmostDescendent</code>, so that is clearer what is does.</p>\n\n<h2>Don't Repeat Yourself</h2>\n\n<p>The code to initialise <code>_treeTraversal</code> appears in 5 methods, and is every time identical. It should be in its own method, and need only called once from <code>Traverse</code>.</p>\n\n<p>This appears all over the place:</p>\n\n<pre><code>_treeTraversal[_treeTraversalIndex] = /*something*/;\n_treeTraversalIndex++;\n</code></pre>\n\n<p>This could be another little method: it would make the code much tidier if it had calls to <code>Append(int)</code> instead of this everywhere, which hides away the complexity of the task, and makes the intention clear.</p>\n\n<p>I'd also replace <code>_currentTraverseForm = -1;</code> everywhere with an <code>InvalidateTraversal()</code> method. This saves you having to put comments in explaining why this cryptic operation is occuring, and will make it much easier to change the behaviour in furture if you see fit to do so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:01:29.050",
"Id": "423550",
"Score": "0",
"body": "thx for good tips. I am working on it. Printing was done for my testing and i forgot to remove it. Can you explain that:\n\n\"Generally, you are opening a serious can of worms when you expose implementation details like your Node class to the world, because anyone can modify a Node from the BST and ruin the data-structure: if you don't need to expose this information, then do not.\"\n\nHow can i fix it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T21:22:31.747",
"Id": "423554",
"Score": "0",
"body": "@UrbanKravos if you put `Node` inside `BST` and make it private, then suddenly the compiler will complain everywhere you are exposing this detail. Then you just have to go through and 'fix' every spot where `Node` is escaping (e.g. you'd have to make `Insert(Node)` private, same with `BinarySearch` (could expose it instead as a `bool Contains(int value)` method, which is much nicer than a `null` check)). Without a detailed spec, it's hard to know whether you _need_ `Node` to leak or not, but if you don't, you can provide a much tighter API by just using `int` (or a generic type) everywhere."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T19:05:13.640",
"Id": "219273",
"ParentId": "219271",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T18:05:54.277",
"Id": "219271",
"Score": "3",
"Tags": [
"c#",
"tree"
],
"Title": "C# Binary search tree"
} | 219271 |
<p>This program is the basis for a bigger game I'm working on. I want to make sure I did this correctly before moving on. Please give pointers to anything I can improve. I'm learning on my own, so I doubt my structure is the best it can be.</p>
<h3>enemy.py module</h3>
<pre><code>class enemy:
'''
This is how to define users and items
'''
def __init__(self, name, hp, damage):
self.name = name
self.hp = hp
self.damage = damage
class item:
def __init__(self, name, hp_bonus, damage_bonus, shield):
self.name = name
self.hp_bonus = hp_bonus
self.damage_bonus = damage_bonus
self.shield = shield
</code></pre>
<h3>game.py/ main module</h3>
<pre><code>import random
import time
from enemy import enemy
from enemy import item
Level = 1
Level_Bonus = [2.0, 5.0, 8.0, 11.0, 13.0, 15.0, 18.0]
Level_Max = 20
ITEM = ""
Enemy = ""
Potion = random.randint(3, 7)
Enemies_Fought = 0
Player = enemy("Player", 100, random.randint(5, 8))
Dog = enemy("DOG", 40, random.randint(1, 8))
Cat = enemy("Cat", 20, random.randint(1, 5))
Monkey = enemy("Monkey", 55, random.randint(5, 8))
Ogre = enemy("Ogre", 100, random.randint(10,120))
Ring = item("RING", 10, 0, 0)
Sword = item("SWORD", 0, 10, 0)
Shield = item("SHIELD", 0, 0, 3)
No_item = item("NO ITEM", 0, 0, 0)
def ITEM_CHANCE():
global ITEM
item_chance = random.randint(1,1000)
if item_chance > 1 and item_chance < 80:
ITEM = Ring
Player.hp += ITEM.hp_bonus
print('''
Your health has increased by 10!''')
print(f'''
You found a {ITEM.name}!!!''')
elif item_chance > 140 and item_chance < 175:
ITEM = Sword
Player.damage += ITEM.damage_bonus
print('''
Your damage has increased by 10!''')
print(f'''
You found a {ITEM.name}!!''')
elif item_chance > 500 and item_chance < 600:
ITEM = Shield
Enemy.damage -= ITEM.shield
print('''
Enemy damage reduced by 3!!''')
print(f'''
You found a {ITEM.name}!!!''')
else:
ITEM = No_item
print('''
No items found''')
def which_enemy():
global Enemy
Enemy_choose = random.randint(1, 100)
if Enemy_choose < 30:
Enemy = Cat
elif Enemy_choose > 30 and Enemy_choose < 70:
Enemy = Dog
elif Enemy_choose > 70 and Enemy_choose < 95:
Enemy = Monkey
else:
Enemy = Ogre
def fight():
global Enemy
global Player
which_enemy()
print(f'''
You have come across a {Enemy.name}''')
keep_going = input(f'''
Do you wish to fight it, this will be a battle to the death and
your hp is "{Player.hp}".
1) Yes.
2) No.
Enter option: ''')
if keep_going == "2":
print(f'''
The enemy hit you for {Enemy.damage} as you escaped.
''')
Player.hp = Player.hp - Enemy.damage
print(f'''
Your health is now {Player.hp}
''')
return False
elif keep_going == "1":
while Player.hp > 0 and Enemy.hp > 0:
print(f'''
The enemy hit you for {Enemy.damage} damage''')
Player.hp = Player.hp - Enemy.damage
if Player.hp < 0:
Player.hp = 0
print(f'''
Your health is now {Player.hp}''')
time.sleep(.2)
print(f'''
You hit the enemy for {Player.damage} damage''')
Enemy.hp = Enemy.hp - Player.damage
if Enemy.hp < 0:
Enemy.hp = 0
print(f'''
The enemy's health is now {Enemy.hp}''')
time.sleep(.2)
else:
return False
if Enemy.hp == 0: # Reset all enemy health for next round
if Enemy == Dog:
Enemy.hp = 40
elif Enemy == Cat:
Enemy.hp = 20
elif Enemy == Monkey:
Enemy.hp = 55
def main():
while True:
global Enemies_Fought
global Level
PLAY = input('''Do you wish to fight a creature?"
1) Yes
2) No''')
if PLAY == "2":
print('''
You gave up. You loose.''')
break
elif PLAY == "1":
ITEM_CHANCE()
Player.hp = Player.hp
fight()
Enemies_Fought += 1
Level += .5
print(f'''
Your level is {Level}''')
if Level in Level_Bonus:
Player.hp = 100
Player.damage = Player.damage + 5
print(f'''
Your damage is {Player.damage}, and your hp has been restored.''')
if Player.hp <= 0:
print(f'''
You reached level: {Level}
You killed: {Enemies_Fought} enemies
''')
print('''
You have died. Thanks for playing''')
break
else:
print('''
Enter valid option.''')
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:26:31.833",
"Id": "423569",
"Score": "0",
"body": "Welcome to CodeReview! I'm sure you'll get some good feedback, but can you go ahead and include the `enemy` module as well? And edit the existing code so it's all one big \"file\", including any parts you may have left out?"
}
] | [
{
"body": "<h2>Gameplay</h2>\n\n<p>So I played the game:</p>\n\n<pre><code>Do you wish to fight a creature?\"\n 1) Yes\n 2) No1\n\n No items found\n\n You have come across a DOG\n\n Do you wish to fight it, this will be a battle to the death and\n your hp is \"100\".\n 1) Yes.\n 2) No.\n Enter option: 1\n\n The enemy hit you for 7 damage\n\n Your health is now 93\n\n ... many lines elided ...\n\n Your level is 1.5\nDo you wish to fight a creature?\"\n 1) Yes\n 2) No2\n\n You gave up. You loose.\n</code></pre>\n\n<p>There are some glaring problems here. First, the extra quotation mark. Next,\nfor some reason you are not printing a newline or a prompt after the Yes/No\nmenu, so the user's choice is echoed after \"No\". Third, I don't know what that\n\"No items found\" message is for, but it's not appropriate at that point in the\ngame. Fourth, all the hit/counter-hit turns are spaced evenly. It would\nprobably be better if the lines were grouped into paragraphs. Finally, \"loose\"\nmeans \"released\" or \"not tight\". You want to say \"You lose\" (1 'o') which is\nthe opposite of \"You win\".</p>\n\n<h2>Coding Style</h2>\n\n<p>Your coding style is pretty jarring. The official Python coding style guide is\nin <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, which I recommend you follow slavishly until you develop\nstrong opinions about a different style.</p>\n\n<h3>Organization</h3>\n\n<p>You have an <code>enemy</code> module, but I don't see a very good reason to keep that\ncode separate. I suggest you just bundle it into the same file as the rest of\nyour game source code. Python is not Java, and you don't need one file per\nclass or anything. Putting related things together is the right thing to do.</p>\n\n<h3>Orthography</h3>\n\n<p>The simple rules for PEP-8 naming:</p>\n\n<ul>\n<li><p>Use <code>snake_case</code> names for functions, methods, module, variables, and\nattributes.</p></li>\n<li><p>Use <code>PascalCase</code> for class names.</p></li>\n<li><p>Use <code>ALL_CAPS</code> for module- or class-level \"constant\" values. (Even though the\nstandard library uses lower case. Do as they say, not as they do.)</p></li>\n</ul>\n\n<h3>Organization</h3>\n\n<p>Use this layout until you have to use a different one, and can justify the\nneed.</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\" Docblock describing the program or module.\n\"\"\"\nimport from __future__ # Usually not present\n\n__dundernames__ # Usually not present\n\nimport standard libary modules\n\nimport 3rd party modules\n\nimport project local modules\n\nGLOBAL_CONSTANTS\n\nGlobal_variables # Location here is PEP8. Cap is my thing.\n\nclass ClassName:\n pass\n\ndef some_function():\n pass\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Design</h2>\n\n<p>You have two classes, but they don't have methods. So I suspect you aren't\ncomfortable with deep OO designs or anything just yet. That's fine, but I'm\ngoing to pitch my ideas in that direction. As you learn more OO, you'll know\ndifferent ways to approach this same problem.</p>\n\n<h3>Create a TextInterface class</h3>\n\n<p>You are sending a lot of messages to the screen. And in those messages, you are\nworking to try to insert newlines and manage the appearance of the message in\nsome kind of consistent manner.</p>\n\n<p>Instead of trying to manage this using triple-quoted strings with embedded\nnewlines, why not create a dedicated class with methods to manage that for you?\nCreate a TextInterface class with methods that reflect the <em>kind</em> of output you\nare sending:</p>\n\n<pre><code>class TextInterface:\n def stat_change(self, msg):\n print(f\"\\n{msg}\")\n\n def found_item(self, msg):\n print(f\"\\n{msg}\")\n</code></pre>\n\n<p>Then you can consistently change the formatting of all messages of a particular\n\"type\" by editing one function. All you have to do is pick the right type for\neach message you print.</p>\n\n<h3>Use parameters/return instead of globals</h3>\n\n<p>If you are treating a global variable as read-only, don't access it as a global\n(even if it exists at global scope). Instead, pass that value as an argument to\nthe functions that need it.</p>\n\n<p>Similarly, if you are setting a global variable inside a function, consider if\nyou could just return the value from the function instead:</p>\n\n<pre><code>def ITEM_CHANCE():\n global ITEM\n item_chance = random.randint(1,1000)\n if item_chance > 1 and item_chance < 80:\n ITEM = Ring\n Player.hp += ITEM.hp_bonus\n print('''\n Your health has increased by 10!''')\n print(f'''\n You found a {ITEM.name}!!!''')\n</code></pre>\n\n<p>This could be:</p>\n\n<pre><code>def maybe_drop_item():\n drop_probabilities = (\n (Ring, 80),\n (Sword, 35),\n (Shield, 100),\n )\n drop_items, weights = zip(*drop_probabilities)\n cum_dist = list(itertools.accumulate(weights))\n\n # Chance of no drop\n if cum_dist[-1] < 1000:\n cum_dist.append(1000)\n drop_items.append(None)\n\n randval = random.random() * cum_dist[-1]\n item = drop_items[bisect.bisect(cum_dist, randval)]\n return item\n</code></pre>\n\n<p>Once you randomly choose an item, you can describe it while using it (I notice\nyou have the Player as type <code>Enemy</code>, so make this a method on that class):</p>\n\n<pre><code>class Enemy:\n def use_item(self, item):\n if item is None:\n return\n\n TextInferface.found_item(\"You found a {item.name}!!!\")\n\n if item.hp_bonus:\n self.hp += item.hp_bonus\n TextInterface.stat_bonus(f\"Your health has increased by {item.hp_bonus}!\")\n if item.damage_bonus:\n self.damage += item.damage_bonus\n TextInterface.stat_bonus(f\"Your damaged has increased by {item.damage_bonus}!\")\n\n if item.shield:\n self.shield += item.shield:\n TextInterface.stat_bonus(f\"Enemy damages reduced by {item.shield}!\")\n</code></pre>\n\n<p>(Note: this last function treats shields as permanent items, while your code\napplies them only to the current enemy. If you don't like that change, feel\nfree to adjust it.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:16:49.417",
"Id": "423615",
"Score": "0",
"body": "Thanks for your time, and in depth response. I will work on what you have pointed out and start over again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T03:29:28.980",
"Id": "219286",
"ParentId": "219282",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219286",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:00:54.250",
"Id": "219282",
"Score": "6",
"Tags": [
"python",
"beginner",
"battle-simulation"
],
"Title": "Game that fights random enemy"
} | 219282 |
<p>i am not the best at security but need a custom way to securely store personal identifiable information like name, address etc - Can i please have some feedback on this custom code, from my perspective it looks okay but with security not being my strong point i don't trust myself.</p>
<p>The data is passed from my application over HTTPS in the header along with a custom auth code which is made up from the users unique ID, fcm ID, package name and the epoch date they obtained the auth code.</p>
<p>This is sent to the server on every request and decrypted to make sure that we have the correct user - the server won't provide any details back to the unless the epoch date matches (this is stored in the database on the auth creation) </p>
<p>Here is the encrypt / decrypt function</p>
<pre><code>function encrypt($string, $public_key = "public key", $action = "e") {
$secret_key = "secret key";
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $public_key );
$secret = substr( hash( 'sha256', $secret_key), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $secret) );
} else if ( $action == 'd') {
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $secret);
}
if (empty($output)) {
denyAccess();
}
return $output;
}
</code></pre>
<p>the data stored in the database uses the same function but with different keys so the data is encrypted twice. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:07:52.370",
"Id": "423581",
"Score": "1",
"body": "Welcome to Code Review. I couldn't answer your question, too much code is missing for my taste, but I do notice two things: 1. The variable `$secret_key` is never used, and the variable `$secret_iv` is never defined. Is that a mistake? 2. Your function encrypts and decrypts, but is simply called `encrypt()`. That is _very_ confusing. This should be split into 2 functions, or be a class. A tip: Give us more code to review, that way you will get a better review. There simply isn't much to review here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:30:03.557",
"Id": "423600",
"Score": "1",
"body": "Also: `$output` will probably never be empty. Unless, of course, you provide an invalid `$action`. However, I think you want to respond to the input `$string` of this function, not the output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:43:44.670",
"Id": "423610",
"Score": "0",
"body": "`else` is more appropriate than `if (empty($output)) {`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:20:55.700",
"Id": "423616",
"Score": "0",
"body": "@KIKOSoftware yes sorry i changed the variable names when copying on here for easier readability the secret_iv is the secret_key"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:33:17.457",
"Id": "423620",
"Score": "0",
"body": "Are we really only to review this solitary function? Are we right to assume that `denyAccess();` kills everything (the function `encrypt()` never gets a chance to return)? How are `encrypt()` calls performed? We'd like to see more code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-27T23:02:29.397",
"Id": "219283",
"Score": "2",
"Tags": [
"php",
"android",
"security"
],
"Title": "Custom Security for API access from server to mobile application"
} | 219283 |
<p>Although UTF-8 validation is a common task, I'm trying to solve a slightly different task; given a string of bytes, work out whether it could potentially be a fragment of a valid UTF-8 string. That's a much less common task, so I thought it'd be easiest to write the code myself. Here's the Perl subroutine I came up with:</p>
<pre class="lang-perl prettyprint-override"><code># Takes one argument, a string with codepoints in the range 0-255
# (representing the bytes of input); returns truthy if and only if some
# valid UTF-8 string has that string as a substring.
sub could_be_substring_of_valid_utf8 {
# We're using regexes on bytes (encoded as codepoints), so
# codepoints don't have their normal Unicode meaning. Tell Perl
# that ASCII = ASCII (it does in UTF-8), but newlines and
# codepoints from 128 up are not special.
use re '/aas';
my $substring = shift;
my $cb = qr/[\x80-\xbf]/; # continuation byte
my $ncb = qr/[^\x80-\xbf]/; # not a continuation byte
my $lb1 = qr/[\xc0-\xdf]/; # leading byte for 1 continuation byte
my $lb2 = qr/[\xe0-\xef]/; # leading byte for 2 continuation bytes
my $lb3 = qr/[\xf0-\xf7]/; # leading byte for 3 continuation bytes
for ($substring) {
# Bytes F8 to FF are never legal in UTF-8 (they'd be leading
# bytes for 4 or more continuation bytes, never necessary to
# represent something within the Unicode range). Bytes F5-F7
# are likewise illegal, because any string starting 0xF5 must
# represent a codepoint of at least U+140000, higher than the
# maximum codepoint of U+10FFFF.
return if /[\xf5-\xff]/;
# Likewise, if we see 4 or more continuation bytes in a row,
# that's also obviously illegal even if we can't see the
# leading byte.
return if /$cb{4}/;
# A string of continuation bytes cannot appear without a leading
# byte to its left, so each individual continuation byte requires
# a leading or continuation byte to its left.
return if /[\x00-\x7f]$cb/;
# A string of leading bytes requires exactly that many continuation
# bytes after it.
return if /($lb1|$lb2|$lb3)$ncb/; # missing first continuation byte
return if /($lb2|$lb3).$ncb/; # missing second continuation byte
return if /$lb3..$ncb/; # missing third continuation byte
return if /$lb1$cb$cb/; # too many continuation bytes
return if /$lb2$cb$cb$cb/; # too many continuation bytes
return if /$lb3$cb$cb$cb$cb/; # too many continuation bytes
# Codepoints U+D800 to U+DFFF must not be encoded in UTF-8 (as
# they're used only as an internal part of UTF-16); ban UTF-8
# sequences that attempt to do that. The encoding of U+D???
# always starts with 0xED, and the MSB of the next nybble
# appears in the 0x20s place of the first continuation byte,
# which is enough information to recognise one even from a
# partial encoding.
return if /\xed[\xa0-\xbf]/; # encodes a surrogate
# Codepoints U+FFFE and U+FFFF must not be encoded in UTF-8.
# Their encodings are 0xEF 0xBF 0xBE and 0xEF 0xBF 0xBF.
return if /\xef\xbf[\xbe\xbf]/;
# Codepoints above U+10FFFF must not be encoded in UTF-8.
# Encodings starting 0xF4 0x9? encode codepoints of the form
# U+11????, and are therefore illegal; likewise, 0xF4 0xA?
# and 0xF4 0xB? encode codepoints of the form U+12???? and
# U+13???? respectively and are illegal. (Codepoints from
# U+140000 upwards have been excluded already by the check
# on illegal bytes.)
return if /\xf4[\x90-\xbf]/;
}
1;
}
</code></pre>
<p>As is recommended nowadays for handling raw bytes in Perl, the strings of bytes are represented as strings where each codepoint in the string represents the byte with the corresponding number (e.g. the byte 0xA0 is encoded as "\x{A0}"); this means that you don't have to worry about how the string is represented internally within Perl (as it happens, it has an optimised internal encoding for strings with codepoints in the 0–255 range, but this code doesn't care about whether it's in use or not).</p>
<p>I believe this subroutine is working, but it's fairly complex and I find it hard to be confident that the code is written as well as it could be. My primary concern is code clarity; anything that would make it more obvious that the code is correct would be useful (especially improvements to things like comments and identifiers). I also care about portability (avoiding experimental features or features only present in newer Perls unless they would be make the code more correct, or particularly faster or clearer), which is why I've used <code>for</code> to set a local binding to <code>$_</code> rather than the clearer <code>given</code>; the code should currently work in Perl 5.14 or later, although I haven't tested it on old versions.</p>
<p>I initially wrote this without worrying about performance. It isn't a major concern yet, but may become so in future, so I'd take any tips for improving performance as long as they don't make the code significantly harder to read. (In particular, I suspect that combining everything into one regex might be more efficient; is it possible to do that while keeping things readable?)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:22:48.857",
"Id": "423597",
"Score": "1",
"body": "You should also post your unit tests for this function, just for completeness. This might give some hints on edge cases you might have forgotten to test."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:28:24.457",
"Id": "423598",
"Score": "1",
"body": "I would have chosen a different approach: take a DFA that accepts UTF-8 (there should already exist plenty of them, well-tested) and transform that into an NFA that starts in every intermediate state. Then validate that after processing the substring, the NFA is still in some valid state. — After doing this, you have two implementations that should behave the same. Use a fuzzer to generate random byte sequences and ensure that both implementations indeed behave the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:12:08.183",
"Id": "423614",
"Score": "1",
"body": "maybe put the regexes in a state variable or in a package variable to avoid recompiling them on each call to the subroutine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:22:33.950",
"Id": "423617",
"Score": "0",
"body": "@RolandIllig: I don't have a complete set of automated unit tests for this subroutine yet (I've been verifying that it works via running a number of *ad hoc* tests, but don't have an enumeration of all cases or something like that). They'd be unlikely to catch mistakes in it anyway, because if I'm under a misconception that causes the program to be wrong, the tests would likely contain a similar misconception. In particular, if I've missed a case in the subroutine's body, how would I know of that case to test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T11:28:36.213",
"Id": "423619",
"Score": "0",
"body": "@HåkonHægland: I was under the impression (and checking `perlreguts` confirms this) that constant regexes are compiled at the same time that the program is, so they aren't being recompiled on each call to the subroutine anyway. A quick test, `perl -Mre=debug -E'sub x {my $a=qr/a/; my $b=qr/a$a/;} BEGIN{die;}'`, shows that uninterpolated regexes are compiled only once, but interpolated regexes are compiled on each call, so there would be a performance gain there by moving regexes like `/$cb{4}/` to package variables (and when you start doing that, you may as well move them all for consistency)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T13:28:39.310",
"Id": "423627",
"Score": "1",
"body": "Automated tests might not help you realize what your wrong assumptions are, but it would help us find and tell you what your wrong assumptions are. Since that doesn't exist it would be nice to include some usage examples. Don't you want some of those for your documentation anyway?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T14:15:01.773",
"Id": "423631",
"Score": "2",
"body": "@ais523 When you don't generate the DFA yourself but use a preexisting implementation, that implementation will not have any of your misconceptions. The first google hit was [this awesome simple and well-documented piece of code](https://bjoern.hoehrmann.de/utf-8/decoder/dfa/). To compare this with your code, you would just have to allocate an array of 8 state variables, initialize them to `{0, 2, 3, 4, 5, 6, 7, 8}`, run the DFA over your substring for each of these states and see if any of these states is still valid, that is, not `1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T23:08:58.740",
"Id": "423665",
"Score": "0",
"body": "@RolandIllig: That does indeed look like a good way to derive the full set of potential rules, so it would make a good testing or even proving strategy (and in fact, it does show that I missed a case: overlong encodings for in-range codepoints). Per Code Review rules, I won't edit the code now that people have been commenting on it, but I think the best approach here is to generate a correctness proof for the code; we can take the readable regexes from the program (after fixing them), and the unreadable states from the DFA, and prove that they lead to the same result."
}
] | [
{
"body": "<p>Performance improvements:</p>\n\n<pre><code># Checks if the provided UTF-8 is complete (doesn't end mid-sequence).\nsub is_complete_utf8 {\n my $utf8 = shift;\n\n # This will be used against a reversed string.\n state $incomplete_seq = qr/\n ^\n (?: (?&lead_of_2)\n | (?&lead_of_3)\n | (?&lead_of_4)\n | (?&cont_byte) (?: (?&lead_of_3)\n | (?&lead_of_4)\n | (?&cont_byte) (?&lead_of_4) ))\n\n (?(DEFINE)\n (?<lead_of_1> [\\x00-\\x7F] )\n (?<cont_byte> [\\x80-\\xBF] )\n (?<lead_of_2> [\\xC0-\\xDF] )\n (?<lead_of_3> [\\xE0-\\xEF] )\n (?<lead_of_4> [\\xF0-\\xF7] )\n (?<invalid> [\\xF8-\\xFF] )\n )\n /x;\n\n return reverse(substr($utf8, -4)) !~ $incomplete_seq;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>Adjust to handle invalid UTF-8 as desired.</li>\n<li>I started by writing a version that used a pattern that looked for complete sequences, but it handled invalid UTF-8 poorly. If invalid seqences are to be considered complete, it's cleaner and simpler to match incomplete sequences.</li>\n<li>There's no performance benefit to using <code>qr//</code> here; I did that for readability.</li>\n<li>Performance could benefit from creating a class equivalent to <code>(?&lead_of_2) | (?&lead_of_3) | (?&lead_of_4)</code> and one equivalent to <code>(?&lead_of_3) | (?&lead_of_4)</code>.</li>\n<li>Performance would benefit from writing this function in C instead of using the regex engine.</li>\n</ul>\n\n<p>Comments on your code:</p>\n\n<ul>\n<li>This sub is expected to return a scalar (something true or false). And while your sub does that when it's invoked in scalar context, it produces surprising results in list context. Replace <code>return</code> with <code>return 0;</code>.</li>\n<li>Is <code>1;</code> really better than <code>return 1;</code>?</li>\n<li>The name of the sub was hard to understand. I reversed the sense of the function (now returns true if complete instead of true if incomplete) to provide a better name. (You could use <code>is_incomplete_utf8</code>, but that could lead to double-negation in the caller.)</li>\n<li>There is a such as excessive commenting :)</li>\n<li>It might be more useful to return a number indicating how many bytes to remove to get only complete sequences.</li>\n<li><code>/aas</code> is useless in your code.\n\n<ul>\n<li><code>/aa</code> affects some built-in characters classes (e.g. <code>\\s</code>) and <code>\\b</code>.</li>\n<li><code>/s</code> affects <code>.</code>.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-29T21:58:57.877",
"Id": "477151",
"Score": "0",
"body": "Isn't this solving an entirely different task to my program? I want to distinguish between sequences like 0x80 0x81 0x82 which could validly appear somewhere inside a UTF-8 string, and 0x80 0x81 0x82 0x83 which can't. Your code seems to assume valid UTF-8, and checks to see whether it ends at a character boundary or not. (Incidentally, I was under the impression that `return;` is better than `return 0;` for producing falsey values, because the list `(0)` is truthy.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T02:53:59.767",
"Id": "477172",
"Score": "1",
"body": "Re \"*Isn't this solving an entirely different task to my program?*\", Maybe. I did what the title says: Identify whether a string is a fragment of UTF-8. This is a common problem when reading from a file handle, sockets and pipes in particular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T03:12:29.413",
"Id": "477177",
"Score": "1",
"body": "Re \"*Your code seems to assume valid UTF-8,*\", No, it correctly handles invalid UTF-8. It's not a validator, if that's what you mean. But you said you weren't looking for a validator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T03:12:56.657",
"Id": "477178",
"Score": "1",
"body": "Re \"*because the list (0) is truthy.*\", Lists are neither true nor false because you can't evaluate the truthness of a list. Only scalars are true or [false](https://stackoverflow.com/a/5655485/589924)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-30T03:13:04.710",
"Id": "477179",
"Score": "1",
"body": "Say sub `is_foo` is expected to return a boolean. Most of the time, it might be used as `if (is_foo()) { ... }` or `my $foo = is_foo()`. In that situation, a `return` in `is_foo` would effectively be `return undef`, and this would work correctly. But one day, someone will do `my %h = ( foo => is_foo(), bar => \"moo\" );` That will fail with `return`. So say what you mean and use `return undef` (or `return 0`) explicitly instead of relying on `return` returning `undef`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-28T20:53:53.940",
"Id": "243081",
"ParentId": "219285",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T02:58:28.040",
"Id": "219285",
"Score": "8",
"Tags": [
"strings",
"perl",
"utf-8"
],
"Title": "Checking whether a string fragment could be part of a longer UTF-8 string"
} | 219285 |
<pre><code># Collect the values of a map into a mapset
def values(map) do
Enum.reduce(map, MapSet.new(),
fn ({_, value}, acc) ->
MapSet.put(acc, value)
end
)
end
values.(%{"a"=>1, "b"=>1, "c"=>2}) |>
IO.inspect
</code></pre>
<p>Is there a cleaner way to write this values function?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:53:04.763",
"Id": "423591",
"Score": "0",
"body": "Does the `Map` provide access to its values as a collection? In Java I would express this as `new Set(map.values())`, using the Set constructor that copies elements from another collection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:00:09.180",
"Id": "423592",
"Score": "2",
"body": "After reading the documentation, `MapSet.new(map.values())` is probably all you need."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T04:31:46.550",
"Id": "219287",
"Score": "1",
"Tags": [
"elixir"
],
"Title": "Collect the values of a Map into a MapSet"
} | 219287 |
<blockquote>
<p>We have a list of points on the plane. Find the K closest points to
the origin (0, 0).</p>
<p>(Here, the distance between two points on a plane is the Euclidean
distance.)</p>
<p>You may return the answer in any order. The answer is guaranteed to
be unique (except for the order that it is in.)</p>
<p><strong>Example 1:</strong></p>
<p>Input: points = [[1,3],[-2,2]], K = 1</p>
<p>Output: [[-2,2]]</p>
<p>Explanation: The distance between (1, 3) and the origin is
<span class="math-container">\$\sqrt{10}\$</span>. The distance between (-2, 2) and the origin is
<span class="math-container">\$\sqrt{8}\$</span>. Since <span class="math-container">\$\sqrt{8} < \sqrt{10}\$</span>, (-2, 2) is closer to
the origin. We only want the closest K = 1 points from the origin, so
the answer is just [[-2,2]].</p>
<p><strong>Example 2:</strong></p>
<p>Input: points = [[3,3],[5,-1],[-2,4]], K = 2</p>
<p>Output: [[3,3],[-2,4]]</p>
<p>(The answer [[-2,4],[3,3]] would also be accepted.)</p>
<p><strong>Note:</strong></p>
<ul>
<li>1 <= K <= points.length <= 10000</li>
<li>-10000 < points[i][0] < 10000</li>
<li>-10000 < points[i][1] < 10000</li>
</ul>
<p>Also note that there can be a situation where distance of 2 nodes are
equal and hence can print any of the node.</p>
</blockquote>
<hr>
<p>Here is my approach.</p>
<ol>
<li>Took tree map (So that I get all sorted distance)</li>
<li>Start filling tree map for all points</li>
<li>Finally took first k element.</li>
</ol>
<pre><code>public class KClosestPointsToOrigin {
public int[][] kClosest(int[][] points, int K) {
int rows = points.length;
SortedMap<Double, List<CoordinatePoint>> distanceToPoint = new TreeMap<>();
for(int i =0; i<rows; i++) {
double distance = getDistance(points[i]);
if(Objects.nonNull(distanceToPoint.get(distance))) {
List<CoordinatePoint> coordinatePointList = distanceToPoint.get(distance);
coordinatePointList.add(new CoordinatePoint(points[i][0], points[i][1]));
} else {
List<CoordinatePoint> coordinatePoints = new ArrayList<>();
coordinatePoints.add(new CoordinatePoint(points[i][0], points[i][1]));
distanceToPoint.put(distance, coordinatePoints);// x and y coordinates.
}
}
int[][] arrayToReturn = new int[K][2];
int counter = 0;
for (Double key : distanceToPoint.keySet()) {
List<CoordinatePoint> coordinatePoints = distanceToPoint.get(key);
Iterator iterator1 = coordinatePoints.iterator();
while (iterator1.hasNext() && counter < K) {
CoordinatePoint coordinatePoint = (CoordinatePoint) iterator1.next();
arrayToReturn[counter][0] = coordinatePoint.x;
arrayToReturn[counter][1] = coordinatePoint.y;
counter++;
}
}
return arrayToReturn;
}
private double getDistance(int[] point) {
int x = point[0];
int y = point[1];
int x2 = Math.abs(x) * Math.abs(x);
int y2 = Math.abs(y) * Math.abs(y);
return Math.sqrt(x2+y2);
}
}
class CoordinatePoint {
int x;
int y;
public CoordinatePoint(int x, int y) {
this.x = x;
this.y = y;
}
}
</code></pre>
<p>However, this solution is not efficient as runtime and memory usage is high. Can you please help me to optimize the solution.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:25:06.727",
"Id": "423583",
"Score": "1",
"body": "What do you mean by \"runtime is high\": is it longer than say \\$\\mathcal O(n\\log n)\\$? And did you measure the memory usage? You are guaranteed to get at most 10000 points, and I think memory usage is \\$\\mathcal O(n\\log n)\\$ as well. As long as there is nothing quadratic, I wouldn't be worried."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:27:10.197",
"Id": "423584",
"Score": "0",
"body": "Since you know \\$k\\$ in advance, you only ever need to store the \\$k\\$ points that are closest to the origin."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:56:47.150",
"Id": "423686",
"Score": "0",
"body": "@RolandIllig the leetcode submission shows Runtime: 75 ms\nMemory Usage: 68.3 MB, which is 15.44% of other solution. I want to improve on Runtime and memory usage."
}
] | [
{
"body": "<p>This task sounds as if it came directly from an advertisement for the Java 8 streams API:</p>\n\n<ul>\n<li>Sort the points by their distance</li>\n<li>Take the minimum k points</li>\n</ul>\n\n<p>This boils down to the following code:</p>\n\n<pre><code>static int[][] kClosest(int[][] points, int k) {\n return Arrays.stream(points)\n .sorted(Comparator.comparing((int[] point) -> point[0] * point[0] + point[1] * point[1]))\n .limit(k)\n .toArray(int[][]::new);\n}\n</code></pre>\n\n<p>That code is written from the top of my head. Since the Java streams API is general-purpose and intended to be highly optimized, it should notice that it only ever needs to remember the <span class=\"math-container\">\\$k\\$</span> smallest elements. You should check this by counting how often the distance function is called. To do that you should extract it to a local method, which is something that your IDE can do for you.</p>\n\n<p>Compared to your code:</p>\n\n<ul>\n<li>I left out the <code>Math.sqrt</code> since the point coordinates are restricted to 10000, which means that the square of the distance can become at most 2e8, which luckily is a bit smaller than <code>Integer.MAX_VALUE</code>.</li>\n<li>Calling <code>Math.abs</code> is unnecessary as well.</li>\n<li>Making a map of lists may help in pathological cases when the given points all have the same distance. In other cases it can be left out.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:58:15.767",
"Id": "423688",
"Score": "0",
"body": "Thanks @Roland I will check this out. In java 8, it is just 2 lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:43:58.307",
"Id": "219296",
"ParentId": "219291",
"Score": "1"
}
},
{
"body": "<p>It would make more sense to store the distance with the point so that you don't have to calculate it each time. </p>\n\n<pre><code>class CoordinatePoint implements Comparable<CoordinatePoint> {\n\n int[] coordinates;\n int squaredDistance;\n\n private CoordinatePoint(int[] coordinates, int squaredDistance) {\n this.coordinates = coordinates;\n this.squaredDistance = squaredDistance;\n }\n\n public CoordinatePoint create(int[] coordinates) {\n int squaredDistance = coordinates[0] * coordinates[0] + coordinates[1] * coordinates[1];\n return new CoordinatePoint(coordinates, squaredDistance);\n }\n\n public int[] getCoordinates() {\n return coordinates;\n }\n\n @Override\n public int compareTo(CoordinatePoint coordinatePoint) {\n return -Integer.compareTo(this.squaredDistance, point.squaredDistance);\n }\n\n}\n</code></pre>\n\n<p>I stored the squared distance because it compares the same as the distance but is easier to calculate. </p>\n\n<p>The square of an integer (real numbers in general) is always positive, so taking the absolute value is unnecessary. </p>\n\n<p>I implemented <code>Comparable</code> so that it could be used with a <code>PriorityQueue</code> without declaring a <code>Comparator</code>. </p>\n\n<pre><code> Queue<CoordinatePoint> nearestPoints = new PriorityQueue<>(K);\n\n for (int[] point : points) {\n nearestPoints.add(CoordinatePoint.create(point));\n\n while (nearestPoints.size() > K) {\n nearestPoints.remove();\n }\n }\n\n int index = 0;\n int[][] results = new int[nearestPoints.size()][2];\n for (CoordinatePoint point : nearestPoints) {\n results[index] = point.getCoordinates();\n index++;\n }\n\n return results;\n</code></pre>\n\n<p>Defined this way, the <code>PriorityQueue</code> returns the largest distance. So what this does is it adds each point to the heap (which is how a <code>PriorityQueue</code> is stored). Then if there are too many points, it removes all but <code>K</code> of them. Then it just converts the heap to an array. </p>\n\n<p>Using the <code>PriorityQueue</code> simplifies the logic. And this solution has a runtime complexity of <span class=\"math-container\">\\$\\mathcal{O}(n\\log k)\\$</span> where <span class=\"math-container\">\\$n\\$</span> is the number of points in the input and <span class=\"math-container\">\\$k\\$</span> is the number to return. This is because for each element in the input, you insert it into a heap of at most <span class=\"math-container\">\\$k\\$</span> elements. And heaps have logarithmic insertion complexity. Your original solution was <span class=\"math-container\">\\$\\mathcal{O}(n\\log n)\\$</span> because it inserted all the elements into the set before removing only some of them. </p>\n\n<p>But actually, I think that this problem is trying to get you to implement the heap yourself. The reason that I think that is that it would be quite possible to return an array organized as a heap. You'd lose the storage of the squared distance that way, so you'd have to calculate it each time. But you'd save storage space and the work of copying the results from intermediate storage. </p>\n\n<p>The part about not caring about order strongly suggests using a heap, as that is one of the properties of a heap. It makes finding the smallest or largest element easy but does not store the elements in order after that. </p>\n\n<p>I haven't tested this code, so be careful of compile errors, etc. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:01:29.627",
"Id": "423689",
"Score": "0",
"body": "Wow.. never thought about using Priority Queue.Thanks @mdfst13. Yes can check as well on using custom heap as an array. May be it can save space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:28:08.057",
"Id": "423690",
"Score": "0",
"body": "Using priority queue saved the running time from 75ms to 34ms. Almost half!!! However, the memory usage is still 68mb. I tried returning from priority queue as an array, using `toArray` method, but the compilation error happened."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T18:05:53.127",
"Id": "219317",
"ParentId": "219291",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T05:44:57.140",
"Id": "219291",
"Score": "2",
"Tags": [
"java",
"sorting",
"interview-questions",
"tree",
"computational-geometry"
],
"Title": "Find all k points which are closest to origin"
} | 219291 |
<p>I want reverse the string with the same order. We should not use the Array functions like <code>split(), .reverse()</code> and some other array functions also except <code>array.length</code>.</p>
<p>Here i am attached my code. How to achieve that thing more efficiently.</p>
<pre><code>var str = "i am javascript";
// result "i ma tpircsavaj"
function reverseString(myStr){
var strlen = myStr.length, result = "", reverseStr = "", reverseStrArr = [];
for(var i = strlen-1; i >= 0; i--){
reverseStr += myStr[i];
}
for(var j = 0; j < strlen; j++){
if(reverseStr[j] == " "){
reverseStrArr.push(result);
result = "";
}else{
result += reverseStr[j];
if(j + 1 == strlen){
reverseStrArr.push(result);
result = "";
}
}
}
for(var k=reverseStrArr.length - 1; k >= 0; k--){
result += reverseStrArr[k] + " "
}
console.log(result);
}
reverseString(str);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:27:21.230",
"Id": "423585",
"Score": "0",
"body": "I think you want to keep the word order, of a string, but reverse each individual word in the string? Yes, the result of your code is `\"i ma tpircsavaj \"`."
}
] | [
{
"body": "<p>I would split this into two function, simply because they do different things:</p>\n\n<p>First a simple string reverser:</p>\n\n<pre><code>function reverseString(input)\n{\n var output = \"\";\n for(var i = input.length - 1; i >= 0; i--) {\n output += input[i];\n }\n return output;\n} \n</code></pre>\n\n<p>This is an easy function that everybody can understand. But we need to reverse words, so we make another function for that.</p>\n\n<pre><code>function reverseWords(input)\n{\n var word = \"\", output = \"\";\n for(var i = 0; i < input.length; i++) {\n if (input[i] == \" \") {\n output += reverseString(word) + \" \";\n word = \"\";\n }\n else {\n word += input[i];\n }\n }\n return output + reverseString(word);\n}\n</code></pre>\n\n<p>And that's it. Now this might not be the niftiest, or shortest, solution, but it is one that reasonably easy to understand, and you get two functions for the price of one.</p>\n\n<p>I had to correct this code after a comment from Blindman67 saying it didn't work for some cases.</p>\n\n<p>A shorter version is also possible:</p>\n\n<pre><code>function reverseWordsShorter(input)\n{\n var word = \"\", output = \"\";\n for(var i = input.length - 1; i >= 0; i--) {\n if (input[i] == \" \") {\n output = \" \" + word + output;\n word = \"\";\n }\n else {\n word += input[i];\n }\n }\n return word + output;\n}\n</code></pre>\n\n<p>Also notice that there's no erroneous space at the end anymore.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:13:38.327",
"Id": "423594",
"Score": "4",
"body": "And in two months, when someone discovers that emojis are destroyed when they are reversed, you only have a single small function that you need to repair instead of a large function. That's because the bug is clearly in the `reverseString` function since when you call `reverseString(\"\")`, the result is wrong without `reverseWords` being involved at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:19:19.850",
"Id": "423596",
"Score": "0",
"body": "@RolandIllig Never thought of that, but yes, you're right. :-) :) How did you make that emoji?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:29:40.533",
"Id": "423599",
"Score": "1",
"body": "With the on-screen keyboard of my tablet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:37:14.950",
"Id": "423601",
"Score": "0",
"body": "@RolandIllig My Windows 10 on-screen keyboard doesn't have emoji, but I can copy yours: Ah, I think this is simply an unicode character. Yes, I've got it!: "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T08:57:52.193",
"Id": "423603",
"Score": "2",
"body": "And then, one month later, another pedantic comes along and says that `\"AA\\u0308A\"` looks like `\"AÄA\"`, but its reversed version puts the dots on one of the outer characters. And there you go, implementing all the trickery in reversing a string. The Swift programming language has these built-in, by the way. Many other programming languages lack decent string reversing support, simply because it's complicated and not needed often."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:05:37.820",
"Id": "423604",
"Score": "0",
"body": "@RolandIllig PHP does indeed not have a multibyte string reverse function. But it is easy to [find one](https://kvz.io/blog/2012/10/09/reverse-a-multibyte-string-in-php/). Oh, sorry, this question was about Javascript... I sometimes get confused... well, quite often..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:06:30.503",
"Id": "423605",
"Score": "0",
"body": "In Swift all this works out of the box because [Character](https://developer.apple.com/documentation/swift/character) represents \"A single extended grapheme cluster that approximates a user-perceived character\", while most other programming languages see a string as a sequence of half-code-points. Note the careful \"approximates\" in the definition of the Character type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:16:46.167",
"Id": "423607",
"Score": "0",
"body": "The PHP function you found is as broken as anything else that naively tries to reverse a string. I only know the Swift implementation that gets this correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T10:25:16.077",
"Id": "423613",
"Score": "0",
"body": "@RolandIllig Python 3 also gets it correct in both `s[::-1]` and `\"\".join(reversed(s))` (I just went and checked)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T14:00:05.090",
"Id": "423630",
"Score": "1",
"body": "@Graipher I'd say Python 3 is as naive as almost all other programming languages: `print(\"\".join(reversed(\"AA\\u0308A\")))` puts the umlaut dots above the first A instead of the middle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T14:16:29.157",
"Id": "423632",
"Score": "0",
"body": "@RolandIllig Ah, I did not try the umlaut example, you are right. At least it gets the emojis right..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T15:52:34.847",
"Id": "423634",
"Score": "2",
"body": "Your answer returns reversed word positions with words unchanged. eg For `\"cat on mat\"` you return `\"mat on cat\"`.Should be `\"tac no tam\"`. Also use String iterator to handle unicode codepoints as single items. eg with string `const W = \"\\u{1F30F}\\u{1F30E}\\u{1F30D}\"` is the following is `true` `[...W].length === 3 && W.length === 6 && W.split(\"\").length === 6`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T18:29:34.563",
"Id": "423641",
"Score": "0",
"body": "@Blindman67 You're right: `\"the cat sat on the mat\"` returns `\"mat the on sat cat the\"`. Not good. I clearly didn't test it well enough. I corrected that problem, it now returns `\"eht tac tas no eht tam\"`. I'm not going to do full unicode, because I don't think that was part of the question."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:41:49.620",
"Id": "219295",
"ParentId": "219293",
"Score": "7"
}
},
{
"body": "<p>:-) Hello kallis,</p>\n\n<p>Could you please clarify why you don't want to put your string in an array ?</p>\n\n<p>Indeed, you could use a call back function with a map method on an array of words. The callback function would reverse each word, while keeping them at the same place in the sentence.</p>\n\n<pre><code>let str = \"I am Javascript\" ; \nconst arrStr = (string) => {\n const string2 = string.split(' ') ;\n return string2 ; \n}\nlet strInArray = arrStr(str) ; \n\nstrInArray = strInArray . map ( word => {\n let l = word.length ; \n let output = '' ; \n\n for (var i=l-1 ; i>=0 ; i--) {\n output += word[i] ; \n }\n return output ; \n} // End of callback function\n\n) ; // End of map method\n\nconsole.log(strInArray.join(' ')) ;`\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T17:56:05.500",
"Id": "423637",
"Score": "2",
"body": "Hello SylviE, welcome to Code Review Stack Exchange. The asker said, that most array functions are forbidden, so they probably can't use `Array.map()`. Also your choice of whitespace looks a bit odd. (Space around `.` and before `;` for example)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:55:48.257",
"Id": "423691",
"Score": "0",
"body": "@MEEthesetupwizard `map` isn't explicitly mentioned so it may be allowed. `split` is out though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T10:18:46.463",
"Id": "219301",
"ParentId": "219293",
"Score": "1"
}
},
{
"body": "<h2>Your function has two bugs</h2>\n\n<ol>\n<li><p>Adds an extra space to the end of the string. Eg for <code>\"the cat sat on the mat\"</code> you return <code>\"eht tac tas no eht tam \"</code>. The input string is 22 characters long and the returned string is 23 characters long.</p></li>\n<li><p>Related to the first. If the input string starts with a space the returned string removes it. Eg for <code>\" the cat sat on the mat\"</code> you return \"eht tac tas no eht tam \". </p></li>\n</ol>\n\n<hr>\n\n<h2>Code style</h2>\n\n<p>This section will cover source code style. These points are independent of the algorithms logic.</p>\n\n<ul>\n<li><p>You are missing the semicolon for the line inside the last <code>for</code> statement.</p></li>\n<li><p>Use <code>===</code> or <code>!==</code> rather than <code>==</code> or <code>!=</code></p></li>\n<li><p>You should never see <code>for (var i</code> If you use a <code>var</code> it should be declared at the top of the function or use <code>for (let i</code>.\nYou can also use <code>const</code> in <code>for...of</code> and <code>for...in</code> loops. Eg <code>for (const i of foo) {</code></p></li>\n<li><p>Don't scrunch up the code. Space between <code>) {</code>, <code>for (</code>, <code>if (</code>, <code>} else</code> and <code>else {</code>. Also operators should be separated by space. <code>i = strlen-1</code> should be <code>i = strlen - 1</code></p></li>\n<li><p>Use <code>const</code> for variables that do not change.</p>\n\n<ul>\n<li>The variable <code>strlen</code> does not change, thus it should be a constant.</li>\n<li>The variable <code>reverseStrArr</code> holds a reference to an array. That reference never changes so the variable should be declared as a constant. <code>const reverseStrArr = [];</code></li>\n</ul></li>\n<li><p>You should try to avoid adding a variable's type to its name. </p>\n\n<p>Names need only fit the context (have semantic meaning) of the scope/function they are declared in.</p>\n\n<ul>\n<li><code>myStr</code> better as <code>words</code> or <code>sentence</code></li>\n<li><code>strLen</code> better as just <code>length</code> or <code>charCount</code> or even just <code>len</code></li>\n<li><code>reverseStr</code> better as <code>reversed</code></li>\n<li><code>reverseStrArr</code> maybe <code>reversedWords</code></li>\n</ul></li>\n</ul>\n\n<h3>Loop variables</h3>\n\n<p>You don't need to declare a different variable of each loop. You need only do that if the loops are nested.</p>\n\n<pre><code>// Nested \nvar i,j;\nfor (i = 0; i < 10; i++) {\n for (j = 0; j < 10; j++) { /*...*/ }\n}\n//or \nfor (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) { /*...*/ }\n}\n\n// Sequential\nvar i;\nfor (i = 0; i < 10; i++) { /*...*/ }\nfor (i = 0; i < 10; i++) { /*...*/ }\n\n//or \nfor (let i = 0; i < 10; i++) { /*...*/ }\nfor (let i = 0; i < 10; i++) { /*...*/ }\n</code></pre>\n\n<hr>\n\n<h2>Algorithms Logic</h2>\n\n<p>This section looks at how your function solves the problem and possible ways to improve it.</p>\n\n<h3>Array as a stack</h3>\n\n<p>You are using the array <code>reverseStrArr</code> as a stack. An array becomes a stack only by the way you use it, it is an abstracted stack.</p>\n\n<p>Stacks are first in last out. You add items one at a time to the top of the stack, then you remove items one at a time from the top. </p>\n\n<p>The two array function <code>push()</code> and <code>pop()</code> provide a fast way to use JS arrays as a stack. </p>\n\n<p>As a stack the final loop where you create the <code>result</code> string can be simplified as</p>\n\n<pre><code>while (reversedWords.length) {\n result += \" \" + reversedWords.pop();\n}\n</code></pre>\n\n<p><sub><sup>(I think the rules will let us use <code>pop</code>.)</sup></sub></p>\n\n<h3>Unneeded steps</h3>\n\n<ol>\n<li><strong>The Last Word</strong></li>\n</ol>\n\n<p>In the second loop you have the statement <code>if(j + 1 == strlen) {</code> to push the last <code>result</code> to the array, then you clear <code>result</code>. </p>\n\n<p>If you remove that statement and its content you can have <code>result</code> hold the last word. In the following loop <code>result</code> already has the first word so you can add the space then word rather than word an space (trailing space bug)</p>\n\n<p>This fixes both bugs.</p>\n\n<ol start=\"2\">\n<li><strong>Repeated Logic</strong></li>\n</ol>\n\n<p>The first loop goes from last to first creating a reversed string, then the next loop indexes the string created from first to last. Its like writing backward so the when you read forward its backward... LOL</p>\n\n<p>The first loop is not needed. Just read the sentence string backward as you process it.</p>\n\n<hr>\n\n<h2>Rewrite</h2>\n\n<p>Putting all the above into your function we get a much simpler source and fix the bugs at the same time.</p>\n\n<pre><code>function reverseString(words) {\n const reversed = [], len = words.length;\n var result = \"\", i = len;\n while (i-- > 0) {\n if (words[i] == \" \") {\n reversed.push(result);\n result = \"\";\n } else { \n result += words[i];\n }\n }\n while (reversed.length) { \n result += \" \" + reversed.pop();\n }\n return result;\n}\n</code></pre>\n\n<h2>Alternative</h2>\n\n<p>The rewrite is still a little too complex .</p>\n\n<p>I used two loops to first create a stack of words and then use the stack to rebuild the sentence. </p>\n\n<p>You can do both within the one loop removing the need to use a stack.</p>\n\n<pre><code>function reverseWords(sentence) {\n var word = \"\", reversed = \"\", i = sentence.length;\n while (i-- > 0) {\n if (sentence[i] === \" \") {\n reversed = \" \" + word + reversed;\n word = \"\";\n } else { word += sentence[i] }\n }\n return word + reversed;\n}\n</code></pre>\n\n<hr>\n\n<h2>Surrogates, Codepoints, Emoji, modifiers, sequences </h2>\n\n<p>I see that in the <a href=\"https://codereview.stackexchange.com/a/219295/120556\">accepted answer</a> there are comments regarding Emoji (surrogate Unicode characters)</p>\n\n<p>In JavaScript strings are iteratable. The iterator handles all codepoint characters as single items. </p>\n\n<p><strong>Note:</strong> Single emoji can be created from one or <strong>more</strong> codepoints. eg ❤ is one emoji (on Chrome win10) but contains 6 codepoints or 8 Javascript string Unicode characters. See note at bottom of answer.</p>\n\n<p>Using iterators to step over strings and you need not worry about character sequences.</p>\n\n<p>Unfortunately iterators don't run backward. As we can not use many of the Array functions we are limited in how to solve the problem</p>\n\n<h3>Simplest solution.</h3>\n\n<p>To solve the problem of surrogate characters (within the restriction of the question) we can use a very quick hack that converts the input string to an array.</p>\n\n<pre><code>sentence = [...sentence]; // separates codepoints\n</code></pre>\n\n<p>The rest of the function remains unchanged because we used bracket notation to index the strings.</p>\n\n<h3>Example</h3>\n\n<p>Shows pass and failure modes when reversing surrogates via string iterator.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function reverseWords(sentence) {\n sentence = [...sentence];\n var word = \"\", reversed = \"\", i = sentence.length;\n while (i-- > 0) {\n if (sentence[i] === \" \") {\n reversed = \" \" + word + reversed;\n word = \"\";\n } else { word += sentence[i] }\n }\n return word + reversed;\n }\n \n \n const test1 = \" The cat on the mat \";\n const test2 = `♂️♀️ \\u200D❤\\u200D \\u{1F3C4}\\u200D\\u2642\\uFE0F`;\n\n log(test1);\n log(\"Reverse...\");\n log(reverseWords(test1));\n \n log(\"--------------------------------------\");\n log(\"Emoji modifiers and sequences may fail.\");\n\n log(`${test2} Reversed is...`);\n log(`${reverseWords(test2)}`);\n\n \n \n function log(textContent) { \n info.appendChild(Object.assign(document.createElement(\"div\"),{textContent}));\n }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#info {\nfont-size: large;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"info\"><code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Note:</strong>\nEmoji modifiers and sequences rely not only on how Javascript handles the string but also how the device OS interprets the string.</p>\n\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt\" rel=\"noreferrer\"><code>String.prototype.codePointAt()</code></a> to locate modifiers, sequences, gruping, etc</p>\n\n<p>For a full Emoji rundown <a href=\"https://unicode.org/reports/tr51/index.html\" rel=\"noreferrer\">Unicode Emoji Technical Standard</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T18:30:37.200",
"Id": "423642",
"Score": "0",
"body": "Nice answer. I'll upvote, and we'll see what happens."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T15:21:26.933",
"Id": "219310",
"ParentId": "219293",
"Score": "7"
}
},
{
"body": "<p>Generally in an interview setting, if you're asked this question, you'll be asked to find a solution by modifying the string in place.</p>\n\n<p>In this case, make sure to split out your code into separate functions, to make it easier for you to reason about.</p>\n\n<pre><code>function replaceAt(str, index, replacement) {\n return str.slice(0, index) + replacement + str.slice(index + 1)\n}\n\nfunction insertAt(str, start, end, value) {\n return str.slice(0, start) + value + str.slice(end + 1)\n}\n\nfunction swap(str, left, right) {\n let temp = str[right]\n str = replaceAt(str, right, str[left])\n str = replaceAt(str, left, temp)\n return str\n}\n\nfunction reverseString(str) {\n for (let i = 0; i < str.length / 2; i++) {\n str = swap(str, i, str.length - 1 - i)\n }\n\n return str\n}\n\nfunction reverseWords(str) {\n str = reverseString(str)\n\n let prev = 0\n let temp = ''\n for (let i = 0; i < str.length; i++) {\n if (str[i] === ' ') {\n str = insertAt(str, prev, i - 1, reverseString(temp))\n prev = i + 1\n temp = ''\n } else {\n temp += str[i]\n }\n }\n\n if (temp.length) {\n str = insertAt(str, prev, str.length - 1, reverseString(temp))\n }\n\n return str\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T15:41:15.210",
"Id": "466728",
"Score": "0",
"body": "It also happens to be a better coding practice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-26T14:23:10.877",
"Id": "237970",
"ParentId": "219293",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219295",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T07:05:35.663",
"Id": "219293",
"Score": "7",
"Tags": [
"javascript",
"strings"
],
"Title": "Reverse the word in a string with the same order in javascript"
} | 219293 |
<p>I implemented a basic <a href="https://en.wikipedia.org/wiki/Binary_heap" rel="nofollow noreferrer">binary heap</a> in Common Lisp to learn programming using the CLOS. It is quite neat and self-contained, the core of the program is about 100 SLOC. The whole repository <a href="https://github.com/thomashoullier/cl-binheap/tree/master" rel="nofollow noreferrer">can be found here</a>.</p>
<p>The crux of the program is <code>binheap.lisp</code>:</p>
<pre><code>;;;; Binary heap implementation.
;;;; We implemented this structure using the excellent article at:
;;;; https://en.wikipedia.org/wiki/Binary_heap
;;;; The binary heap is implemented as a CLOS class.
;;;; Please note that the vector you provide to the heap object is used in-place
;;;; throughout the life of the heap. It is up to you to make copies and ensure
;;;; the vector is not modified externally.
(in-package :binhp)
(defclass heap ()
((vec
:documentation "Resizeable array to store the implicit Binary Heap."
:initarg :vec
:initform (error "class heap: Please provide a vector")
:accessor vec)
(test
:documentation "Total order function. The heap enforces:
{funcall totorder parent child} throughout the binary tree."
:initarg :test
:initform (error "class heap: Please provide a total order relation.")
:accessor test)))
(defun make-heap (vec test)
"Heap constructor.
I: vec: Vector to back the implicit binary tree structure. Works in place.
Must have a fill-pointer.
test: The total order to enforce throughout the heap.
[funcall test parent child] is true throughout the tree."
(assert (array-has-fill-pointer-p vec))
(assert (typep test 'function))
(let ((hp (make-instance 'heap :vec vec :test test)))
(build hp)
hp))
;;; Main
(defmethod build ((tree heap))
"Initial building of the binary heap from the input vector of data.
Sub-method."
;; We work our way up the tree calling the down-heap method on each parent
;; node.
;; Parent nodes are the ones from 0 to floor{n-2 / 2} included.
(loop for ind from (floor (/ (- (length (vec tree)) 2) 2)) downto 0 do
(down-heap tree ind)))
(defmethod insert ((tree heap) newkey)
"Push a new element to the heap.
I: * Heap instance.
* New element."
(with-slots ((arr vec)
(test test)) tree
;; Inserts a new element at the end of arr and performs a up-heap.
;; Last element of the array is guaranteed to be a leaf of the tree.
(vector-push-extend newkey arr)
;; Compare the new element with its parent node.
;; * If order is respected or if we've reached the root of the tree
;; then return.
;; * Else swap. And repeat.
(let* ((ind (1- (length arr)))
(parind (floor (/ (1- ind) 2))))
(loop while (and (not (= ind 0))
(not (funcall test (aref arr parind)
(aref arr ind)))) do
(rotatef (aref arr parind) (aref arr ind))
(setf ind parind)
(setf parind (floor (/ (1- ind) 2)))))))
(defmethod down-heap ((tree heap) ind)
"Perform the down-heap operation. Move the parent node at 'ind' downwards
until it settles in a suitable position. Sub-method, not exposed to user."
;; Compare the current key with its two children. Return if order is respected
;; else swap the current key with the child that respects the total order with
;; the other child. Also return if we have reached a leaf of the tree.
;; Nodes at an index starting at ceil{n-2 / 2} are leafs.
(with-slots ((arr vec)
(test test)) tree
(let* ((maxind (1- (length arr)))
(leaf-limit (floor (/ (1- maxind) 2)))
(left-child (+ (* 2 ind) 1))
(right-child (min (1+ left-child) maxind)))
(loop while
(and
;; Order of tests matters here!
(not (> ind leaf-limit))
(not (and (funcall test (aref arr ind) (aref arr left-child))
(funcall test (aref arr ind) (aref arr right-child)))))
do
;; Find out the right child to swap with and swap.
(if (funcall test (aref arr left-child) (aref arr right-child))
(progn (rotatef (aref arr ind) (aref arr left-child))
(setf ind left-child))
(progn (rotatef (aref arr ind) (aref arr right-child))
(setf ind right-child)))
(setf left-child (+ (* 2 ind) 1))
(setf right-child (min (1+ left-child) maxind))))))
(defmethod extract ((tree heap))
"Pop the root element from the heap. Rearranges the tree afterwards.
I: Heap instance.
O: Root element."
(with-slots ((arr vec)) tree
(let ((root (aref arr 0)))
;; replace the root with the last leaf
;; resize vector
;; down-heap the new root.
(setf (aref arr 0) (aref arr (1- (length arr))))
(vector-pop arr)
(down-heap tree 0)
root)))
(defmethod print-tree ((tree heap))
"Print the whole tree in a very basic formatting, level by level
and left to right."
(with-slots ((arr vec)) tree
(let* ((n (length arr))
(h (floor (log n 2))))
;; The heap is already ordered by level. And each level is in the right
;; order.
(loop for level from 0 upto h do
(loop for ind from (1- (expt 2 level))
below (1- (expt 2 (1+ level))) do
(if (< ind n)
(format t "~a " (aref arr ind))))
(terpri t)))))
(defmethod size ((tree heap))
(length (vec tree)))
</code></pre>
<p>And you can see some examples in <code>example.lisp</code>:</p>
<pre><code>;;;; Examples illustrating the use of the binary heap implementation.
;;; Loading the library, adjust the paths to your own directories.
;;; Can also be done by loading the source files directly.
(if (not (member #p"~/portacle/projects/"
asdf:*central-registry*))
(push #p"~/portacle/projects/"
asdf:*central-registry*))
(ql:quickload :binheap)
;;; Max-heaps
;; Let's build a heap of integers ordered from biggest to smallest.
(defparameter *arr* (make-array 6 :fill-pointer 6
:initial-contents (list 3 4 1 2 5 6)))
(defparameter *heap* (binhp:make-heap *arr* #'>=))
;; #'>= is the relation enforced throughout the heap between every parent node
;; and its children.
(binhp:print-tree *heap*)
;; =>
;; 6
;; 5 3
;; 2 4 1
;; Alright, this is a nice heap.
;; You can insert elements in it:
(binhp:insert *heap* 3.5)
(binhp:print-tree *heap*)
;; =>
;; 6
;; 5 3.5
;; 2 4 1 3
;; The new element fits in the heap.
;; You can pop elements to get the successive biggest of the heap:
(loop for it from 0 below (length *arr*) do
(format t "~a " (binhp:extract *heap*)))
(terpri t)
;; => 6 5 4 3.5 3 2 1
;;; The same goes for Min-heaps, just replace #'>= with #'<=.
;;; You can define any relation that is a total order in 'test.
;;; Alphabetical heap.
;; The heap implementation works for any element types and any total order.
;; Let's put some strings in an alphabetical order heap.
(defparameter *arr*
(make-array 5
:fill-pointer 5
:initial-contents (list "Pierre" "Jacques" "Paul" "Jean" "Luc")))
(defparameter *heap* (binhp:make-heap *arr* #'string-lessp))
(binhp:print-tree *heap*)
;; =>
;; Jacques
;; Jean Paul
;; Pierre Luc
(loop for it from 0 below (length *arr*) do
(format t "~a " (binhp:extract *heap*)))
(terpri t)
;; => Jacques Jean Luc Paul Pierre
</code></pre>
<p>As well as some tests in <code>test.lisp</code>:</p>
<pre><code>;;;; Simple tests for validating binheap.
;;; Loading the library, adjust the paths to your own directories.
(if (not (member #p"~/portacle/projects/"
asdf:*central-registry*))
(push #p"~/portacle/projects/"
asdf:*central-registry*))
(ql:quickload :binheap)
;;; Validation
(format t "Creating empty or small binary heaps:...")
(dotimes (it 10 t)
(let ((arr (make-array it :fill-pointer it)))
(binhp:make-heap arr #'>=)))
(format t " OK") (terpri t)
(format t "Simple heaps and operations:...")
(loop for test in (list #'>= #'<=) do
(loop for nelem from 10 upto 50 do
(let ((arr (make-array nelem :fill-pointer nelem))
(arrval (make-array nelem))
(hp nil))
(loop for ind from 0 below nelem do
(setf (aref arr ind) (random 100))
(setf (aref arrval ind) (aref arr ind)))
(setf hp (binhp:make-heap arr test))
;; Now pop all the elements and verify that we get the right order
(sort arrval test)
(loop for ind from 0 below nelem do
(assert (= (binhp:extract hp) (aref arrval ind))))
;; Reinsert shuffled elements.
(loop for ind from 0 below nelem do
(rotatef (aref arrval ind) (aref arrval (random nelem))))
(loop for elem across arrval do
(binhp:insert hp elem))
;; Now repop everything and check order.
(sort arrval test)
(loop for ind from 0 below nelem do
(assert (= (binhp:extract hp) (aref arrval ind)))))))
(format t "OK") (terpri t)
;;; Performance
(terpri t) (format t "Performance:") (terpri t)
(loop for nelem in (list 100 10000 1000000) do
(let ((arr (make-array nelem :element-type 'double-float
:fill-pointer nelem
:initial-element 0d0))
(hp nil))
(loop for ind from 0 below nelem do
(setf (aref arr ind) (random 100d0)))
(format t "Building a max-heap of ~a double-floats: " nelem) (terpri t)
(time (setf hp (binhp:make-heap arr #'>=)))
(format t "Popping a max-heap of ~a double-floats: " nelem) (terpri t)
(time (dotimes (it nelem t) (binhp:extract hp)))
(format t "Reinserting ~a double-floats:" nelem) (terpri t)
(time (dotimes (it nelem t) (binhp:insert hp (random 100d0))))))
</code></pre>
<h2>Review</h2>
<ul>
<li>I am mostly happy with <code>binheap.lisp</code> (but should I be?). Are there any obvious shortcuts that could be used to make the code more elegant/efficient?</li>
<li>The tests are quite awkward. I validate the library for random cases and do a few performance benchmarks for <code>double-float</code> types. Is there any package that you could recommend for the same kind of tests but in a less awkward way to program and read?</li>
</ul>
<p>All this testing might be overkill for such a simple and small program, but my goal is to have a self-contained example of a typical, very <em>neat</em> Common-Lisp project. So by all means be nitpicky please.</p>
| [] | [
{
"body": "<h2>Packaging</h2>\n\n<ul>\n<li>The project and repository is called <code>cl-binheap</code>, while the ASDF\nsystem is called <code>binheap</code> - it's a good idea for those to match,\nmostly due to UX: I'll try loading the repository name first all the\ntime.</li>\n<li>Worse is the package name <code>binhp</code>. Now we have <em>three</em> names instead\nof one. Simply pick one of them and go with it (not <code>binhp</code> though,\nwhy's leaving out two vowels make things better?).</li>\n<li>Depending on who you'd like to use the code,\n<a href=\"https://softwareengineering.stackexchange.com/questions/147111/what-is-wrong-with-the-unlicense\">the Unlicense might not be so advisable</a>.</li>\n<li>The README.md looks okayish, I'd rather also see an API reference\nwith some more details though.</li>\n</ul>\n\n<h2>Code</h2>\n\n<ul>\n<li>The tests use <code>assert</code>, instead I'd recommend one of the existing\nframeworks, possibly also linking it into ASDF so that\n<code>asdf:test-system</code> works.</li>\n<li>Some of the source files correctly have <code>in-package</code>, some don't - I'd\nsuggest always specifying which package to use, even (or especially)\nif it's example code.</li>\n<li><code>example.lisp</code> doesn't work for me on CCL (I'd also suggest testing\ncode with at least two or more implementations if you want it to be\nwidely used): <code>#(6 5 3 2 4 1) is not an adjustable array.</code> Adding\n<code>:adjustable t</code> to the definition of <code>*arr*</code> fixes that.</li>\n<li><code>binheap.lisp</code> has some trailing whitespace and some tabs. Consider\n<kbd>M-x delete-trailing-whitespace</kbd> and\n<kbd>M-x untabify</kbd>.</li>\n<li><code>(floor (/ x y))</code> could be simplified to\n<a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/f_floorc.htm#floor\" rel=\"nofollow noreferrer\"><code>(floor x y)</code></a>\nhere (note the second return value is gonna be different though).</li>\n<li><code>(not (= ind 0))</code> will hopefully be optimised. If not, however, <code>(not\n(eql ind 0))</code> might be better (of course <code>(/= ind 0)</code> also exists, but\nstill does numeric comparison).</li>\n<li>I'd suggest adding a <code>key</code> to make the container more generic / match\nthe standard sequence operators. This helps immensely when adding\nsome objects and then using one of the attributes for comparison; it\ncomposes better than a single <code>test</code> argument.</li>\n<li>Lastly, CLOS is great and all, but strictly speaking all of the\nmethods could be functions and therefore be a bit quicker. Unless of\ncourse you have plans to add more containers with the same interface.\nConsider also annotating everything with types and looking at what the\ncompiler (well, SBCL only really) will tell you about problems when\ncompiling with higher optimisation settings\n(<code>(declaim (optimize ...))</code>). However, I'd say that unless you're\nvery certain <em>do not</em> however put <code>(declare (optimize ...))</code> into the\nlibrary code, it's easy to get that wrong.</li>\n<li>Don't use <code>assert</code> if the error isn't correctable by changing the\nvalue interactively. Like in <code>make-heap</code>, both of those should be\nregular errors: Retrying won't fix the problem (that's a common\nrestart established with <code>assert</code>) and changing <code>vec</code> or <code>test</code> isn't\nsomething you'd do interactively ... I think. So, <code>check-type</code> and\n<code>error</code> would be the way to go here.</li>\n<li>For randomised testing there's AFAIK nothing like a standard package,\nlook for Quickcheck clones or \"random testing common lisp\" probably.</li>\n</ul>\n\n<p>Edit: Oh I just saw you said to be nitpicky. Alright then:</p>\n\n<ul>\n<li>It's \"Common Lisp\", no dash :)</li>\n<li><code>ind</code>, <code>*arr*</code>, <code>arr</code>, <code>arrval</code>, etc. aren't great names. Especially\nin function signatures consider matching what the standard uses for\nsimilar purposes. I'm betting that it's <code>index</code> and <code>array</code>\nrespectively. Common Lisp has a tendency to have long names (for\ngood!) and I'm (nitpicky) of the opinion that it's good style to match\nthat (as much as possible).</li>\n<li><code>loop</code> should be replaced by\n<a href=\"https://common-lisp.net/project/iterate/\" rel=\"nofollow noreferrer\"><code>iterate</code></a> because it has\nmore parentheses. Not kidding, it simply looks better.</li>\n<li>The docstrings are suboptimal and again should match an existing\nstyle. <code>I: * Heap instance...</code> I haven't seen before and it doesn't\neven mention which parameter (name) it describes. Take\n<a href=\"https://edicl.github.io/drakma/\" rel=\"nofollow noreferrer\">some exemplary</a>\n<a href=\"http://quickdocs.org/drakma/api\" rel=\"nofollow noreferrer\">documentation</a> as a guideline\nperhaps.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T15:10:44.680",
"Id": "447140",
"Score": "0",
"body": "Thank you very much for this very detailed answer. I have many things to look into at many levels now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-27T19:02:47.567",
"Id": "447164",
"Score": "0",
"body": "Hope it helps; btw. you can always post again here with a follow-up if you want too."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T23:54:01.800",
"Id": "229672",
"ParentId": "219298",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "229672",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T09:17:08.563",
"Id": "219298",
"Score": "7",
"Tags": [
"unit-testing",
"heap",
"common-lisp"
],
"Title": "Binary Heap implementation in Common Lisp and tests"
} | 219298 |
<p>The task is to compare students homework SQL files with mentors SQL files.</p>
<p>I've written two functions, which return a two-dimensional array (1st elements are an absolute path, 2nd are a relative). </p>
<p>Then I'm going to compare the relative path of students and mentors and execute SQL files (finding using absolute path) if these values are equal </p>
<p>Is there a more elegant implementation?</p>
<p>The folder structure of mentors dir:</p>
<pre><code>Homework (folder)
├ 1 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ 2 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ n (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
</code></pre>
<p>The folder structure of students dir:</p>
<pre><code>├Students Homework (folder)
├Student1(folder)
├ 1 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ 2 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ n (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├Student2(folder)
├ 1 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ 2 (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
├ n (folder)
| ├ 1.sql
| ├ 2.sql
| └ n.sql
</code></pre>
<p>"Mentors" function:</p>
<pre class="lang-py prettyprint-override"><code>def find_mentors_sql(config):
mentors_sql_abs = []
mentors_sql_rel = []
for dirpath, subdirs, files in walk(config["MAIN_DIR"] + '\\Homework'):
mentors_sql_abs.extend(path.join(dirpath, x) for x in files if x.endswith(".sql"))
mentors_sql_rel.extend(path.join(path.basename(dirpath), x) for x in files if x.endswith(".sql"))
mentors_sql = [[0] * 2 for i in range(len(mentors_sql_abs))]
iter = 0
for _ in mentors_sql_abs:
mentors_sql[iter][0] = mentors_sql_abs[iter]
iter += 1
iter1 = 0
for _ in mentors_sql_rel:
mentors_sql[iter1][1] = mentors_sql_rel[iter1]
iter1 += 1
return mentors_sql
</code></pre>
<p>"Students" function (the logic is similar to the previous one:</p>
<pre class="lang-py prettyprint-override"><code>def find_students_sql(config):
students_sql_abs = []
students_sql_rel = []
for dirpath, subdirs, files in walk(config["MAIN_DIR"] + '\\Students Homework'):
students_sql_abs.extend(path.join(dirpath, x) for x in files if x.endswith(".sql"))
students_sql_rel.extend(path.join(path.basename(dirpath), x) for x in files if x.endswith(".sql"))
students_sql = [[0] * 2 for i in range(len(students_sql_abs))]
iter = 0
for _ in students_sql:
students_sql[iter][0] = students_sql_abs[iter]
iter += 1
iter1 = 0
for _ in students_sql:
students_sql[iter1][1] = students_sql_rel[iter1]
iter1 += 1
return students_sql
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T18:22:30.987",
"Id": "423640",
"Score": "0",
"body": "Getting close to perfect there... Quick tips; _`for _ in <iterable>`_ could do without `iter = 0` stuff if ya use `enumerate()`, eg. _`for i, thing in enumerate(<iterable>)`_... though why you're pre-building an empty nested list is a little beyond me, I'd use a `list` of `tuples` or a `dict`ionary... Looks like the `find_mentors_sql` and `find_students_sql` could be merged into one function, and I think _`walk_path = os.path.join(p1, p2)`_ you'll find more portable than `walk`ing `p1 + '\\\\p2'`... finally for this comment, those one-liner `for` loops with `extend` hurt the code's readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T20:17:14.597",
"Id": "423652",
"Score": "2",
"body": "@S0AndS0 Comments are for seeking clarification to the question, and may be deleted. Please put all suggestions for improvements in answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:35:21.287",
"Id": "423656",
"Score": "0",
"body": "Wups @200_success, I'll attempt to do better in the future, for now my attempt at an answer will go into trying to address _`\"Is there a more elegant implementation?\"`_, because I spent a little more time with the code."
}
] | [
{
"body": "<ol>\n<li><p>It's recommended to use <code>enumerate</code> rather than <code>iter</code> (renamed <code>i</code>), <code>_</code> and indexing.</p>\n\n<pre><code>for i, abs_path in enemerate(mentors_sql_abs):\n mentors_sql[i][0] = abs_path\n</code></pre></li>\n<li><p>It's better to use <code>zip</code> rather than build <code>mentors_sql</code> manually.</p></li>\n<li>Your function could further be simplified if you don't extend <code>mentors_sql_*</code> and just <code>yield</code> the values.</li>\n<li>Please only use one string delimiter, either <code>'</code> or <code>\"</code>.</li>\n<li><code>x</code> is a pretty bad variable name, I would use <code>file</code>. Even for a comprehension it's pretty poor, as x isn't short hand for anything.</li>\n<li>The only difference between the two functions as you walk different paths. And so you can change your input to account for this, and use one function.</li>\n<li>I don't see the need for returning both relative and absolute paths, and so won't comment on it too much. You may want to return one and convert when needed.</li>\n</ol>\n\n<pre><code>def find_sql(path):\n for dirpath, subdirs, files in walk(path):\n for file in files:\n if file.endswith('.sql'):\n yield (\n path.join(dirpath, file),\n path.join(path.basename(dirpath), file)\n )\n\n\nmentors = find_sql(config[\"MAIN_DIR\"] + '\\\\Homework')\nstudents = find_sql(config[\"MAIN_DIR\"] + '\\\\Students Homework')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T11:53:18.070",
"Id": "423717",
"Score": "0",
"body": "`iter` is also a built-in being shadowed here (although you don't use it in the end)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T12:00:45.547",
"Id": "423720",
"Score": "0",
"body": "I agree in general. But when actually iterating over something, calling the iterating variable `iter` can be quite confusing IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:09:57.010",
"Id": "467664",
"Score": "0",
"body": "@Graipher I agree `iter` is a terrible variable name. It doesn't matter if it's it's shadowing a builtin or not, it's just bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:16:10.607",
"Id": "467667",
"Score": "0",
"body": "Working through a back log of about a year of comments? In any case, I agree, although I'm also not a big fan of my usual choice of `it`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-06T00:19:36.710",
"Id": "467668",
"Score": "0",
"body": "@Graipher Something like that yeah. Hadn't seen you around either so had to give you a ping ;P Hmm, I've seen `it` for iterator/iterable, I think `i` is ok but not great - at least it's kinda a standard."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:10:29.093",
"Id": "219322",
"ParentId": "219302",
"Score": "2"
}
},
{
"body": "<p>Okay I spent just a little while with your code @Valentyn, and I think it is mostly unharmed...</p>\n\n<h3><code>sql_utils/__init__.py</code></h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\n\ndef walked_sql_paths(config, sub_dir):\n \"\"\"\n Generates `tuple` of absolute and relative file paths\n\n - `config` should contain a 'MAIN_DIR' key with a value similar to\n - `/home/Mentor`\n - `/home/StudentName`\n - `sub_dir` should contain a string such as `Homework`\n \"\"\"\n ## ... I am guessing that ya might be doing something\n ## else with the `config` object, if this is not\n ## the case, then this could be simplified to\n ## only taking a `path` argument instead.\n target_dir = os.path.join(config['MAIN_DIR'], sub_dir)\n\n for dirpath, subdirs, files in walk(target_dir):\n for item in files:\n if not item.endswith('.sql'):\n continue\n\n sql_abs = os.path.join(dirpath, item)\n sql_rel = os.path.basename(dirpath)\n yield sql_abs, sql_rel\n</code></pre>\n\n<blockquote>\n <p>That <em>stuff</em> between <code>\"\"\"</code> (triple quotes) be a <a href=\"https://en.wikipedia.org/wiki/Docstring\" rel=\"nofollow noreferrer\"><em><code>\"docstring\"</code></em></a>, and is accessable via either <code>help(walked_sql_paths)</code> or <code>print(walked_sql_paths.__doc__)</code>. The <a href=\"https://en.wikipedia.org/wiki/Dunder\" rel=\"nofollow noreferrer\"><em><code>\"dunder\"</code></em></a> or <a href=\"https://rszalski.github.io/magicmethods/\" rel=\"nofollow noreferrer\"><em><code>\"Magic Method\"</code></em></a> stuff I'll not cover here as that's a whole <em>'nother-can-o-worms</em>. What is important is that accessible documentation is something that Python allows for, while code that doesn't require it is something to strive for.</p>\n</blockquote>\n\n<p>I'm using <a href=\"https://stackoverflow.com/a/231855/2632107\"><em><code>yield</code></em></a> in the above <code>for</code> loop so that it yields partial results to whatever calls <code>next()</code> or <code>__next__()</code> methods (called by <code>for</code> loops and other processes implicitly), <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\"><code>generators</code></a> are a <em>cheep</em> way of optimizing code as well as ensuring that users experience less <em>herky jerky</em> loading between results; even if things are taking awhile this'll usually <em>feel</em> faster in other-words.</p>\n\n<p>The assignments of <code>sql_abs</code> and <code>sql_rel</code> are first for readability, and second for making it easy to later do something like <em><code>yield sql_rel, sql_abs</code></em> instead. Otherwise there's little reason to prefer it over the answer posted by <a href=\"https://codereview.stackexchange.com/a/219322/197446\">@Peilonrayz</a>.</p>\n\n<p>Here's one way of using the above modified code...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from sql_utils import walked_sql_paths\n\n\n## ... setting of `mentors` and `students` `_config` objects\n## and other stuff I am guessing will go here...\n\n\nstudents_paths = walked_sql_paths(config = students_config,\n sub_dir = 'Students Homework')\n\nmentors_paths = walked_sql_paths(config = mentors_config,\n sub_dir = 'Homework')\n\n\nfor s_paths, m_paths in zip(students_paths, mentors_paths):\n if not s_paths[0] == m_paths[0]:\n print(\"Warning, continuing past -> {s_rel_path} and {m_rel_path} miss-match!\".format(\n s_rel_path = s_path[0],\n m_rel_path = m_path[0]))\n continue\n\n print(\"Time to compare -> Mentors {m_abs_path} with Students {s_abs_path}\".format(\n m_abs_path = m_paths[1],\n s_abs_path = s_paths[1]))\n</code></pre>\n\n<p>I'm using <a href=\"https://docs.python.org/3.3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><em><code>zip</code></em></a> to zip-up the two generators in the above <code>for</code> loop because it's a built-in that seems to do what ya want.</p>\n\n<p>Hopefully none of this is <em>mind blowing</em> because like I stated in your question's comments @Valentyn, you where really close to something that I'd not be able to add to.</p>\n\n<hr>\n\n<p>Looking at the folder structure a bit closer, it looks like things'll could get just a bit <em>fancier</em> with the loops. What's your preference on ordering?</p>\n\n<p>My thoughts would be to iterate over <em><code>Students_Homework/</code></em> of students and then <em><code>zip</code>-up</em> between sub-folders, in which case it maybe possible to <em>cache</em> the Mentor's folders on the first pass. However, that would not be nice to scale or if there's lots of sub-directories... Another thought would be to iterate over the Mentor's <code>1</code>-<code>n</code> folders and <code>zip</code>-up on each student in turn. Feel free to comment with a preference as to which might be more helpful.</p>\n\n<hr>\n\n<p>Thoughts on the future, using <code>try</code>/<code>except</code> you can code for cases where, <em><code>Student3</code></em> didn't turn in the <em><code>5.sql</code></em> file espected in <em><code>2</code>'s folder</em>, so here's some <em>skeleton-code</em> that'll hopefully get ya a little closer to fault tolerantness...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def safety_zipper(*iters, search_strs):\n \"\"\"\n Allows for doing something _clever_ where things could have gone painfully wrong\n\n - `iters`, `list` of iterables that each output `tuple`s of length two `(rel_path, abs_path)`\n - `search_strs`, `list` of `str`ings to search for matches on `rel_path`\n\n Yields `list` of `tuple`s `(rel_path, abs_path)`\n \"\"\"\n for search_str in search_strs:\n partial_results = []\n for thing in iters:\n try:\n path_tuple = thing.next()\n except (GeneratorExit, StopIteration):\n ## Note passing can be dangerous, I only do it\n ## because the parent loop will exit, eventually\n print(\"Warning {abs_path} miss-match with {search_str}\".format(\n abs_path = path_tuple[1],\n search_str = search_str))\n pass\n else: ## No error so do things with next thing\n ## Uncomment the following if useful\n # abs_path = path_tuple[1]\n rel_path = path_tuple[0]\n if search_str == rel_path:\n partial_results.append(path_tuple)\n continue\n\n ## Deal with miss-matches in a clever way here, such\n ## as if a student is late to turn in an assignment.\n\n finally:\n ## Finally runs regardless, well so long as another\n ## exception is not raised before reaching here.\n ## Only included for completeness and in-case ya\n ## wanted to do something fancy here too.\n pass\n\n yield partial_results\n</code></pre>\n\n<p>... I'll warn that the above is not complete, but essentially it'll allow for catching cases where <em><code>Student</code></em> directories or files do not match those of the <em><code>Mentor</code>'s</em> file paths. It may have to be <em>stacked</em> to be able to check for differences in both directories and files, and pre-loading <code>search_strs</code> list would either require foreknowledge or pre-parsing a chunk of <em><code>Mentor</code>'s</em> file paths to populate.</p>\n\n<p>But whatever's <em>downstream</em> will have a much cleaner input and require much less edge-case detection.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:31:33.127",
"Id": "219324",
"ParentId": "219302",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T10:42:03.733",
"Id": "219302",
"Score": "5",
"Tags": [
"python",
"file-system"
],
"Title": "Comparing each item from dir with each item from another dir"
} | 219302 |
<p>I am writing a function to decode Argon2 hashed string to extract parameters. I need to handle many decode errors, and handle those errors lead to write many repeating <code>if err == nil</code> check code. Is there a better way to do this kind of check?</p>
<p>The encodedHash string follows the format, separated by <code>$</code></p>
<pre><code>"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s"
</code></pre>
<p>so an example string looks like</p>
<pre><code>$argon2id$v=19$m=65536,t=3,p=4$ruDgwQK24h0wGXI87+lVWAbHmgNidUNPVSTdSloOlfM$py20HR7L4K6LllGsZNDbkrbh89x2tIF8JCIG0DAaoi8
</code></pre>
<p>What the decode function do is convert the string into this struct</p>
<pre><code>type Argon2Params struct {
Memory uint32
Time uint32
Threads uint8
SaltLength uint32
KeyLength uint32
}
</code></pre>
<p>Here is the decode function, I need to do a serious check during the decoding process. Every filed need to be checked to make sure no error rises.</p>
<pre><code>func decodeHash(encodedHash string) (p *Params, salt, hash []byte, err error) {
fileds := strings.Split(encodedHash, "$")
if len(fileds) != 6 {
return nil, nil, nil, errors.New("The encoded hash is not in the correct format")
}
var version int
// error check
if _, err = fmt.Sscanf(fileds[2], "v=%d", &version); err != nil {
return
}
// error check
if version != argon2.Version {
return nil, nil, nil, errors.New("Argon2 version not match")
}
p = &Params{}
_, err = fmt.Sscanf(fileds[3], "m=%d,t=%d,p=%d", &p.memory, &p.time, &p.threads)
// error check
if err != nil {
return
}
salt, p.saltLength, err = decodeBase64WithLength(fileds[4])
// error check
if err != nil {
return
}
// error check
hash, p.keyLength, err = decodeBase64WithLength(fileds[5])
return
}
// a helper function
func decodeBase64WithLength(encodeString string) (str []byte, length uint32, err error) {
str, err = base64.RawStdEncoding.DecodeString(encodeString)
length = uint32(len(str))
return
}
</code></pre>
| [] | [
{
"body": "<p>Because you use named parameters, the error checking can indeed be simplified.</p>\n\n<p>While you critique the use of <code>if err != nil</code>, I enjoy the consistent error handling, and prefer it to the concepts used in many other languages.</p>\n\n<h2>Returning errors</h2>\n\n<p>Rather than explicitly returning values, such as</p>\n\n<pre><code>return nil, nil, nil, errors.New(\"...\")\n</code></pre>\n\n<p>You can instead set the named return value <code>err</code>:</p>\n\n<pre><code>if len(fields) != 6 {\n err = errors.New(\"incorrect hash format\")\n return\n}\n</code></pre>\n\n<p>This does not set the other values to <code>nil</code>, and that shouldn't matter. In terms of consuming this API, it would be bad practice to use any other return values if <code>err</code> is not <code>nil</code>. It would be the equivalent in C of using the return value of <code>strtoul()</code> without checking <code>errno</code>.</p>\n\n<p>Having the comment <code>// error check</code> each time is too verbose.</p>\n\n<h2>Misspelling</h2>\n\n<p>The variable <code>fileds</code> is misspelled, it should be <code>fields</code>.</p>\n\n<h2>Helper function</h2>\n\n<p>Using named return values in your helper function is superfluous. You can easily return those variables directly.</p>\n\n<pre><code>func decodeBase64WithLength(encStr string) ([]byte, uint32, error) {\n s, err := base64.RawStdEncoding.DecodeString(encStr)\n return s, uint32(len(s)), err\n}\n</code></pre>\n\n<p>But now that the function has been cleaned up, it's easy to see that it really isn't needed. If this is the only place you use the function, then doing something small twice doesn't justify a helper function in my opinion.</p>\n\n<h2><code>Params</code></h2>\n\n<p>You reference <code>Argon2Params</code> as <code>Params</code>, and both are exported types, but you refer to its members as unexported types. I'll assume it's exported, and capitalize the member variables.</p>\n\n<h2>Conclusion</h2>\n\n<p>Here is the code I ended up with:</p>\n\n<pre><code>package main\n\nimport (\n \"encoding/base64\"\n \"errors\"\n \"fmt\"\n \"strings\"\n\n \"golang.org/x/crypto/argon2\"\n)\n\n// Argon2Params are ...\ntype Argon2Params struct {\n Memory uint32\n Time uint32\n Threads uint8\n SaltLength uint32\n KeyLength uint32\n}\n\nfunc decodeHash(encodedHash string) (p *Argon2Params, salt, hash []byte, err error) {\n fields := strings.Split(encodedHash, \"$\")\n\n if len(fields) != 6 {\n err = errors.New(\"incorrect hash format\")\n return\n }\n\n var version int\n\n if _, err = fmt.Sscanf(fields[2], \"v=%d\", &version); err != nil {\n return\n }\n\n if version != argon2.Version {\n err = errors.New(\"argon2 version mismatch\")\n return\n }\n\n p = &Argon2Params{}\n\n if _, err = fmt.Sscanf(fields[3], \"m=%d,t=%d,p=%d\", &p.Memory, &p.Time,\n &p.Threads); err != nil {\n return\n }\n\n salt, err = base64.RawStdEncoding.DecodeString(fields[4])\n p.SaltLength = uint32(len(salt))\n\n if err != nil {\n return\n }\n\n hash, err = base64.RawStdEncoding.DecodeString(fields[5])\n p.KeyLength = uint32(len(hash))\n\n return\n}\n\nfunc main() {\n decodeHash(\"$argon2id$v=19$m=65536,t=3,p=4$ruDgwQK24h0wGXI87+lVWAbHmgNidUNPVSTdSloOlfM$py20HR7L4K6LllGsZNDbkrbh89x2tIF8JCIG0DAaoi8\")\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T05:56:39.837",
"Id": "423952",
"Score": "1",
"body": "Wow! such a detailed answer! Yes the `Params` is same as `Argon2Params `."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T05:02:14.547",
"Id": "219476",
"ParentId": "219308",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219476",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T14:14:56.850",
"Id": "219308",
"Score": "1",
"Tags": [
"error-handling",
"go"
],
"Title": "Decode Argon2 parameters and handling decode errors"
} | 219308 |
<p>I created this code</p>
<pre><code>@Service
public class TestService {
@Autowired
private Test1Repository test1Repository;
@Autowired
private Test2Repository test2Repository;
@Autowired
private Test1Mapper test1Mapper;
@Autowired
private Test2Mapper test2Mapper;
public void test(Map<String, Object> body){
if("test1".equals(body.get("type"))){
Test1 test1 = test1Mapper.mapToTest1(body);
// logic here
test1Repository.save(test1);
} else if("test2".equals(body.get("type"))){
Test2 test2 = test2Mapper.mapToTest2(body);
//logic here
test2Repository.save(test2);
}
}
}
</code></pre>
<p>I think it's not so good to create if statement for each type of request because in the future I need to add more types. I try to use enum</p>
<pre><code>TestType.valueOf((String) body.get("type")).saveInDB();
</code></pre>
<p>But in the enum, I can not inject repositories and mappers. I searching for some way to solve this problem but I can not find it. Does anyone have a source with an explanation to solve the problem with if statements or some can explain how to solve it?</p>
<p>Thank you in advance.</p>
| [] | [
{
"body": "<ul>\n<li>Your repositories should have a common method save() and your mappers a mapToTest() that you can define as your interface or base class. Also your test-objects should have a common interface or base class. Let's assume that you can do that. If you cannot do that, then your code inside the if-statements is too different and you could only solve that by a map with key=TestType and value=lambda-expression (or in other words, value = object of abstract classes derived from Runnable with the code inside each run-method.).</li>\n<li>Do you really need so much new classes and instances for each new if-statement? That means for a third if-statement you would need to write new classes Test3, Test3Mapper, Tests3Repository and need to insert additional member variables into your main method for it? I fear your code quickly becomes unmaintainable. Because of all these definitions, my code example below can not be done simpler anymore. Try to write only a few classes instead and define a factory which returns different instances of it. The code example below would be much shorter if you for example would have an array of TestRepositories (or their factory names) instead of single variables test1Repository, test2Repository etc. </li>\n<li>You wrote that you cannot inject repositories and mappers in your enum. But you can inject them in your main class and pass them to the enum instances.</li>\n<li>Your enum name is \"TEST1\", but in your map \"body\" you have stored \"test1\". So you must somehow map this label to the enum. For that, you need an internal static hash map inside the enum. You will not need it if you store \"\"TEST1\" inside your map instead. But let's assume both are independent and cannot be converted via toUpperCase() etc., so we need to define the method valueOfLabel() in the enum and pass this label in the constructor.</li>\n</ul>\n\n<p>Here is the enum:</p>\n\n<pre><code>private enum TestType {\n TEST1 (\"test1\", test1Repository, test1Mapper),\n TEST2 (\"test2\", test2Repository, test2Mapper);\n\n private String label;\n private TestRepository testRepository;\n private TestMapper testMapper;\n\n private static final Map<String, TestType> labelMap = new HashMap<>();\n static {\n for (TestType testType: values()) {\n labelMap.put(testType.label, testType);\n }\n }\n public static TestType valueOfLabel(String label) {\n return labelMap.get(label);\n }\n\n TestType(String label, TestRepository testRepository, TestMapper testMapper) {\n this.label = label;\n this.testRepository = testRepository;\n this.testMapper = testMapper;\n }\n\n public void saveInDB(Map<String, Object> body) {\n Test test = testMapper.mapToTest(body);\n // TODO logic here\n System.out.println(\"test=\" + test.getClass().getSimpleName() + \", this=\" + this);\n testRepository.save(test);\n }\n\n public String toString() {\n return \"TestType [label=\" + label + \", testRepository=\" + testRepository.getClass().getSimpleName() + \", testMapper=\" + testMapper.getClass().getSimpleName() + \"]\";\n }\n}\n</code></pre>\n\n<p>Here is the replacement for your if-statements and testing this method:</p>\n\n<pre><code>private void test(Map<String, Object> body) {\n TestType.valueOfLabel((String) body.get(\"type\")).saveInDB(body);\n}\n\npublic static void main(String[] args) {\n Map<String, Object> body = new HashMap<>();\n body.put(\"type\", \"test1\");\n new Main().test(body);\n body.put(\"type\", \"test2\");\n new Main().test(body);\n}\n</code></pre>\n\n<p>Here is the test console output:</p>\n\n<pre><code>test=Test1, this=TestType [label=test1, testRepository=Test1Repository, testMapper=Test1Mapper]\ntest=Test2, this=TestType [label=test2, testRepository=Test2Repository, testMapper=Test2Mapper]\n</code></pre>\n\n<p>Here is the full program with all the clases needed to run it.\nNot everybody has Spring or has it set up, so to simplify the solution that everybody can run, I just created the needed classes.\nFeel free to change the code to autowire them instead.</p>\n\n<pre><code>package main;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Main\n{\n // tests\n static class Test {\n }\n static class Test1 extends Test {\n }\n static class Test2 extends Test {\n }\n\n // repositories\n static class TestRepository {\n public void save(Test test) {\n // TODO save it\n }\n }\n static class Test1Repository extends TestRepository {\n }\n static class Test2Repository extends TestRepository {\n }\n\n // mappers\n static class TestMapper {\n private Test test;\n public TestMapper(Test test) {\n this.test = test;\n }\n public Test mapToTest(Object body) {\n // TODO get some data out of body and call test with it\n return test;\n }\n }\n static class Test1Mapper extends TestMapper {\n public Test1Mapper(Test test) {\n super(test);\n }\n }\n static class Test2Mapper extends TestMapper {\n public Test2Mapper(Test test) {\n super(test);\n }\n }\n\n // autowired\n private static Test1Repository test1Repository = new Test1Repository();\n private static Test2Repository test2Repository = new Test2Repository();\n private static Test1Mapper test1Mapper = new Test1Mapper(new Test1());\n private static Test2Mapper test2Mapper = new Test2Mapper(new Test2());\n\n // enum\n private enum TestType {\n TEST1 (\"test1\", test1Repository, test1Mapper),\n TEST2 (\"test2\", test2Repository, test2Mapper);\n\n private String label;\n private TestRepository testRepository;\n private TestMapper testMapper;\n\n private static final Map<String, TestType> labelMap = new HashMap<>();\n static {\n for (TestType testType: values()) {\n labelMap.put(testType.label, testType);\n }\n }\n public static TestType valueOfLabel(String label) {\n return labelMap.get(label);\n }\n\n TestType(String label, TestRepository testRepository, TestMapper testMapper) {\n this.label = label;\n this.testRepository = testRepository;\n this.testMapper = testMapper;\n }\n\n public void saveInDB(Map<String, Object> body) {\n Test test = testMapper.mapToTest(body);\n // TODO logic here\n System.out.println(\"test=\" + test.getClass().getSimpleName() + \", this=\" + this);\n testRepository.save(test);\n }\n\n public String toString() {\n return \"TestType [label=\" + label + \", testRepository=\" + testRepository.getClass().getSimpleName() + \", testMapper=\" + testMapper.getClass().getSimpleName() + \"]\";\n }\n }\n\n // test\n public static void main(String[] args) {\n Map<String, Object> body = new HashMap<>();\n body.put(\"type\", \"test1\");\n new Main().test(body);\n body.put(\"type\", \"test2\");\n new Main().test(body);\n } \n\n // method under test \n private void test(Map<String, Object> body) {\n TestType.valueOfLabel((String) body.get(\"type\")).saveInDB(body);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:08:30.453",
"Id": "219369",
"ParentId": "219309",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T14:41:59.783",
"Id": "219309",
"Score": "-3",
"Tags": [
"java",
"design-patterns",
"spring",
"abstract-factory"
],
"Title": "Some way to create factory pattern for spring application"
} | 219309 |
<p>I am working on a screen which has segmented control and has 3 segments (year value 2019, 18, 17) and what I am doing is that on each segment click I have to reload data inside a tableview (getting data from an API request).</p>
<pre><code>let purchaseResponse = inputs.selectedTab.map { index -> String in
switch index {
case 0:
return "2019"
case 1:
return "2018"
case 2:
return "2017"
default:
return "2019"
} }
.distinct()
.flatMapLatest { year in
return purchaseService.fetchPurchaseHistory(forYear: year, pageNumber: 1)
}
.trackActivity(inputs.indicator)
.materialize()
.share()
</code></pre>
<p>Right now this is what I have, and it works fine, as you can see I am using the <code>Distinct</code> operator which is like this:</p>
<pre><code>extension Observable where Element: Hashable {
func distinct() -> Observable<Element> {
var set = Set<Element>()
return flatMap { element -> Observable<Element> in
objc_sync_enter(self); defer {objc_sync_exit(self)}
if set.contains(element) {
return Observable<Element>.empty()
} else {
set.insert(element)
return Observable<Element>.just(element)
}
}
}
}
</code></pre>
<p>Can I somehow refactor this, or maybe use builtin operators? The reason to use <code>Distinct</code> was that if the user clicks a segment, next time it shouldn't get data from the API.</p>
| [] | [
{
"body": "<p>The operator you are looking for is <a href=\"https://rxmarbles.com/#distinctUntilChanged\" rel=\"nofollow noreferrer\">distinctUntilChanged()</a>. It skips only equal items followed one by one.</p>\n\n<p>Or <a href=\"http://reactivex.io/documentation/operators/distinct.html\" rel=\"nofollow noreferrer\">distinct()</a> operator which skips the items what has been even once emitted in the sequence. In your case the <code>fetchPurchaseHistory</code> method could be triggered no more than 3 times by this observable with <code>distinct</code> operator</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-12T20:04:14.027",
"Id": "220150",
"ParentId": "219311",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T15:39:47.483",
"Id": "219311",
"Score": "1",
"Tags": [
"swift",
"ios",
"rx-swift"
],
"Title": "Calling API only once on changing segments"
} | 219311 |
<p>I'm using Sequelize and Google oAuth for authentication, I want to create a middleware that </p>
<ol>
<li>Verifies the sent token passed in the headers matches the one the user was initially signed to.</li>
<li>Finds the user if he/she exists and returns it to the client.</li>
</ol>
<p>The middleware be used for protected routes.</p>
<pre class="lang-js prettyprint-override"><code>const getCurrentUser = (req, res, next) => {
if (!req.headers || !req.headers.authorization) return res.status(401).end();
const token = req.headers.authorization.split(' ')[1];
if (!token) return res.status(401).end();
JWT.verify(token, process.env.JWT_SECRET, async (err, decoded) => {
if (err) {
res.status(401).end();
} else {
res.locals.JWT = decoded;
const user = await models.user.findOne({ where: { id: decoded.id } });
if (!user) return res.status(404).send({ message: 'No user found' });
req.user = user;
next();
}
});
};
</code></pre>
<p>One thing I'd like to make sure I'm doing correctly is error handling. Does this look alright? Anything to change/improve on?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T16:10:42.077",
"Id": "219313",
"Score": "4",
"Tags": [
"javascript",
"express.js",
"oauth",
"jwt"
],
"Title": "Get current user middleware from JWT using express"
} | 219313 |
<p>This is my code for <a href="https://projecteuler.net/problem=4" rel="nofollow noreferrer">Project Euler Problem #4</a></p>
<p><strong>The question:</strong></p>
<blockquote>
<p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.</p>
</blockquote>
<p><strong>My code:</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function problem4(){
let product = 1;
let largest = 1;
for(let i = 100; i<1000; i++){
for(let j = i; j<1000; j++){
product = i*j;
if(("" + product) == ("" + product).split("").reverse().join("")){
largest = Math.max(largest, product);}
}
}
return largest;
}
console.log(problem4());</code></pre>
</div>
</div>
</p>
<p>At present, it takes <code>311.5649999999732 ms</code> for execution, but I think it can be better. So how can I make it more efficient and faster?</p>
| [] | [
{
"body": "<p>How about this small modification that could potentially make it faster if the answer is large enough.</p>\n\n<pre><code>function problem4(){\n let product = 1;\n let largest = 1;\n for(let i = 999; i>=100; i--){\n for(let j = 999; j>=i && i*j>largest; j--){\n product = i*j;\n if((\"\" + product) == (\"\" + product).split(\"\").reverse().join(\"\")){\n largest = Math.max(largest, product);}\n}\n }\n return largest;\n}\nconsole.log(problem4());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T03:07:03.240",
"Id": "423668",
"Score": "0",
"body": "This new code consistently runs in under 10ms in my browser."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T02:55:36.680",
"Id": "219333",
"ParentId": "219314",
"Score": "3"
}
},
{
"body": "<h2>Smarter brute force</h2>\n\n<p>You have two major slow points. </p>\n\n<ol>\n<li><p>You are checking numbers from the smallest towards the largest. That means that you can not use any found palindromes to help you avoid calculations. Ie there is no need to check if a product is a palindrome if it is smaller than the current biggest found.</p></li>\n<li><p>The method you use to check if a number is a palindrome is slow. Using a faster numerical test will provide a significant performance increase.</p></li>\n</ol>\n\n<h2>A better palindrome checker</h2>\n\n<p>The following function is on average 3 times faster than the method you use. Simply using it in your could would reduce the time from 311ms down to near 100ms.</p>\n\n<pre><code>function isPalindrome(num) {\n var top = Math.pow(10, Math.log10(num) | 0), bot = 1;\n while (top >= bot) {\n if ((num / top % 10 | 0) !== (num / bot % 10 | 0)) { return false }\n top /= 10;\n bot *= 10;\n }\n return true;\n}\n</code></pre>\n\n<h2>Pick the low hanging fruit</h2>\n\n<p>The palindrome that you are after is most likely near the high numbers. </p>\n\n<p>Using iterators that count from 1000 down we can avoid checking products if they are lower than any found max.</p>\n\n<p>We also know that because we are counting down, each iterator will only be stepping over smaller products. Using this we can break from the inner or outer iterator as soon as we find a product that is smaller than the max found palindrome.</p>\n\n<h2>Example</h2>\n\n<p>The following solution is still a brute force method. </p>\n\n<p>It finds the palindrome in 1.3ms, iterating over 5267 products, checking 5224 of them for palindromes. </p>\n\n<p>Compared to your function that iterated over 405,450 products and checked each for palindromes. Little wonder it took nearly one third of a second to do.</p>\n\n<pre><code>function problem(){\n const minNum = 100, range = 899;\n const isPalindrome = num => {\n var top = Math.pow(10, Math.log10(num) | 0), bot = 1;\n while (top >= bot) {\n if ((num / top % 10 | 0) !== (num / bot % 10 | 0)) { return false }\n top /= 10;\n bot *= 10;\n }\n return true;\n }\n\n var i = range, max = minNum * minNum, j, iVal;\n\n while (i--) {\n iVal = i + minNum;\n j = i + 1;\n if (iVal * (j - 1 + minNum) < max) { break }\n while (j--) {\n const product = iVal * (j + minNum);\n if (product <= max) { break }\n if (isPalindrome(product)) { max = Math.max(max, product) }\n }\n }\n return max;\n}\n</code></pre>\n\n<h2>Under 1ms</h2>\n\n<p>The above function is still slow. 1.3ms is forever in computer time. I have a feeling this can get down to about 0.6ms. I checked to see how many of the 5267 products iterated over were smaller than the max palindrome. </p>\n\n<p>3088 (58%) checked products were smaller than the result. It is likely a different pattern of iteration steps can avoid many of these.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T05:08:47.343",
"Id": "219338",
"ParentId": "219314",
"Score": "2"
}
},
{
"body": "<p>It is worth pointing out that if you are trying to improve the performance of your code, you can focus your code on <em>exactly the problem you want to solve.</em></p>\n\n<h3>Standardize your timing</h3>\n\n<p>If I told you a function ran in 400 ms on my machine would you prefer it over your 311 ms version? What if my machine is an OOOOOOLD 32-bit laptop?</p>\n\n<p>Always provide a timing framework. That way I can check the performance of my code versus your code, using your framework. I've included one below based on the <code>performance</code> module.</p>\n\n<h3>Focus on the problem</h3>\n\n<p>You aren't looking for \"any palindrome\" or \"any number that is a palindrome.\" You are looking for \"any number that is the product of two 3-digit numbers which is a palindrome.\" Take advantage of that!</p>\n\n<p>You know that the smallest 3-digit number is 100, and the largest is 999. So the smallest product will be 10,000 and the largest product will be <1,000,000.\nThus, the palindrome in question is either a 5-digit number or a 6-digit number. Write your code to that specification:</p>\n\n<pre><code>const is_palindrome = num => {\n if (num >= 100000) {\n let t0 = num % 10;\n let t5 = num / 100000 | 0;\n if (t5 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t4 = num / 10000 % 10 | 0;\n if (t4 != t1) return false;\n let t2 = num / 100 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t2) return false;\n }\n else {\n let t0 = num % 10;\n let t4 = num / 10000 | 0;\n if (t4 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t1) return false;\n }\n return true;\n}\n</code></pre>\n\n<h3>Be lazy</h3>\n\n<p>As Jorge F. points out, you are looking for the largest palindromic number. So why start at the small end of the range? For some product X * Y, you know that if Y1 > Y2, then X * Y1 > X * Y2. So always try the higher number first! And if you find a palindrome, then you're done with <em>all</em> the other Y2's that might be smaller than your Y1, so move on to the next X.</p>\n\n<pre><code>for (var x = 999; x >= 100; --x)\n for (var y = 999; y >= x; --y) {\n</code></pre>\n\n<h3>Laziness: fail early</h3>\n\n<p>Also as Jorge shows, you can quit if the product ever gets smaller than your present largest value:</p>\n\n<pre><code>for (var x = 999; x >= 100; --x) {\n if (x * 999 <= largest) \n break;\n\n for (var y = 999; y >= x; --y) {\n if (x * y <= largest)\n break;\n</code></pre>\n\n<h3>Explore the optimizer!</h3>\n\n<p>Finally, one thing worth considering is that you don't really know how the particular optimizer your javascript engine is running will work. So it's worth trying to manually perform some improvements to see if it helps. One improvement you could perform is to notice that you are always multiplying by one less number:</p>\n\n<pre><code>x * 999\nx * 998\nx * 997\n</code></pre>\n\n<p>Which is really just the same as subtracting <code>x</code> from the previous result:</p>\n\n<pre><code>product = x * 999\nproduct -= x\nproduct -= x\n</code></pre>\n\n<p>Why not make that your inner loop and see if performance improves? FWIW, on my machine, it made a small difference (sometimes -2, sometimes -1 from <code>_jf</code> version). I'm not sure if that's real, or just a result of getting things into the cache. Let me know what your timings look like.</p>\n\n<pre><code>Results:\nFunction OK? Timing(ms)\nEagle Y 2095\nJorge Fernández Y 17\nBlindman67 Y 10\naghast_bm Y 5\naghast_jf Y 4\naghast_nomult Y 2\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function profile(name, fn) {\n let t0 = performance.now();\n let result = fn(); \n // Run some more, for more timing!\n fn();\n fn();\n fn();\n let t1 = performance.now();\n return [name, result, (t1-t0)];\n}\n\nfunction p4_eagle(){\n let product = 1;\n let largest = 1;\n for(let i = 100; i<1000; i++){\n for(let j = i; j<1000; j++){\n product = i*j;\n if((\"\" + product) == (\"\" + product).split(\"\").reverse().join(\"\")){\n largest = Math.max(largest, product);}\n}\n }\n return largest;\n}\n\nfunction p4_jorge_fernandez(){\n let product = 1;\n let largest = 1;\n for(let i = 999; i>=100; i--){\n for(let j = 999; j>=i && i*j>largest; j--){\n product = i*j;\n if((\"\" + product) == (\"\" + product).split(\"\").reverse().join(\"\")){\n largest = Math.max(largest, product);}\n}\n }\n return largest;\n}\n\nfunction p4_blindman67(){\n const minNum = 100, range = 899;\n const isPalindrome = num => {\n var top = Math.pow(10, Math.log10(num) | 0), bot = 1;\n while (top >= bot) {\n if ((num / top % 10 | 0) !== (num / bot % 10 | 0)) { return false }\n top /= 10;\n bot *= 10;\n }\n return true;\n }\n\n var i = range, max = minNum * minNum, j, iVal;\n\n while (i--) {\n iVal = i + minNum;\n j = i + 1;\n if (iVal * (j - 1 + minNum) < max) { break }\n while (j--) {\n const product = iVal * (j + minNum);\n if (product <= max) { break }\n if (isPalindrome(product)) { max = Math.max(max, product) }\n }\n }\n return max;\n}\n\nfunction p4_aghast_bm(){\n const is_palindrome = num => {\n if (num >= 100000) {\n let t0 = num % 10;\n let t5 = num / 100000 | 0;\n if (t5 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t4 = num / 10000 % 10 | 0;\n if (t4 != t1) return false;\n let t2 = num / 100 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t2) return false;\n }\n else {\n let t0 = num % 10;\n let t4 = num / 10000 | 0;\n if (t4 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t1) return false;\n }\n return true;\n }\n\n const minNum = 100, range = 899;\n var i = range, max = minNum * minNum, j, iVal;\n\n while (i--) {\n iVal = i + minNum;\n j = i + 1;\n if (iVal * (j - 1 + minNum) < max) { break }\n while (j--) {\n const product = iVal * (j + minNum);\n if (product <= max) { break }\n if (is_palindrome(product)) { max = Math.max(max, product) }\n }\n }\n return max;\n}\n\nfunction p4_aghast_jf(){\n const is_palindrome = num => {\n if (num >= 100000) {\n let t0 = num % 10;\n let t5 = num / 100000 | 0;\n if (t5 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t4 = num / 10000 % 10 | 0;\n if (t4 != t1) return false;\n let t2 = num / 100 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t2) return false;\n }\n else {\n let t0 = num % 10;\n let t4 = num / 10000 | 0;\n if (t4 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t1) return false;\n }\n return true;\n }\n let product = 1;\n let largest = 1;\n for(let i = 999; i>=100; i--){\n for(let j = 999; j>=i && i*j>largest; j--){\n product = i*j;\n if (is_palindrome(product)) {\n largest = Math.max(largest, product);\n }\n }\n }\n return largest;\n}\n\nfunction p4_aghast_nomult(){\n const is_palindrome = num => {\n if (num >= 100000) {\n let t0 = num % 10;\n let t5 = num / 100000 | 0;\n if (t5 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t4 = num / 10000 % 10 | 0;\n if (t4 != t1) return false;\n let t2 = num / 100 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t2) return false;\n }\n else {\n let t0 = num % 10;\n let t4 = num / 10000 | 0;\n if (t4 != t0) return false;\n let t1 = num / 10 % 10 | 0;\n let t3 = num / 1000 % 10 | 0;\n if (t3 != t1) return false;\n }\n return true;\n }\n\n let largest = 1;\n for (let i = 999; i >= 100; --i) {\n if (i * 999 <= largest) \n break;\n\n for (let product = i * 999; product >= i * i; product -= i) {\n if (product <= largest)\n break;\n if (is_palindrome(product)) \n {\n largest = product;\n break;\n }\n }\n }\n return largest;\n}\n////////////////////////////////////////////////////////////\n\nvar details = [\n ['Eagle', p4_eagle],\n ['Jorge Fernández', p4_jorge_fernandez],\n ['Blindman67', p4_blindman67],\n ['aghast_bm', p4_aghast_bm],\n ['aghast_jf', p4_aghast_jf],\n ['aghast_nomult', p4_aghast_nomult],\n];\nvar results = [];\nfor (deets of details) {\n let [name, fn] = deets;\n results.push(profile(name, fn));\n}\n\nlet correct = results[0][1];\n\nconst tab = \"\\t\";\nconst pad = \" \".repeat(20);\n\nvar msg = \"Results:\\n\"\n + (\"Function\" + pad).slice(0, 20) + \"OK?\" + tab + \"Timing(ms)\\n\";\n\nfor (res of results) {\n let [name, answer, time] = res;\n msg += (name + pad).slice(0, 20) + (correct == answer ? \"Y\" : \"No!\") + tab + time + \"\\n\";\n}\n\n//alert(msg);\nconsole.log(msg);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:10:27.410",
"Id": "219380",
"ParentId": "219314",
"Score": "2"
}
},
{
"body": "<p>In general, prefer to use the narrowest possible scope for variables. Old-school JavaScript is an exception for technical reasons to do with its scope rules being rather unusual and catching out people who were used to other languages: <code>let</code> was introduced to address that problem.</p>\n\n<p>In short, <code>product</code> should be declared inside the loop over <code>j</code>.</p>\n\n<p>Also, given the way it's used, it makes reasonable sense for it to be <code>\"\" + i*j</code> so that the conversion from number to string is only done once.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if((\"\" + product) == (\"\" + product).split(\"\").reverse().join(\"\")){\n largest = Math.max(largest, product);}\n}\n }\n</code></pre>\n</blockquote>\n\n<p>What happened to the whitespace there?</p>\n\n<hr>\n\n<blockquote>\n <p>So how can I make it more efficient and faster?</p>\n</blockquote>\n\n<p>Often the key to making something much faster is to use a completely different approach.</p>\n\n<p>The challenge requires you to</p>\n\n<blockquote>\n <p>Find the largest palindrome made from the product of two 3-digit numbers.</p>\n</blockquote>\n\n<p>but it doesn't tell you <em>how</em> to do that.</p>\n\n<p>One approach is to look at products of 3-digit numbers, filter to palindromes, and find the largest product which passes the filter. This is the approach you've taken, and the one taken by all of the answers so far.</p>\n\n<p>Another approach is to look at 6-digit palindromes in reverse order and filter to products of 3-digit numbers:</p>\n\n<pre><code>for (let d50 = 900009; d50 > 0; d50 -= 100001) {\n for (let d41 = 90090; d41 >= 0; d41 -= 10010) {\n for (let d32 = 9900; d32 >= 0; d32 -= 1100) {\n let palindrome = d50 + d41 + d32;\n for (let x = Math.ceil(palindrome / 999); x < 1000 && x * x <= palindrome; x++) {\n if (palindrome % x === 0) {\n return palindrome;\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>In my benchmarking this is twice as fast as the fastest proposal so far in this thread, and I haven't even micro-optimised it. (To do that: replace <code>x * x</code> with <code>x2</code>, initialised to <code>x * x</code> and then updated as <code>x2 += 2*x + 1</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T17:14:59.153",
"Id": "219659",
"ParentId": "219314",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T16:18:59.340",
"Id": "219314",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"programming-challenge",
"palindrome"
],
"Title": "Largest Palindrome Product - Project Euler #4"
} | 219314 |
<p>I am looking for feedbacks about my ASP.NET Core Request / Response logging middleware, in particular in ways to lower the memory footprint and string allocations:</p>
<pre><code>public class RequestResponseLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestResponseLoggingMiddleware> _logger;
private readonly RecyclableMemoryStreamManager _recyclableMemoryStreamManager;
private const int ReadChunkBufferLength = 4096;
public RequestResponseLoggingMiddleware(RequestDelegate next, ILogger<RequestResponseLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
_recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
}
public async Task Invoke(HttpContext context)
{
var requestProfilerModel = new RequestProfilerModel
{
RequestTime = new DateTimeOffset(),
Context = context,
Request = await FormatRequestAsync(context)
};
var originalBody = context.Response.Body;
using (var newResponseBody = _recyclableMemoryStreamManager.GetStream())
{
context.Response.Body = newResponseBody;
await _next(context);
newResponseBody.Seek(0, SeekOrigin.Begin);
await newResponseBody.CopyToAsync(originalBody);
newResponseBody.Seek(0, SeekOrigin.Begin);
requestProfilerModel.Response = await FormatResponseAsync(context, newResponseBody);
requestProfilerModel.ResponseTime = new DateTimeOffset();
_logger.LogInformation(requestProfilerModel.Request);
_logger.LogInformation(requestProfilerModel.Response);
}
}
private async Task<string> FormatResponseAsync(HttpContext context, Stream newResponseBody)
{
var request = context.Request;
var response = context.Response;
return $"Http Response Information: {Environment.NewLine}" +
$"Schema: {request.Scheme} {Environment.NewLine}" +
$"Host: {request.Host} {Environment.NewLine}" +
$"Path: {request.Path} {Environment.NewLine}" +
$"QueryString: {request.QueryString} {Environment.NewLine}" +
$"Headers: {Environment.NewLine}" + FormatHeaders(response.Headers) +
$"StatusCode: {response.StatusCode} {Environment.NewLine}" +
$"Response Body: {await ReadStreamInChunksAsync(newResponseBody)}";
}
private async Task<string> FormatRequestAsync(HttpContext context)
{
var request = context.Request;
return $"Http Request Information: {Environment.NewLine}" +
$"Schema:{request.Scheme} {Environment.NewLine}" +
$"Host: {request.Host} {Environment.NewLine}" +
$"Path: {request.Path} {Environment.NewLine}" +
$"QueryString: {request.QueryString} {Environment.NewLine}" +
$"Headers: {Environment.NewLine}" + FormatHeaders(request.Headers) +
$"Request Body: {await GetRequestBodyAsync(request)}";
}
private string FormatHeaders(IHeaderDictionary headers)
{
var stringBuilder = new StringBuilder();
foreach (var (key, value) in headers)
{
stringBuilder.AppendLine($"- {key}: {value}");
}
return stringBuilder.ToString();
}
public async Task<string> GetRequestBodyAsync(HttpRequest request)
{
request.EnableBuffering();
request.EnableRewind();
using (var stream = _recyclableMemoryStreamManager.GetStream())
{
await request.Body.CopyToAsync(stream);
request.Body.Seek(0, SeekOrigin.Begin);
return await ReadStreamInChunksAsync(stream);
}
}
private static async Task<string> ReadStreamInChunksAsync(Stream stream)
{
stream.Seek(0, SeekOrigin.Begin);
string result;
using (var stringWriter = new StringWriter())
using (var streamReader = new StreamReader(stream))
{
var readChunk = new char[ReadChunkBufferLength];
int readChunkLength;
//do while: is useful for the last iteration in case readChunkLength < chunkLength
do
{
readChunkLength = await streamReader.ReadBlockAsync(readChunk, 0, ReadChunkBufferLength);
await stringWriter.WriteAsync(readChunk, 0, readChunkLength);
} while (readChunkLength > 0);
result = stringWriter.ToString();
}
return result;
}
}
</code></pre>
| [] | [
{
"body": "<p>I would recommend using <a href=\"https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/extensibility?view=aspnetcore-2.2\" rel=\"nofollow noreferrer\">Factory-based middleware</a> instead of the by-convention method that you share here. You would then be able to have scoped DI.</p>\n\n<p>For string concatenation, consider using a <code>StringBuilder</code> instead of the plus-operator everywhere. I can see you use it in some places, but that string concatenation with interpolation \"looks\" costly. Refer to the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netframework-4.8#remarks\" rel=\"nofollow noreferrer\">remarks section</a> to see if the <code>StringBuilder</code> is a good choice for your use-case.</p>\n\n<p>Experiment with <code>ReadChunkBufferLength</code> and consider making it a configurable value with a sane default. <a href=\"https://stackoverflow.com/questions/780316/optimal-buffer-size-for-response-stream-of-httpwebresponse\">This SO post</a> might provide some insight.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:39:27.350",
"Id": "423682",
"Score": "1",
"body": "String concatenation with `+` only matters in loops. Here it doesn't make any difference and OP is already using `StringBuilder` with a loop. What's ugly are the new-lines. `string.Join` would be an option too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:20:21.670",
"Id": "423692",
"Score": "0",
"body": "@t3chb0t btw, nothing can be improved through `Span<T>`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:22:10.057",
"Id": "423693",
"Score": "0",
"body": "@EhouarnPerret `Span<T>` is for reading and creating `string` _views_ to avoid copying it, you are only creating `string`s and writing so I don't thing it could help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T09:56:20.147",
"Id": "423705",
"Score": "0",
"body": "@t3chb0t okay makes sense, thanks for the clarifications!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T22:22:58.560",
"Id": "219326",
"ParentId": "219315",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219326",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T17:05:12.590",
"Id": "219315",
"Score": "4",
"Tags": [
"c#",
"logging",
"memory-optimization",
"asp.net-core",
".net-core"
],
"Title": "ASP.NET Core Request / Response logging middleware"
} | 219315 |
<p><strong>Question</strong></p>
<p>Any way I can optimize this further using new C++11 or C++17 features? Would also like feedback on my variable naming, memory management, and style (notice my placement of <code>varible_name++</code> in some areas), and how I've abstracted the sort into a <code>recursive_merge_sort</code> function and a <code>merge</code> function.</p>
<p><strong>Code</strong></p>
<pre><code>#include <iostream>
void merge(int* data, int low, int mid, int high)
{
int low_copy = low;
int mid_copy = mid;
int size = high - low;
int* sorted = new int[size];
int i = 0;
while(low_copy < mid && mid_copy < high) {
if(data[low_copy] < data[mid_copy]) {
sorted[i] = data[low_copy++];
}
else {
sorted[i] = data[mid_copy++];
}
++i;
}
while(low_copy < mid) {
sorted[i++] = data[low_copy++];
}
while(mid_copy < high) {
sorted[i++] = data[mid_copy++];
}
for(i = 0; i < size; ++i) {
data[low + i] = sorted[i];
}
}
void recursive_merge_sort(int* data, int low, int high) {
if(low >= high - 1) { return; }
int mid = (high + low) / 2;
recursive_merge_sort(data, low, mid);
recursive_merge_sort(data, mid, high);
merge(data, low, mid, high);
}
void merge_sort(int* data, int num_elements) {
recursive_merge_sort(data, 0, num_elements);
}
int main()
{
int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };
int num_elements = 9;
std::cout << "unsorted\n";
for(int i=0; i < num_elements; ++i) {
std::cout << data[i] << " ";
}
merge_sort(data, num_elements);
std::cout << "\nsorted\n";
for(int i=0; i < num_elements; ++i) {
std::cout << data[i] << " ";
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T17:56:57.117",
"Id": "423638",
"Score": "4",
"body": "This is not much different from C, and there is a memory leak. Perhaps you could use a tool such as valgrind to detect memory leak and have a look at [classic answer](https://stackoverflow.com/a/24650627/4593721) on implementation of sorting algorithms?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:25:55.007",
"Id": "423679",
"Score": "1",
"body": "This becomes much more interesting when you are sorting something not as trivial as `int`. Because C++ allows you to define the `operator<` for any type you can sort any type that can be compared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T11:44:04.383",
"Id": "423716",
"Score": "0",
"body": "Did you calculate how much memory your code allocates during sorting, say, a one thousand elements array? And how many times it invokes allocator function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T04:29:27.920",
"Id": "423818",
"Score": "0",
"body": "I attempted to use valgrind, but ran into this issue on my OS https://stackoverflow.com/questions/52732036/how-to-install-valgrind-on-macos-mojave10-14-with-homebrew"
}
] | [
{
"body": "<ol>\n<li><p>If you have a range from start till end, why do you describe it with a base-pointer and two indices, instead of two pointers or a pointer and a size?<br>\nEquivalently for the split range passed to <code>merge()</code>.</p></li>\n<li><p>You are allocating a new array on each call to <code>merge()</code>.<br>\nWhy not just do a single allocation in the base <code>merge_sort()</code>?</p></li>\n<li><p>Also, you are leaking it.</p></li>\n<li><p>Using the ternary operator <code>condition ? true_expr : false_expr</code> would simplify some of your code.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n</ol>\n\n<p>That should be enough to get you started.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T00:31:18.247",
"Id": "219328",
"ParentId": "219316",
"Score": "3"
}
},
{
"body": "<h3>Design</h3>\n<p>Passing <code>data</code> with <code>high</code> and <code>low</code> works. But is equivalent to <code>data+low</code> and <code>data+high</code>. And just passing two values.</p>\n<p>This is what is referred to as an Iterator range. If you look at the standard library you will see that a lot of the concepts hinge around iterators you should look that up and understand how it works.</p>\n<h3>Code Review</h3>\n<p>For every call to <code>new</code> there should be a call to <code>delete</code>.</p>\n<pre><code> int* sorted = new int[size];\n</code></pre>\n<p>Or so the old text books tell us. In modern C++ you probably should never call new or delete (unless you know its a good idea).</p>\n<p>But here you are leaking memory because you don't release it. You should add a <code>delete [] sorted;</code> to the end of the function.</p>\n<p><strong>BUT</strong> leaving the new/delete in your code is not a good idea. It's not exception safe to start with. So simply declare a <code>vector<int></code> here and let it manage the memory for you.</p>\n<p>We should also note that memory management is very expensive. So rather than doing this every loop. Why not do it once at the beginning and reuse the memory.</p>\n<p>Sure this works:</p>\n<pre><code> while(low_copy < mid && mid_copy < high) {\n if(data[low_copy] < data[mid_copy]) {\n sorted[i] = data[low_copy++];\n }\n else {\n sorted[i] = data[mid_copy++];\n }\n ++i;\n }\n</code></pre>\n<p>But we could simplify it:</p>\n<pre><code> for(;low_copy < mid && mid_copy < high; ++i) {\n sorted[i] = (data[low_copy] < data[mid_copy])\n ? data[low_copy++];\n : data[mid_copy++];\n }\n</code></pre>\n<p>Also when you see loops like this you should look at the standard algorithms to see if there is one that will do all that work for you.</p>\n<p>Another thing to note is that you are copying the value from <code>data</code> to <code>sorted</code>. This is fine for integers, but you should be able to sort nearly any C++ type and copying a C++ type is not usually the most efficient way to get the value from one location to another. You should look up the concept of <code>moving</code>. When the type being sorted is a bit more complex moving it (rather than copying is usually a better idea).</p>\n<p>These loops can definitely be done by standard algorthims:</p>\n<pre><code> while(low_copy < mid) {\n sorted[i++] = data[low_copy++];\n }\n // Or \n std::copy(data + low_copy, data + mid, sorted + i);\n // Or (when you move objects)\n std::move(data + low_copy, data + mid, sorted + i);\n</code></pre>\n<p>This is subject to overflow.</p>\n<pre><code> int mid = (high + low) / 2;\n</code></pre>\n<p>Common mistake. If <code>high</code> and <code>low</code> are both large then this could easily overflow. Do the division fist (on the difference). Then add to the low.</p>\n<pre><code> int mid = low + (high - low) / 2;\n</code></pre>\n<p>Are you sure there are 9 elements?</p>\n<pre><code> int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };\n int num_elements = 9;\n</code></pre>\n<p>Common source of errors. Don't manually do stuff the compiler can work out correctly. This is especially true if <code>data</code> is subsequently modified (and human person can make mistakes) does not change <code>num_elements</code>.</p>\n<pre><code> int data[] = { 5, 1, 4, 3, 65, 6, 128, 9, 0 };\n int num_elements = sizeof(data)/sizeof(data[0]);\n</code></pre>\n<p>In more modern versions of C++ we even have a standard way of doing it:</p>\n<pre><code> int num_elements = std::size(data);\n</code></pre>\n<p>No need for this in main:</p>\n<pre><code> return 0;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:00:40.983",
"Id": "423804",
"Score": "0",
"body": "For your `std::copy` example, why did you choose to add to the pointers instead of using `var.begin()` and `var.end()`? This must be an example of an Iterator range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:01:11.773",
"Id": "423806",
"Score": "0",
"body": "How did you determine what calculation you use for mid to over overflow here ` int mid = low + (high - low) / 2;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:39:48.077",
"Id": "423808",
"Score": "0",
"body": "@greg: The `std::copy()` example is an example of replacing your `where(){}` loop. So it should use the same range."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:41:02.167",
"Id": "423809",
"Score": "0",
"body": "@greg: How did I work out out how to calculate the mid point in a range? Or how did I determine that `high + low` could overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:42:14.563",
"Id": "423811",
"Score": "0",
"body": "@greg Please write comments in sentences. I don't understand what you mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:42:16.730",
"Id": "423812",
"Score": "0",
"body": "How did you rearrange my equation to account for overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:42:35.963",
"Id": "423813",
"Score": "1",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93021/discussion-between-martin-york-and-greg)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T04:46:37.303",
"Id": "423819",
"Score": "0",
"body": "Pointer iterator syntax is explained here https://www.programiz.com/cpp-programming/pointers-arrays"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T06:32:54.023",
"Id": "423828",
"Score": "1",
"body": "@greg Note pointers are an implementation of the iterator concept."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:46:50.570",
"Id": "219341",
"ParentId": "219316",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "219341",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T17:35:14.960",
"Id": "219316",
"Score": "3",
"Tags": [
"c++",
"c++11",
"pointers",
"mergesort",
"c++17"
],
"Title": "Merge Sort C++11 C++17"
} | 219316 |
<p>Is the following a cryptographically secure way to generate a random token? Does it have any of the predictability risks that are theoretically associated with using a GUID as a token?</p>
<pre><code>using System;
using System.Security.Cryptography;
namespace myApp
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[32];
using (var rng = new RNGCryptoServiceProvider()) {
rng.GetBytes(bytes);
}
string hexToken = BitConverter.ToString(bytes).Replace("-", "").ToLower();
Console.WriteLine(hexToken);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>What is there to say about it?</p>\n\n<p>The code generates 32 random bytes, fed by a good Cryptographically Secure Random Number Generator, seeded by the operating system. Then it converts to just lowercase hexadecimals.</p>\n\n<p>There is only a very small chance that a <code>CryptographicException</code> is thrown by the random number generator, but if it happens it is currently not caught.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T20:39:11.810",
"Id": "219321",
"ParentId": "219318",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219321",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T18:39:55.887",
"Id": "219318",
"Score": "2",
"Tags": [
"c#",
"cryptography"
],
"Title": "Cryptographically secure token generation in C#"
} | 219318 |
<p>This is an exercise to create a class that behaves exactly like an <code>int</code>.</p>
<h2>Questions</h2>
<ul>
<li>Am I missing anything?</li>
<li>Or did I going about this about this the wrong way?</li>
<li>Is there anything I could improve on?</li>
<li>Are there any tricks that I could learn from this?<br></li>
<li>How about style; does the style look OK?</li>
</ul>
<pre><code>#include <iostream> // std::cout
#include <utility> // std::move
class jd_int {
public:
jd_int() = default;
jd_int(int i) : _i{i} { }
jd_int(const jd_int& jdi) : _i{jdi._i} { }
jd_int(jd_int&& jdi) : _i{std::move(jdi._i)} { }
jd_int operator= (int i) { _i = i; return *this; }
jd_int operator= (double d) { _i = d; return *this; }
jd_int operator= (const jd_int& jdi) { _i = jdi._i; return *this; }
jd_int operator= (jd_int&& jdi) { _i = std::move(jdi._i); return *this; }
~jd_int() = default;
operator bool() { return !!_i; }
operator int() { return static_cast<int>(_i); }
operator double() { return static_cast<double>(_i); }
jd_int operator+=(jd_int jdi) { return _i += jdi._i; }
jd_int operator+ (jd_int jdi) { return _i + jdi._i; }
jd_int operator-=(jd_int jdi) { return _i -= jdi._i; }
jd_int operator- (jd_int jdi) { return _i - jdi._i; }
jd_int operator*=(jd_int jdi) { return _i *= jdi._i; }
jd_int operator* (jd_int jdi) { return _i * jdi._i; }
jd_int operator/=(jd_int jdi) { return _i /= jdi._i; }
jd_int operator/ (jd_int jdi) { return _i / jdi._i; }
jd_int operator%=(jd_int jdi) { return _i %= jdi._i; }
jd_int operator% (jd_int jdi) { return _i % jdi._i; }
jd_int operator++() { return ++_i; }
jd_int operator++(int) { jd_int tmp = *this; ++_i; return tmp; }
jd_int operator--() { return --_i; }
jd_int operator--(int) { jd_int tmp = *this; --_i; return tmp; }
friend bool operator< (jd_int lhs, jd_int rhs);
friend bool operator> (jd_int lhs, jd_int rhs);
friend bool operator<=(jd_int lhs, jd_int rhs);
friend bool operator>=(jd_int lhs, jd_int rhs);
friend bool operator==(jd_int lhs, jd_int rhs);
friend bool operator!=(jd_int lhs, jd_int rhs);
private:
int _i;
friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
friend std::istream& operator>>(std::istream& is, jd_int jdi);
};
bool operator< (jd_int lhs, jd_int rhs) { return (lhs._i < rhs._i); }
bool operator> (jd_int lhs, jd_int rhs) { return (lhs._i > rhs._i); }
bool operator<=(jd_int lhs, jd_int rhs) { return (lhs._i <= rhs._i); }
bool operator>=(jd_int lhs, jd_int rhs) { return (lhs._i >= rhs._i); }
bool operator==(jd_int lhs, jd_int rhs) { return (lhs._i == rhs._i); }
bool operator!=(jd_int lhs, jd_int rhs) { return (lhs._i != rhs._i); }
std::ostream& operator<<(std::ostream& os, const jd_int jdi) {
os << jdi._i;
return os;
}
std::istream& operator>>(std::istream& is, jd_int jdi) {
is >> jdi._i;
return is;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:22:00.853",
"Id": "423653",
"Score": "1",
"body": "What's the primary purpose for doing so? Can you elaborate please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:49:09.370",
"Id": "423661",
"Score": "0",
"body": "It's an exercise question by Bjarne Stroustrup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T22:08:37.457",
"Id": "423662",
"Score": "1",
"body": "There's a number of operator definitions missing then,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:40:46.883",
"Id": "423683",
"Score": "1",
"body": "Yes, this question appears to be incomplete. We can handle large pieces of code, don't be afraid to upload it all. However, that's for next time. Your question has already been answered now, so please don't touch the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:42:03.973",
"Id": "423684",
"Score": "0",
"body": "Isn't declaring a private `int _i` cheating here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:44:03.387",
"Id": "423685",
"Score": "2",
"body": "Basically, you're simulating an `int` by comparing against an actual `int`. That's not simulating, that's wrapping."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:45:12.437",
"Id": "423883",
"Score": "0",
"body": "Strictly speaking, this is impossible. For example, it is not possible to have a class `C` such that `std::is_integral_v<C>` is true."
}
] | [
{
"body": "<p>I would make the bool operator explicit (and const)</p>\n\n<p>The explicit will prevent the object being auto converted to bool in situations where you don't want it too. This may break with <code>int</code> type but is usually a better work match.</p>\n\n<pre><code>explicit operator bool() const { return !!_i; }\n</code></pre>\n\n<p>I know how the <code>!!</code> works but it is obscure and a lot of people will raise an eyebrow. At least write a comment about it.</p>\n\n<hr>\n\n<p>These methods should be const</p>\n\n<pre><code>operator int() const { return static_cast<int>(_i); }\noperator double() const { return static_cast<double>(_i); }\n// ^^^^^\n</code></pre>\n\n<p>They do not change the state of the class.</p>\n\n<hr>\n\n<p>All the assignment operator methods are defined wrong.</p>\n\n<pre><code>jd_int operator+=(jd_int jdi) { return _i += jdi._i; }\n\n// Should be:\n\njd_int& operator+=(jd_int const& jdi) { _i += jdi._i; return *this; }\n</code></pre>\n\n<p>The <code>op=</code> is modifying the current object. Thus you should return a reference (not an object). Consequentially the return should return <code>*this</code>. There is no need to pass the input parameter by value (this could cause an unrequited copy). Rather pass the parameter by const reference to avoid this.</p>\n\n<hr>\n\n<p>All the simple operator could be done better</p>\n\n<pre><code>jd_int operator+ (jd_int jdi) { return _i + jdi._i; }\n\n// Should be:\n\njd_int operator+ (jd_int const& jdi) { return jd_int(*this) += idi; }\n</code></pre>\n\n<p>Pass the parameter by const reference. Then use the op-assignment to do the work.</p>\n\n<hr>\n\n<p>You define all the operators as members of the class. Personally I would also do this. But there is an argument for making the free standing functions.</p>\n\n<pre><code>id_int + int => works. (int will be converted to id_int then addition done)\nint + id_int => fails to compile.\n</code></pre>\n\n<p>If you convert the above members into free standing functions then you will get either side to auto convert. </p>\n\n<hr>\n\n<p>The freestanding friend functions.</p>\n\n<pre><code>friend bool operator< (jd_int lhs, jd_int rhs);\n...\nfriend std::ostream& operator<<(std::ostream& os, const jd_int jdi);\nfriend std::istream& operator>>(std::istream& is, jd_int jdi);\n</code></pre>\n\n<p>You declare them in the function and then define them later. Why? These are trivial functions define them inside the class. Splitting the declaration and definition does not provide any benefit.</p>\n\n<p>Also pass the parameters by const reference when you can.</p>\n\n<pre><code>friend bool operator< (jd_int const& lhs, jd_int const& rhs) {return (lhs._i < rhs._i); }\n...\nfriend std::ostream& operator<<(std::ostream& os, jd_int const& jdi) {return os << idi._i;}\nfriend std::istream& operator>>(std::istream& is, jd_int& jdi) {return is >> idi._i;}\n</code></pre>\n\n<hr>\n\n<p>I think you are missing a couple of operations (<code>binary and</code> and <code>binary or</code> sprint to mind).</p>\n\n<hr>\n\n<p>I hate it when people use underscore as the first character of an identifier.</p>\n\n<pre><code>int _i;\n</code></pre>\n\n<p>There are some complex rules around its usage. Not everybody knows these rules exactly so something best avoided. Also why <code>i</code> why not <code>value</code> at least that is a bit more meaningful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T11:10:02.430",
"Id": "423714",
"Score": "0",
"body": "I am afraid I have to differ on the \"pass by const reference whenever possible\" viewpoint. Passing a `jd_int` by value is probably better than by const reference considering its size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:14:10.860",
"Id": "423741",
"Score": "0",
"body": "@L.F. If you make the assumption that the class will never change. Since parameters are usually passed by register you will use the same amount of register by either method. So passing by value at best will be the same cost."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:00:43.457",
"Id": "423805",
"Score": "0",
"body": "But passing by value has its benefit, right? You don’t want to pass builtin types by value. That doesn’t really matter that much, anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:37:49.313",
"Id": "423807",
"Score": "0",
"body": "@L.F. I can see your argument. But having to take into account future maintenance I would do the const reference passing now. It may never pay off but just in case it does (and it does not cost you anything (in my opinion (apart from two minutes of time)))."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T06:16:38.787",
"Id": "219340",
"ParentId": "219323",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p>Are there any tricks that I could learn from this?</p>\n</blockquote>\n\n<p>This sometimes defeats the purpose of an exercise, but it's worth knowing about ways to reduce the amount of boilerplate. Notice how much typing you have to perform in order to define so many almost-identical functions, e.g. all the comparison operators, all the arithmetic operators. With the <a href=\"https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern\" rel=\"nofollow noreferrer\">CRTP</a>, you can drastically outsoure the repetitive funtionality into base class templates.</p>\n\n<p>Luckily, getting started with this is easy if you allow for a dependency on <a href=\"https://www.boost.org/doc/libs/1_70_0/libs/utility/operators.htm\" rel=\"nofollow noreferrer\">Boost operators</a>:</p>\n\n<pre><code>#include <boost/operators.hpp>\n\nclass jd_int : private boost::totally_ordered<jd_int, boost::integer_arithmetic<jd_int>> {\npublic:\n jd_int() = default;\n jd_int(int i) : _i{i} { }\n\n jd_int& operator+=(jd_int jdi) { _i += jdi._i; return *this; }\n jd_int& operator-=(jd_int jdi) { _i -= jdi._i; return *this; }\n jd_int& operator*=(jd_int jdi) { _i *= jdi._i; return *this; }\n jd_int& operator/=(jd_int jdi) { _i /= jdi._i; return *this; }\n jd_int& operator%=(jd_int jdi) { _i %= jdi._i; return *this; }\n\n friend bool operator< (jd_int lhs, jd_int rhs) { return lhs._i < rhs._i; }\n friend bool operator==(jd_int lhs, jd_int rhs) { return lhs._i == rhs._i; }\n\nprivate:\n int _i;\n\n friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);\n friend std::istream& operator>>(std::istream& is, jd_int jdi);\n};\n</code></pre>\n\n<p>The base class here defines the missing comparison operators based on the two provided, same for the non-mutating arithmetic operators. Implementing these base-classes yourself is probably an excellent exercise, too.</p>\n\n<blockquote>\n <p>Is there anything I could improve on?</p>\n</blockquote>\n\n<p>If the compiler-generated special member functions are fine, don't specify them. This is the case, no need to implement the copy or move-ctor.</p>\n\n<p>And, as pointed out in the comments and by @MartinYork, not all operators that clients would expect are present. Example: shouldn't the following compile?</p>\n\n<pre><code>jd_int i = 42;\n\n+i; // this is called \"unary plus\"\n\njd_int j = -i; // ... and \"unary minus\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:45:17.280",
"Id": "219345",
"ParentId": "219323",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219340",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-28T21:20:07.210",
"Id": "219323",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"reinventing-the-wheel",
"integer"
],
"Title": "Defining a class that behaves exactly like an `int`"
} | 219323 |
<p>I am using a library that specifically needs me to provide arguments as strings one by one. However, different combinations are possible. Right now I am using a bunch of elif:</p>
<pre><code>def get_all_users(times=False, groups=False, ips=False):
"""Get a list of all users online"""
if times and groups and ips:
return ts3conn.exec_("clientlist", "times", "groups", "ips")
elif times and groups:
return ts3conn.exec_("clientlist", "times", "groups")
elif times and ips:
return ts3conn.exec_("clientlist", "times", "ips")
elif groups and ips:
return ts3conn.exec_("clientlist", "groups", "ips")
elif times:
return ts3conn.exec_("clientlist", "times")
elif groups:
return ts3conn.exec_("clientlist", "groups")
elif ips:
return ts3conn.exec_("clientlist", "ip")
else:
return ts3conn.exec_("clientlist")
</code></pre>
<p>But I am wondering if this could be improved.</p>
<p><strong>NOTE:</strong> I tried if I could use tuples but it won't work:</p>
<pre><code>stuff = (times, groups, ips)
return ts3conn.exec_("clientlist", stuff)
>>> TypeError: can only concatenate str (not "tuple") to str
</code></pre>
<p><strong>Update:</strong><br>
Library is at: <a href="https://github.com/benediktschmitt/py-ts3/blob/v2/ts3/query_builder.py" rel="nofollow noreferrer">https://github.com/benediktschmitt/py-ts3/blob/v2/ts3/query_builder.py</a> </p>
<p>The code raises error on function <code>compile</code>:</p>
<pre><code>for option in options:
res += " -" + option
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T00:56:19.537",
"Id": "423666",
"Score": "0",
"body": "To be clear, could you point us to the documentation for the `ts3conn` object, whatever it is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T00:59:59.917",
"Id": "423667",
"Score": "0",
"body": "See the updated code for documentation. ts3conn is a `ts3.query.TS3ServerConnection` object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T03:31:49.477",
"Id": "423669",
"Score": "1",
"body": "You want `ts3conn.exec_('clientlist', *stuff)` (tuple splatting). But this is off topic for CR, as this isn't about improving working code. Rather, your attempt to use tuples yields an error, which is a question that is on topic for StackOverflow."
}
] | [
{
"body": "<p>In Order to unpack a tuple you can use the <code>*</code> operator, then you just need to generate a tuple of selected options and expand it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_all_users(times=False, groups=False, ips=False):\n \"\"\"Get a list of all users online\"\"\"\n\n argument_list = ['clientlist']\n if times: \n argument_list.append('times')\n if groups: \n argument_list.append('groups')\n if ips: \n argument_list.append('ips')\n arguments = tuple(argument_list)\n\n return ts3conn.exec_(*arguments)\n</code></pre>\n\n<p>From your question I guess you already have the tuple of <code>arguments</code>, this would make the entire process considerably easier. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T10:34:34.510",
"Id": "423709",
"Score": "3",
"body": "You don't actually need to convert to a tuple; lists are unpackable in the same way. i.e. `return ts3conn.exec_(*argument_list)` would work too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T10:38:33.787",
"Id": "423710",
"Score": "0",
"body": "@HoboProber I am aware of that however I thoght I convert the list to a tuple as this is more in line with what OP asked, but good remark."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:17:19.967",
"Id": "219346",
"ParentId": "219330",
"Score": "1"
}
},
{
"body": "<p>You could use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.compress\" rel=\"nofollow noreferrer\"><code>itertools.compress</code></a> in combination with the tuple</p>\n\n<pre><code>def get_all_users(times=False, groups=False, ips=False):\n \"\"\"Get a list of all users online\"\"\"\n arguments = (\"clientlist\", \"times\", \"groups\", \"ips\")\n selectors = (True, times, groups, ips)\n\n return ts3conn.exec_(*itertools.compress(arguments , selectors))\n</code></pre>\n\n<p>or in python 3.6+, using the retained insertion order of dicts (earlier versions can use an <code>collections.ordereddict</code></p>\n\n<pre><code>def get_all_users(times=False, groups=False, ips=False):\n \"\"\"Get a list of all users online\"\"\"\n arguments = {\n \"clientlist\": True,\n \"times\": times,\n \"groups\" : groups, \n \"ips\": ips,\n }\n return ts3conn.exec_(*(key for key, value in arguments.items() if value))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:56:35.297",
"Id": "423747",
"Score": "0",
"body": "is there any reason to use orderdeddict post-3.7?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T14:58:45.260",
"Id": "423748",
"Score": "0",
"body": "the important part is the ordering of the dict. In Cpython, this is guarantued from python 3.7:`Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.`. This might not be the case for PyPy or CPython 4.0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:45:04.360",
"Id": "423769",
"Score": "0",
"body": "at least current versions of pypy have iteration order=insertion order, and unless someone finds a faster type of dict, pypy won't change."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:51:18.780",
"Id": "219360",
"ParentId": "219330",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219360",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T00:42:08.697",
"Id": "219330",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "Convert list/tuple of arguments into just arguments"
} | 219330 |
<p>I have a class which parses a .csv file and converts it into successful rows and errors. Currently I have 12 different kind of errors (mail is not valid, missing column x, row is duplicate etc.).</p>
<p>Each error has a custom message. I also need to know in other classes what kind of error a row was, so a simple string is not enough. So far I am using this error class:</p>
<pre><code><?php
namespace App\Registration\GroupUploads;
/**
* Represents all possible errors that may occur during a group upload.
*/
class Error
{
const USEREXISTS = 7;
const MAILINVALID = 1;
const SEALUSED = 2;
const MIXEDUP = 3;
// ..
protected $id;
protected $options;
/**
* Each error has a unique ID
* @param int $id
* @param array $options optional
*/
protected function __construct($id, $options = null)
{
$this->id = $id;
$this->options = $options;
}
/**
* Get Message of current object
* @return string
*/
public function getMessage()
{
switch ($this->id) {
case static::USEREXISTS:
return 'User already exists';
break;
case static::MAILINVALID:
return 'Mail is not valid';
break;
case static::SEALUSED:
return 'Sealnr is already used by other user.';
break;
case static::SEALUSED:
return 'They messed up and mixed the seals inbetween orgas.';
break;
// ...
default:
return 'No message provided for error code';
break;
}
}
/**
* Create error for an existing user
* @return bool
*/
public static function getDuplicateUserError()
{
return new static(static::USEREXISTS);
}
/**
* Check if class is duplicate user error
* @return bool
*/
public function isDuplicateUserError()
{
return $this->id == static::USEREXISTS;
}
// ...
}
</code></pre>
<p>There are 12 constants, each representing the id of a specific error. There is one method <code>getMessage()</code> which uses a <code>switch</code> with 12 cases. Then I have 12 messages of the kind <code>getErrorMessageX</code> and another 12 methods <code>isThisErrorNameX</code>. </p>
<p>I feel that this is kind of messy and redundant. Also their might be me more error cases in the future, which will bloat up the class even more.</p>
<p>I thought about creating 12 separate classes, each class named by the error name. Something like that:</p>
<pre><code><?php
namespace App\Registration\GroupUploads;
/**
* Error for existing user
*/
class UserExistsAlreadyError
{
public function getMessage()
{
return 'User already exists';
}
}
</code></pre>
<p>So instead of <code>if($error->isDuplicateUserError())</code> I would write <code>if($error instanceof UserExistsAlreadyError)</code> .</p>
<p>However, I think creating 12 different classes, where each consists only of 12 lines, is a bit too much. Is there a better solution then those two extremes? </p>
| [] | [
{
"body": "<p>This is how I ended up doing it now:</p>\n\n<pre><code><?php\n\nnamespace App\\Registration\\GroupUploads\\Errors;\n\n/**\n * Error that appear during parsing csv file\n * @var [type]\n */\nabstract class Error\n{\n const USEREXISTS = 7;\n const MAILINVALID = 1;\n const SEALUSED = 2;\n const MIXEDUP = 3;\n const QUALMISSING = 20;\n\n public $id;\n protected $msg;\n\n /**\n * Get error message\n * @return [type] [description]\n */\n public function getMsg()\n {\n return $this->msg;\n }\n\n /**\n * Error if user existed before registration\n * @param [type] $name [description]\n * @return [type] [description]\n */\n public static function userAlreadyExists($name)\n {\n $error = new Error();\n $error->id = static::USEREXISTS;\n $error->msg = \"User \" . $name . \" already exists\";\n return $error;\n }\n\n /**\n * Mail is not valid\n * @param [type] $mail [description]\n * @return [type] [description]\n */\n public static function mailInvalid($mail)\n {\n $error = new Error();\n $error->id = static::MAILINVALID;\n $error->msg = \"The mail \" . $mail . \" is not valid\";\n return $error;\n }\n\n //..\n}\n</code></pre>\n\n<p>This way the <code>getMsg</code> method is short. Also adding a new error only requires to add one method instead of two (and no modification of the <code>getMsg</code> function).</p>\n\n<p>To identify an error I call <code>if($error->id == Error::USEREXISTS){...}</code>.</p>\n\n<p>Having the id was quite important, because I wanted to store the errors in DB.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T09:20:47.543",
"Id": "219354",
"ParentId": "219344",
"Score": "1"
}
},
{
"body": "<p>Its better to use factory pattern for creating custom errors. I'm working on Java and following Java code might be helpful:</p>\n\n<pre><code>class CsvException extends Exception {\n public static final int USEREXISTS = 7;\n public static final int MAILINVALID = 1;\n public static final int SEALUSED = 2;\n public static final int MIXEDUP = 3;\n\n public static final CsvException createException(int type) {\n CsvException exc = null;\n switch (type) {\n case CsvException.USEREXISTS:\n exc = new UserExistException();\n break;\n\n case CsvException.MAILINVALID:\n exc = new MailInvalidException();\n break;\n\n case CsvException.SEALUSED:\n exc = new SealUsedException();\n break;\n\n case CsvException.MIXEDUP:\n exc = new MixedUpException();\n break;\n\n default:\n exc = new CsvException();\n break;\n }\n return exc;\n }\n\n @Override\n public String getMessage() {\n return \"A CSV Exception occurred!\";\n }\n}\n\nclass UserExistException extends CsvException {\n\n @Override\n public String getMessage() {\n return \"User already exists!\";\n }\n\n}\n\nclass MailInvalidException extends CsvException {\n @Override\n public String getMessage() {\n return \"Invalid email ID!\";\n }\n}\n\nclass SealUsedException extends CsvException {\n @Override\n public String getMessage() {\n return \"Seal is already used!\"; //I'm assuming message and this class by exception type\n }\n}\n\nclass MixedUpException extends CsvException {\n @Override\n public String getMessage() {\n return \"Mixed up!\";\n }\n}\n</code></pre>\n\n<p>And you can use above exception factory like below:</p>\n\n<pre><code> ...\n\n public void checkMail() throws MailInvalidException {\n //If invalid email ID\n throw (MailInvalidException)CsvException.createException(CsvException.MAILINVALID);\n }\n\n public void checkUser() throws UserExistException {\n //If user already exists\n throw (UserExistException)CsvException.createException(CsvException.MAILINVALID);\n }\n\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T11:35:56.540",
"Id": "423715",
"Score": "0",
"body": "I believe these objects are not intended to be thrown"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T12:26:40.220",
"Id": "423726",
"Score": "1",
"body": "You should add more details about your code because it's not clear what this code is about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T03:56:40.097",
"Id": "423816",
"Score": "0",
"body": "@t3chb0t, The first code section contains required classes for exception, the 2nd code section shows a small example of use of Exception factory. You can read more about factory pattern here : https://www.geeksforgeeks.org/design-patterns-set-2-factory-method/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T11:12:15.407",
"Id": "219357",
"ParentId": "219344",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T07:41:12.480",
"Id": "219344",
"Score": "0",
"Tags": [
"php",
"object-oriented",
"error-handling"
],
"Title": "Custom Error Classes in OOP"
} | 219344 |
<p>I'm doing a application to work with PDF and TIFF files.
To divide them, the user opens the file or folder (if it is a folder, it gets all the files inside) and the app splits the file, getting a tiny image (thumbnail) in JPG format. Then it creates a ListViewItem adding the thumbnail, the name and the size of the file.</p>
<p>But it takes too long (1:40min) with a PDF with 68 pages, so if a larger PDF is opened, it will take too long.</p>
<p><a href="https://i.stack.imgur.com/DPhjw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DPhjw.png" alt="the time for 68 pages"></a></p>
<p>So I wish someone could say where can I improve my code so it doesn't take that long.</p>
<h2>CODE</h2>
<pre><code>public void SplitPDF2(string input)
{
try
{
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(input);
iTextSharp.text.pdf.PdfReader.unethicalreading = true;
string name = Path.GetFileNameWithoutExtension(input);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
using (MemoryStream ms = new MemoryStream())
{
//get thumbnail from 1st page-----------------------------------------------------
using (var document = PdfiumViewer.PdfDocument.Load(input))
{
var image = document.Render(i - 1, 60, 84, 300, 300, true);
image.Save(ms, ImageFormat.Jpeg);
thumbnails.Images.Add(j.ToString(), image);
image.Dispose();
}
//split pdf-----------------------------------------------------------------------
string p = AppDomain.CurrentDomain.BaseDirectory + "temporario\\" + name + " - Pagina " + i + ".PDF";
using (Stream outputStream = new FileStream(p, FileMode.Create))
{
Document doc = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, outputStream);
doc.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
PdfImportedPage importedpage = pdfWriter.GetImportedPage(reader, i);
iTextSharp.text.Rectangle mediabox = reader.GetPageSize(i);
doc.SetPageSize(mediabox);
doc.NewPage();
pdfContentByte.AddTemplate(importedpage, 0, 0);
doc.Close();
doc.Dispose();
pdfWriter.Dispose();
}
//in the end it will add the thumbnail, the name and the size of the file to the ListView
FileInfo f = new FileInfo(p);
ListViewItem _item1 = new ListViewItem();
_item1.ImageKey = j.ToString(); //image
_item1.SubItems.Add(name + " - Pagina " + i + ".PDF"); //name
_item1.SubItems.Add(f.Length.ToString()); //size
lista2.Items.Add(_item1);
j++;
}
}
reader.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:40:10.537",
"Id": "423694",
"Score": "3",
"body": "Why are you saving the images on the disk and not working with them in memory? You seem to mix a couple of principles there. `using` and `Dispose` at the same time, no `using` in other cases... quite a mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:43:59.483",
"Id": "423695",
"Score": "0",
"body": "How should I do it using the memory? Using a MemoryStream? @t3chb0t"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T10:19:32.640",
"Id": "423706",
"Score": "0",
"body": "@t3chb0t Could you help me organizing and \"unmessing\" my code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T16:43:45.010",
"Id": "453449",
"Score": "0",
"body": "Welcome! You might want to take a look at profiling: https://docs.microsoft.com/en-us/visualstudio/profiling/?view=vs-2019"
}
] | [
{
"body": "<p>This code leaves a bunch of open questions, minor ones:<br>\n- <code>SplitPDF2(string input)</code> what has been/happened to <code>SplitPDF()</code> or <code>SplitPDF1()</code>?<br>\n- what is <code>lista2</code>? </p>\n\n<p>Non-minor: </p>\n\n<ul>\n<li>Document/comment your source code. In the code.</li>\n<li>Preparing thumbnails and splitting a PDF into separate-file-per-page do neither sound nor look related:<br>\nDo not put/implement both in a single procedure </li>\n<li>I can't seem to see a purpose in saving each thumbnail rendered into a <code>MemoryStream ms</code> that doesn't get used otherwise. </li>\n<li>You instantiate one and only one <code>iTextSharp.text.pdf.PdfReader(input)</code> for each input:<br>\nDo the same for PdfiumViewer.PdfDocument</li>\n<li><code>it will add the thumbnail</code> I don't see that.</li>\n</ul>\n\n<p>Overall, I'm left mistrusting <em>writing file-per-page PDF</em> to be a useful step in accomplishing the larger task at hand.<br>\n<code>wish someone could say where [to improve the] code so it doesn't take that long</code> my crystal ball is dull, but profiling/timeit() might help.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-13T16:08:38.770",
"Id": "453637",
"Score": "0",
"body": "Thank you for your answer and I’m no longer working with that... since I am portuguese, some variables can be strange to you, such as “lista2”, my appologies. If I remember it well, the other SplitPDF() functions were with another libraries. I’m sure that who uses your answer to resolve their problems, it will help them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-12T15:05:07.457",
"Id": "232252",
"ParentId": "219349",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T08:36:52.340",
"Id": "219349",
"Score": "6",
"Tags": [
"c#",
"performance",
"beginner",
"winforms",
"pdf"
],
"Title": "Spliting PDF and get thumbnail while adding it to a ListView"
} | 219349 |
<p>This code belongs to a contest. I tried to apply the range of data to a std::map. The contest system however warns me that the implementation of the <code>assign</code> function is not valid. I don't know which part of the code is written incorrectly, hence the system doesn't reveal any details except that the implementation is erroneous.</p>
<hr>
<p><strong>Edit:</strong> I also added the test class that I used for testing the <code>interval_map</code> class. I tried to test every possible aspect of what could possibly go wrong. The test runs without any problem.</p>
<pre class="lang-cpp prettyprint-override"><code> void assign(unsigned char first, unsigned char last, unsigned char value)
{
test();
interval_map::assign(first, last, value);
for (int i = first; i < last; ++i)
vector_cont[i] = value;
test();
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:26:17.087",
"Id": "423865",
"Score": "6",
"body": "Do you have a written description of the requirements ? If you could add them to the question them that would be great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-08T14:52:36.647",
"Id": "424905",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
}
] | [
{
"body": "<p>It is possible the interview failed because of the 4th line in the code:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Code such as a template class will generally be in a header file, and it is very bad practice to have the <code>using namespace std;</code> within a header file, it breaks all the reasons for having namespaces. What happens if someone wants to use this class as a base class but needs to write special <code>cin</code> and <code>cout</code> overloads, or overload any of the library functions provided by <code>namespace std</code>?</p>\n\n<p>In general professions will never default to the <code>std namespace</code>. Namespaces are used to prevent collisions of functions see this <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stackoverflow question</a>.</p>\n\n<p>The second problem with <code>using namespace std</code> is that it isn't necessary, the code compiles without it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:43:30.327",
"Id": "423881",
"Score": "1",
"body": "@Mehrzad I suggest mentioning this in the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:53:36.707",
"Id": "219361",
"ParentId": "219359",
"Score": "3"
}
},
{
"body": "<p>Quite frankly it seems that you did not do what was asked from you.</p>\n\n<p>The text above <code>assign</code> gives you the requirements</p>\n\n<pre><code> // Assign value val to interval [keyBegin, keyEnd).\n // Overwrite previous values in this interval.\n // Conforming to the C++ Standard Library conventions, the interval\n // includes keyBegin, but excludes keyEnd.\n // If !( keyBegin < keyEnd ), this designates an empty interval,\n // and assign must do nothing.\n</code></pre>\n\n<p>So you have to find all elements in the map that are in the range [keyBegin, keyEnd) and assign val to them. Then you should insert <code>keyBegin</code> and <code>keyEnd</code> with the value val into the map.</p>\n\n<p>Actually you are quite close to what was asked with the calls to <code>lower_bound</code></p>\n\n<pre><code> void assign(K const& keyBegin, K const& keyEnd, V const& val) {\n // keyBegin < keyEnd indicates an empty interval, so the function simply returns\n if (!(keyBegin < keyEnd))\n return;\n\n ....\n }\n</code></pre>\n\n<p>This is already a problem as the comment is incorrect. It should read <code>keyEnd < keyBegin</code></p>\n\n<pre><code> auto begin_lower_iter = m_map.lower_bound(keyBegin);\n auto end_upper_iter = m_map.upper_bound(keyEnd);\n</code></pre>\n\n<p>The first call is obviously correct. However, the second call is the wrong one. <code>upper_bound</code> returns the first element that is <em>greater</em> than the key. Now consider if keyEnd is in the map. As the interval is half opened you would have to decrement twice in that case and once if it is not in the map.</p>\n\n<p>Rather than that you can simply use <code>lower_bound</code> here too</p>\n\n<pre><code> auto begin_iter = m_map.lower_bound(keyBegin);\n auto end_iter = m_map.lower_bound(keyEnd);\n</code></pre>\n\n<p>Now we have to consider the bounds. First you should check, whether keyBegin is already in the map. Otherwise you should insert it so that the left boundary is inclusive. Note that in that case we can use begin_iter as a hint so that the complexity is an amortized constant</p>\n\n<pre><code> if (begin_iter->first != keyBegin) {\n begin_iter = m_map.insert(begin_iter, val);\n // The element at begin_iter already has the correct value so increment \n ++begin_iter;\n }\n</code></pre>\n\n<p>It is slightly different for the upper boundary, as that is exclusive. As far as i understand it, that means that you should insert an element with the value the interval had previously so that it is the inclusive left border of the new interval.</p>\n\n<p>If end_iter is at keyEnd it already has the correct value and we do not have to do anything. However if it is not in the map, then we have to insert the value of the previous element at position keyEnd</p>\n\n<pre><code> if (end_iter->first != keyEnd) {\n V const& oldVal = std::prev(end_iter, 1)->second; \n end_iter = m_map.insert(end_iter, oldVal);\n }\n</code></pre>\n\n<p>Now to a completely different topic. As you might have seen insert returns an updated iterator. While there is no iterator invalidation in std::map,i would not risk it. So the insertion should happen right after you get the iterator.</p>\n\n<pre><code> auto begin_iter = m_map.lower_bound(keyBegin);\n if (begin_iter->first != keyBegin) {\n begin_iter = m_map.insert(begin_iter, val);\n // The element at begin_iter already has the correct value so \n ++begin_iter;\n }\n\n auto end_iter = m_map.lower_bound(keyEnd);\n if (end_iter->first != keyEnd) {\n V const& oldVal = std::prev(end_iter, 1)->second; \n end_iter = m_map.insert(end_iter, oldVal);\n }\n</code></pre>\n\n<p>Also this is still not correct. Lets assume begin_iter was not less that the first element in the map smaller than <code>keyEnd</code>. In that case we would have overwritten the original value of the -larger- interval. Therefore, the insertion of the upper bound needs to happen first.</p>\n\n<p>Now that we handeled the borders, we should update the elements int the range</p>\n\n<pre><code> while(begin_iter != end_iter) {\n begin_iter->second = val;\n ++begin_iter;\n }\n</code></pre>\n\n<p>Finally, there is still an elephant in the room. While the whole file seems to be not fully consistent, the arguments to the function are camelCase. Yet you named your variables using snake_case. For me that is already a minus as you do not adopt to the existing codebase and inconsistent naming is a constant source of confusion and a huge drain on mental capacity.</p>\n\n<p>So lets put it together</p>\n\n<pre><code> void assign(K const& keyBegin, K const& keyEnd, V const& val) {\n // keyBegin < keyEnd indicates an empty interval, so the function simply returns\n if (!(keyBegin < keyEnd)) {\n return;\n }\n\n // Search for the upper bound and if necessary include a border element\n // with the value of the old interval\n auto endIter = m_map.lower_bound(keyEnd);\n if (endIter->first != keyEnd) {\n // As the intervals are half open we need to take the value of the left element and insert it at keyEnd \n V const& oldVal = std::prev(endIter, 1)->second; \n endIter = m_map.insert(endIter, oldVal);\n }\n\n // Search for the lower bound and if necessary include the element\n auto beginIter = m_map.lower_bound(keyBegin);\n if (beginIter->first != keyBegin) {\n beginIter = m_map.insert(beginIter, val);\n // The element at begin_iter already has the correct value so \n ++beginIter;\n }\n\n // Update the values within the range [beginIter, endIter)\n while(beginIter != endIter) {\n beginIter->second = val;\n ++beginIter;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T20:42:46.370",
"Id": "219462",
"ParentId": "219359",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T13:14:05.223",
"Id": "219359",
"Score": "6",
"Tags": [
"c++",
"interview-questions",
"c++17",
"hash-map",
"interval"
],
"Title": "How to set an interval to std::map"
} | 219359 |
<p>This is the problem:</p>
<blockquote>
<p>You notice that the device repeats the same frequency change list over
and over. To calibrate the device, you need to find the first
frequency it reaches twice.</p>
<p>For example, using the same list of changes above, the device would
loop as follows:
- Current frequency 0, change of +1; resulting frequency 1.
- Current frequency 1, change of -2; resulting frequency -1.
- Current frequency -1, change of +3; resulting frequency 2.
- Current frequency 2, change of +1; resulting frequency 3.
- (At this point, the device continues from the start of the list.)
- Current frequency 3, change of +1; resulting frequency 4.
- Current frequency 4, change of -2; resulting frequency 2, which has already been seen.</p>
<p>In this example, the first frequency reached twice is 2. Note that
your device might need to repeat its list of frequency changes many
times before a duplicate frequency is found, and that duplicates
might be found while in the middle of processing the list.</p>
<p>Here are other examples:
- +1, -1 first reaches 0 twice.
- +3, +3, +4, -2, -4 first reaches 10 twice.
- -6, +3, +8, +5, -6 first reaches 5 twice.
- +7, +7, -2, -7, -4 first reaches 14 twice.</p>
<p>What is the first frequency your device reaches twice?</p>
<p>Here is my implementation in C, why does it not work. It loops through the > whole list but never finds a match.</p>
</blockquote>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int main(void){
int sum = 0;
int q = 0;
int len = 0;
char buffer[20];
int val = 0;
int list[2000];
int *plist = list;
FILE *pFile = NULL;
pFile = fopen("input.txt", "r");
if (pFile == NULL){
printf("file failed to open\n");
return -1;
}
while((fgets(buffer, 20, pFile)) != NULL){ //store all the sums (calculated frequncies induced by changes) in an array called list
sum += atoi(buffer);
*plist = sum;
++plist;
++len;
}
fclose(pFile);
pFile = NULL;
plist = list;
printf("length is %d\n\n", len);
//below will now iterate through the loop and treat it as circular, so up to the element before current element
for(int i = 0; i < len && val == 0; ++i){
for(int j = i + 1; j < len + i; ++j){
if (j >= len)
q = abs(len - j);
else
q = j;
printf("here is i: %d\there is j: %d\n", list[i], list[q]);
if(list[i] == list[q]){
val = list[i];
break;
}
}
}
printf("the first frequency is %d\n", val);
getchar();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:34:43.337",
"Id": "423755",
"Score": "0",
"body": "Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing *what* your code does. Once the code does what you want, we would love to help you do the same thing in a cleaner way! Please see our [help center](/help/on-topic) for more information."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:31:33.740",
"Id": "219370",
"Score": "1",
"Tags": [
"c"
],
"Title": "Advent of Code 2018 Day 1 Part 2"
} | 219370 |
<p>I have a vba code which takes data from SQL database and dumps it into excel. I see that my query should extract approximately total of 120k records. I monitored this activity and learnt that even after 8 hours of my office time, the query is successful in extracting barely 70k records.</p>
<p>This is frustrating me as I am totally new to VBA. Can you guys help me here by modifying my code?</p>
<pre><code> Macro1
Private Sub Macro1()
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\kursekar\Documents\Work\Apps\ReferralStrApp\StdztnRefRepTrial.xlsx")
objExcel.Visible = True
Dim Conn
Dim RS
Dim SQL
SQL = "WITH cte_REFERRALS_REPORTS(referralnum, refer_from, refer_from_name, refer_from_id, refer_to, refer_to_name, refer_to_id) AS (SELECT referralnum, refer_from, CASE WHEN refer_from_id = 'R' THEN RdicF.refname WHEN refer_from_id = 'P' THEN PdicF.provname END AS refer_from_name, refer_from_id, refer_to, "
SQL = SQL & "CASE WHEN refer_to_id = 'R' THEN RdicT.refname WHEN refer_to_id = 'P' THEN PdicT.provname END AS refer_to_name, refer_to_id FROM referral_t r Left Join refcode_t RdicF ON r.refer_from = CASE WHEN r.refer_from_id='R' THEN RdicF.refcode ELSE NULL END Left Join refcode_t RdicT ON r.refer_to = CASE WHEN r.refer_to_id = 'R' THEN RdicT.refcode ELSE NULL END "
SQL = SQL & "Left Join provcode_t PdicF ON r.refer_from = CASE WHEN r.refer_from_id = 'P' THEN PdicF.provcode ELSE NULL END Left Join provcode_t PdicT ON r.refer_to = CASE WHEN r.refer_to_id = 'P' THEN PdicT.provcode ELSE NULL END ) SELECT chgslipno , a.acctno, patfname, patlname, appt_date, a.enccode, pr.provname "
SQL = SQL & ",a.provcode, rfc.refname, a.refcode, r1.refer_from as r1_ref_from, r1.refer_from_id as r1_ref_from_id, r1.refer_from_name as r1_ref_from_name, a.referral1 as r1_refnum, r2.refer_from as r2_ref_from, r2.refer_from_id as r2_ref_from_id, r2.refer_from_name as r2_ref_from_name,a.referral2, prgrc.provgrpdesc,s.specdesc, a.prov_dept, pos.posdesc,pr.cred "
SQL = SQL & "FROM apptmt_t a Left JOIN patdemo_t p ON a.acctno = p.acctno LEFT JOIN provcode_t pr ON pr.provcode = a.provcode LEFT JOIN refcode_t rfc ON a.refcode = rfc.refcode LEFT JOIN (SELECT*FROM cte_REFERRALS_REPORTS) r1 ON a.referral1 = r1.referralnum LEFT JOIN (SELECT*FROM cte_REFERRALS_REPORTS) r2 "
SQL = SQL & "on a.referral2 = r2.referralnum LEFT JOIN provgrpprov_t prgrpr on a.provcode = prgrpr.provcode LEFT JOIN provgrpcode_t prgrc on prgrpr.provgrpcode = prgrc.provgrpcode LEFT JOIN specialty_t s on pr.speccode = s.speccode LEFT JOIN poscode_t pos on a.poscode = pos.poscode "
SQL = SQL & "WHERE UPPER(a.enccode) in ('CON','APE','COB','CONZ','HAC','HFUI','MMN','NCG','NCHF','NCPF','NHFU','NMC','NOB','NP','NP15','NPE','NPI','NPOV','NPS','NPSV','NPV','OVN','IMC','NP30') AND UPPER(a.appt_status)='ARR' AND appt_date >= '2017-01-01' "
SQL = SQL & "ORDER BY a.acctno"
Set Conn = CreateObject("ADODB.Connection")
Conn.Open = "Provider=SQLOLEDB.1;Password='25LaurelRoad';User ID='CPSMDIT\kursekar';Data Source='analyzer';Initial Catalog='analyzer_str';Integrated Security=SSPI; Persist Security Info=True;"
Set RS = Conn.Execute(SQL)
Set Sheet = objWorkbook.ActiveSheet
Sheet.Activate
Dim R
R = 2
While RS.EOF = False
Sheet.Cells(R, 1).Value = RS.Fields(0)
Sheet.Cells(R, 2).Value = RS.Fields(1)
Sheet.Cells(R, 3).Value = RS.Fields(2)
Sheet.Cells(R, 4).Value = RS.Fields(3)
Sheet.Cells(R, 5).Value = RS.Fields(4)
Sheet.Cells(R, 6).Value = RS.Fields(5)
Sheet.Cells(R, 7).Value = RS.Fields(6)
Sheet.Cells(R, 8).Value = RS.Fields(7)
Sheet.Cells(R, 9).Value = RS.Fields(8)
Sheet.Cells(R, 10).Value = RS.Fields(9)
Sheet.Cells(R, 11).Value = RS.Fields(10)
Sheet.Cells(R, 12).Value = RS.Fields(11)
Sheet.Cells(R, 13).Value = RS.Fields(12)
Sheet.Cells(R, 14).Value = RS.Fields(13)
Sheet.Cells(R, 15).Value = RS.Fields(14)
Sheet.Cells(R, 16).Value = RS.Fields(15)
Sheet.Cells(R, 17).Value = RS.Fields(16)
Sheet.Cells(R, 18).Value = RS.Fields(17)
Sheet.Cells(R, 19).Value = RS.Fields(18)
Sheet.Cells(R, 20).Value = RS.Fields(19)
Sheet.Cells(R, 21).Value = RS.Fields(20)
Sheet.Cells(R, 22).Value = RS.Fields(21)
Sheet.Cells(R, 23).Value = RS.Fields(22)
RS.MoveNext
R = R + 1
Wend
RS.Close
Conn.Close
Application.DisplayAlerts = False
'Release memory
Set objFSO = Nothing
Set objFolder = Nothing
Set objFile = Nothing
ActiveWorkbook.Save
'objWorkbook.SaveAs Filename:="C:\\Users\kursekar\Documents\Work\Dailytasks\January\ReferralStrApp\StdztnRefRepTrial.xlsx", FileFormat:=51
Application.DisplayAlerts = True
objWorkbook.Close
objExcel.Workbooks.Close
objExcel.Quit
Workbooks.Close
Set objExcel = Nothing
MsgBox ("Saved")
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:49:52.893",
"Id": "423757",
"Score": "2",
"body": "Consider `Range.CopyFromRecordset` instead of writing one single cell at a time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:51:33.980",
"Id": "423758",
"Score": "0",
"body": "Hi brother !!! Thank you very much for your help. It worked like a magic. Here is my new pasted code which works !!!!!! Thank you so muach mahn. Saved the day !!! hehehe. Take Care. God Bless You."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:54:18.647",
"Id": "423759",
"Score": "1",
"body": "For a VBA new user I recommend one of the excel programming books by John Walkenbach at http://spreadsheetpage.com/. That is how I learned to program VBA."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:56:14.400",
"Id": "423760",
"Score": "0",
"body": "Yes. I have started VBA 3 weeks back by reading documentations. My internship is requiring this skill which I was totally not even asked in interview. lol. I know some C#. So any recommendations for books and websites are warmly and cheerfully welcomed. Please help me know more bros."
}
] | [
{
"body": "<p>As per the comment from Mathieu, I modified the code. The code is given below; Works like a charm !!! barely 3 minutes and entire process is done. Thank you for your all help. This is being pasted for information purpose to others. I am new to VBA so its for other beginners like me. Take Care all. BYE !!!!</p>\n\n<pre><code> Macro1\nPrivate Sub Macro1()\n\nSet objExcel = CreateObject(\"Excel.Application\")\nSet objWorkbook = objExcel.Workbooks.Open(\"C:\\Users\\kursekar\\Documents\\Work\\Apps\\ReferralStrApp\\StdztnRefRepTrial.xlsx\")\nobjExcel.Visible = False\nSet Conn = CreateObject(\"ADODB.Connection\")\nSet RS = CreateObject(\"ADODB.Recordset\") \nDim SQL\nDim Sconnect\nSconnect = \"Provider=SQLOLEDB.1;Password='25LaurelRoad';User ID='CPSMDIT\\kursekar';Data Source='analyzer';Initial Catalog='analyzer_str';Integrated Security=SSPI; Persist Security Info=True;\"\nConn.Open Sconnect\n\nSQL = \"WITH cte_REFERRALS_REPORTS(referralnum, refer_from, refer_from_name, refer_from_id, refer_to, refer_to_name, refer_to_id) AS (SELECT referralnum, refer_from, CASE WHEN refer_from_id = 'R' THEN RdicF.refname WHEN refer_from_id = 'P' THEN PdicF.provname END AS refer_from_name, refer_from_id, refer_to, \"\nSQL = SQL & \"CASE WHEN refer_to_id = 'R' THEN RdicT.refname WHEN refer_to_id = 'P' THEN PdicT.provname END AS refer_to_name, refer_to_id FROM referral_t r Left Join refcode_t RdicF ON r.refer_from = CASE WHEN r.refer_from_id='R' THEN RdicF.refcode ELSE NULL END Left Join refcode_t RdicT ON r.refer_to = CASE WHEN r.refer_to_id = 'R' THEN RdicT.refcode ELSE NULL END \"\nSQL = SQL & \"Left Join provcode_t PdicF ON r.refer_from = CASE WHEN r.refer_from_id = 'P' THEN PdicF.provcode ELSE NULL END Left Join provcode_t PdicT ON r.refer_to = CASE WHEN r.refer_to_id = 'P' THEN PdicT.provcode ELSE NULL END ) SELECT chgslipno , a.acctno, patfname, patlname, appt_date, a.enccode, pr.provname \"\nSQL = SQL & \",a.provcode, rfc.refname, a.refcode, r1.refer_from as r1_ref_from, r1.refer_from_id as r1_ref_from_id, r1.refer_from_name as r1_ref_from_name, a.referral1 as r1_refnum, r2.refer_from as r2_ref_from, r2.refer_from_id as r2_ref_from_id, r2.refer_from_name as r2_ref_from_name,a.referral2, prgrc.provgrpdesc,s.specdesc, a.prov_dept, pos.posdesc,pr.cred \"\nSQL = SQL & \"FROM apptmt_t a Left JOIN patdemo_t p ON a.acctno = p.acctno LEFT JOIN provcode_t pr ON pr.provcode = a.provcode LEFT JOIN refcode_t rfc ON a.refcode = rfc.refcode LEFT JOIN (SELECT*FROM cte_REFERRALS_REPORTS) r1 ON a.referral1 = r1.referralnum LEFT JOIN (SELECT*FROM cte_REFERRALS_REPORTS) r2 \"\nSQL = SQL & \"on a.referral2 = r2.referralnum LEFT JOIN provgrpprov_t prgrpr on a.provcode = prgrpr.provcode LEFT JOIN provgrpcode_t prgrc on prgrpr.provgrpcode = prgrc.provgrpcode LEFT JOIN specialty_t s on pr.speccode = s.speccode LEFT JOIN poscode_t pos on a.poscode = pos.poscode \"\nSQL = SQL & \"WHERE UPPER(a.enccode) in ('CON','APE','COB','CONZ','HAC','HFUI','MMN','NCG','NCHF','NCPF','NHFU','NMC','NOB','NP','NP15','NPE','NPI','NPOV','NPS','NPSV','NPV','OVN','IMC','NP30') AND UPPER(a.appt_status)='ARR' AND appt_date >= '2017-01-01' \"\nSQL = SQL & \"ORDER BY a.acctno\"\n\nSet Sheet = objWorkbook.ActiveSheet\nSheet.Activate\n\nRS.Open SQL, Conn\n Sheet.Range(\"A2\").CopyFromRecordset RS\n\nRS.Close\nConn.Close\n\nobjExcel.DisplayAlerts = False\n'Release memory\n'Set objFSO = Nothing\n'Set objFolder = Nothing\n'Set objFile = Nothing\nobjWorkbook.Save\nobjExcel.DisplayAlerts = True\nobjWorkbook.Close\nobjExcel.Workbooks.Close\nobjExcel.Quit\n\n'Set objExcel = Nothing\nMsgBox (\"Saved\")\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:54:28.557",
"Id": "219378",
"ParentId": "219371",
"Score": "3"
}
},
{
"body": "<p><code>Range.CopyFromRecordset</code> only addresses the [massive] performance issue of traversing an entire recordset row by agonizing row and writing it to a worksheet cell by agonizing cell - all while Excel painstakingly repaints itself every time, fires <code>Worksheet.Change</code> events, and evaluates whether or not recalculations should be happening... <em>between every single worksheet write</em>.</p>\n\n<p>Whenever you programmatically interact with a worksheet, it's a good idea to turn off screen updating, event firing, and make calculations manual to avoid this overhead:</p>\n\n<pre><code>With objExcel\n .ScreenUpdating = False\n .EnableEvents = False\n .Calculation = xlCalculationManual\nEnd With\n</code></pre>\n\n<p>And then, don't forget to toggle this <code>Application</code> state back on, and handle runtime errors to make sure it's toggled back on regardless of whether an error occurs or not. Note that any code that involves I/O or a database connection, <em>should</em> handle run-time errors. Right now if the connection times out or if there's a syntax error in that SQL statement, the error is unhandled. I'd recommend something like this:</p>\n\n<pre><code>Public Sub DoSomething()\n On Error GoTo CleanFail\n '...do stuff...\nCleanExit:\n '...clean up: restore state, close open connections, etc...\n Exit Sub\nCleanFail:\n 'log error, warn user, etc.\n Resume CleanExit\nEnd Sub\n</code></pre>\n\n<p>You are not consistently declaring your variables: the fact that the code can even compile & run with undeclared variables, means you haven't specified <code>Option Explicit</code> at the top of the module. This is a very common beginner trap: VBA is very permissive and lets you do this - doesn't mean you <em>should</em> though. By specifying <code>Option Explicit</code> at the top of every module, you force yourself to declare all variables - which turns a typo into a compile error instead of a very hard-to-diagnose run-time bug.</p>\n\n<p>Activating the active sheet is redundant:</p>\n\n<blockquote>\n<pre><code>Set Sheet = objWorkbook.ActiveSheet\nSheet.Activate\n</code></pre>\n</blockquote>\n\n<p>Rule of thumb, you pretty much <em>never</em> need to <code>Activate</code> anything - especially if you mean to work \"in the background\" with a hidden application instance. Speaking of which...</p>\n\n<blockquote>\n<pre><code>Set objExcel = CreateObject(\"Excel.Application\")\n</code></pre>\n</blockquote>\n\n<p>You're hosted in Excel: the Excel type library <em>has</em> to be referenced. There is no reason whatsoever to use <code>CreateObject</code> for this. The <code>New</code> keyword is used for creating objects for which the type is known at compile-time:</p>\n\n<pre><code>Set objExcel = New Excel.Application\n</code></pre>\n\n<p>Avoid <code>CreateObject</code> whenever possible: it's hitting the Windows Registry, looking up the provided ProgID string, then finds the corresponding class, loads the type from the library, creates an instance, and returns it. Between this:</p>\n\n<blockquote>\n<pre><code>Set RS = Conn.Execute(SQL)\n</code></pre>\n</blockquote>\n\n<p>And this:</p>\n\n<blockquote>\n<pre><code>Set RS = CreateObject(\"ADODB.Recordset\") \nRS.Open SQL, Conn\n</code></pre>\n</blockquote>\n\n<p>I take <code>Conn.Execute</code> any day. So you're also using late binding for ADODB:</p>\n\n<blockquote>\n<pre><code>Dim Conn\nDim RS\nDim SQL\n</code></pre>\n</blockquote>\n\n<p><code>Conn</code> and <code>RS</code> should be declared <code>As Object</code>, and <code>SQL</code> should be <code>As String</code>. As it stands, all 3 are implicit <code>Variant</code>. But ideally, you would be referencing the ADODB library, and declare <code>Conn As ADODB.Connection</code> and <code>RS As ADODB.Recordset</code>, creating the connection with <code>Set Conn = New ADODB.Connection</code>.</p>\n\n<p>Note that <code>While...Wend</code> loops were made obsolete when <code>Do While...Loop</code> was introduced, a long time ago: avoid <code>While...Wend</code> - these loops can't be exited without a <code>GoTo</code> jump, but you can early-exit a <code>Do</code> loop with <code>Exit Do</code>.</p>\n\n<p>Watch out for implicit <code>ByVal</code> expressions here:</p>\n\n<blockquote>\n<pre><code>MsgBox (\"Saved\")\n</code></pre>\n</blockquote>\n\n<p>This takes the <code>\"Saved\"</code> string literal, evaluates it as an expression (yielding... a string literal), and passes the result <code>ByVal</code> to the <code>MsgBox</code> function. The parentheses are redundant and harmful!</p>\n\n<pre><code>MsgBox \"Saved\"\n</code></pre>\n\n<p>Note that this wouldn't compile:</p>\n\n<pre><code>MsgBox (\"Saved\", vbOkOnly)\n</code></pre>\n\n<p>Because <code>(\"Saved\", vbOkOnly)</code> isn't a legal expression that can be evaluated.</p>\n\n<p>Lastly, note that a lot of everything mentioned above (and more) would have been picked up by the <em>Code Inspections</em> of <a href=\"http://www.github.com/rubberduck-vba/Rubberduck\" rel=\"noreferrer\">Rubberduck</a>, a VBIDE add-in open-source project I contribute to (along with a merry bunch of fellow VBA reviewers - star us on GitHub if you like!) - I'm obviously biased, but I can't recommend it enough. The <a href=\"https://rubberduckvba.wordpress.com/\" rel=\"noreferrer\">project's blog</a> is also a valuable resource for various VBA topics, from late binding to object-oriented programming and modern best-practices.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:59:04.303",
"Id": "423773",
"Score": "0",
"body": "Hi Mathieu. Thanks very much for such detailed post. i shall research this and write a new code and post it here for you guys to review it and then probably you can criticise it further for me to come up with a more sophisticated work. I need to deploy this in production so I wish to be as fine tuned as I could be. Thanks once again. Really appreciate all the details you mentioned here for me !!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:01:27.573",
"Id": "423775",
"Score": "0",
"body": "@KaustubhUrsekar that's what this site is all about! =) don't hesitate to post a follow-up with the updated code, in a new \"question\" (I'd recommend reviewing Rubberduck inspections first though)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:08:25.510",
"Id": "423776",
"Score": "0",
"body": "Sure !!. I shall take your description as an answer on this post brother. I shall surely research the stuff you told me and get back to you in a new question. Feeling Happy !! hehehe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:27:39.630",
"Id": "423780",
"Score": "0",
"body": "BTW Rubberduck is written in C#, if you're ever looking for a fun & challenging OSS project to contribute to - we need all the help we can get!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:47:35.807",
"Id": "423781",
"Score": "0",
"body": "Yes sure mahn. I have developed webpages and websites with C# and .net to be precise. So I would really love to be a \"strong\" no matter how small or big part of something new and more. Would surely hone my skills with you guys. I wish to learn as much i could. I stepped into computer science field just 4 months back and I see so much in here !!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:57:20.003",
"Id": "423782",
"Score": "0",
"body": "@KaustubhUrsekar come to our [dev chat!](https://chat.stackexchange.com/rooms/14929/vba-rubberducking)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:46:58.980",
"Id": "219383",
"ParentId": "219371",
"Score": "13"
}
},
{
"body": "<p>I would try using QueryTable feature, which can take either a Recordset or ConnectionString + SQL. For the sample code below, I have an SQLite database file next to my Excel file. Otherwise, there are no other dependencies.</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub QueryTableSourceAdoRecordSet()\n Dim Driver As String\n Dim Options As String\n Dim Database As String\n\n Dim adoConnStr As String\n Dim qtConnStr As String\n Dim SQL As String\n Dim QTName As String\n\n Database = ThisWorkbook.Path + "\\" + "ADODBTemplates.db"\n Driver = "SQLite3 ODBC Driver"\n Options = "SyncPragma=NORMAL;LongNames=True;NoCreat=True;FKSupport=True;OEMCP=True;"\n adoConnStr = "Driver=" + Driver + ";" + _\n "Database=" + Database + ";" + _\n Options\n\n qtConnStr = "OLEDB;" + adoConnStr\n\n SQL = "SELECT * FROM people WHERE id <= 45"\n\n Dim AdoRecordset As ADODB.Recordset\n Set AdoRecordset = New ADODB.Recordset\n \n With AdoRecordset\n .ActiveConnection = adoConnStr\n .source = SQL\n .CursorLocation = adUseClient\n .CursorType = adOpenStatic\n .LockType = adLockReadOnly\n .Open\n Set .ActiveConnection = Nothing\n End With\n\n Dim Buffer As Excel.Worksheet\n Set Buffer = ActiveSheet\n Dim WSQueryTable As Excel.QueryTable\n Set WSQueryTable = Buffer.QueryTables.Add(Connection:=AdoRecordset, Destination:=Buffer.Range("A1"))\n With WSQueryTable\n .FieldNames = True\n .RowNumbers = False\n .PreserveFormatting = True\n .RefreshOnFileOpen = False\n .BackgroundQuery = True\n .RefreshStyle = xlInsertDeleteCells\n .SaveData = False\n .AdjustColumnWidth = True\n .RefreshPeriod = 0\n .PreserveColumnInfo = True\n .EnableEditing = True\n End With\n WSQueryTable.Refresh\nEnd Sub\n</code></pre>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub QueryTableSourceConnStr()\n Dim Driver As String\n Dim Options As String\n Dim Database As String\n\n Dim adoConnStr As String\n Dim qtConnStr As String\n Dim SQL As String\n Dim QTName As String\n\n Database = ThisWorkbook.Path + "\\" + "ADODBTemplates.db"\n Driver = "SQLite3 ODBC Driver"\n Options = "SyncPragma=NORMAL;LongNames=True;NoCreat=True;FKSupport=True;OEMCP=True;"\n adoConnStr = "Driver=" + Driver + ";" + _\n "Database=" + Database + ";" + _\n Options\n\n qtConnStr = "OLEDB;" + adoConnStr\n\n SQL = "SELECT * FROM people WHERE id <= 45"\n\n Dim Buffer As Excel.Worksheet\n Set Buffer = ActiveSheet\n Dim WSQueryTable As Excel.QueryTable\n Set WSQueryTable = Buffer.QueryTables.Add(Connection:=qtConnStr, Destination:=Buffer.Range("K1"), SQL:=SQL)\n With WSQueryTable\n .FieldNames = True\n .RowNumbers = False\n .PreserveFormatting = True\n .RefreshOnFileOpen = False\n .BackgroundQuery = True\n .RefreshStyle = xlInsertDeleteCells\n .SaveData = False\n .AdjustColumnWidth = True\n .RefreshPeriod = 0\n .PreserveColumnInfo = True\n .EnableEditing = True\n End With\n WSQueryTable.Refresh\nEnd Sub\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T08:24:22.833",
"Id": "257218",
"ParentId": "219371",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219383",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T15:45:45.057",
"Id": "219371",
"Score": "9",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Write to EXCEL from SQL DB using VBA script"
} | 219371 |
<p>I wrote a solution to a problem based on the N-Queens problem which should use more pieces than just queens. Problem is it's very slow, it probably has to do with how I modeled data and my lack of knowledge on how to compare boards without the possibility of extending from an interface <code>compareTo</code> as I would do in a language like Java.</p>
<p>This is the algorithm:</p>
<pre class="lang-golang prettyprint-override"><code>func Solution(board b.Board, pieces []rune, solutions *[]b.Board, testedConfigurations *[]b.Board) *[]b.Board {
if len(pieces) != 0 {
for i := 1; i < board.M; i++ {
for j := 1; j < board.N; j++ {
c := p.CreatePiece(pieces[0], i, j)
if b.IsSafe(board, c) {
modifiedBoard := b.Place(board, c)
if len(pieces) != 1 {
if !contains(modifiedBoard, *testedConfigurations) {
*testedConfigurations = append(*testedConfigurations, modifiedBoard)
Solution(modifiedBoard, pieces[1:], solutions, testedConfigurations)
}
} else {
if !contains(modifiedBoard, *solutions) {
*solutions = append(*solutions, modifiedBoard)
println("Found Solutions", len(*solutions))
}
}
}
}
}
}
return solutions
}
</code></pre>
<p>This is how I represent a piece in the board:</p>
<pre class="lang-golang prettyprint-override"><code>type Piece struct {
Name rune
Row int
Col int
}
</code></pre>
<p>This is how I represent the board</p>
<pre class="lang-golang prettyprint-override"><code>type Board struct {
M int
N int
Board [][]rune
Used []primitives.Attacks
}
</code></pre>
<p>This is the Attacks interface (I use it to check if a piece attacks another):</p>
<pre class="lang-golang prettyprint-override"><code>type Attacks interface {
Attacks(piece Attacks) bool
Row() int
Col() int
Name() rune
ToString() string
}
</code></pre>
<p>This is what I use to check if a solution is already been used:</p>
<pre class="lang-golang prettyprint-override"><code>func contains(boardContains b.Board, testedConfigurations []b.Board) bool {
for _, k := range testedConfigurations {
if len(k.Used) == len(boardContains.Used) && EqualBoards(k.Board, boardContains.Board, k.M, k.N) {
return true
}
}
return false
}
</code></pre>
<p>And this is what I use to check if two boards are equal:</p>
<pre class="lang-golang prettyprint-override"><code>func EqualBoards(board1 [][]rune, board2 [][]rune, M, N int) bool{
for i:=1; i< M; i++ {
for j:=1; j< N; j++ {
if board1[i][j]!=board2[i][j] {
return false
}
}
}
return true
}
</code></pre>
<p><a href="https://github.com/ignaciomosca/ChessChallengeGolang/tree/0a55e5f244f0812d7f4a3448fb6a446efc9a8b80" rel="nofollow noreferrer">Here's the code</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:34:03.127",
"Id": "423766",
"Score": "0",
"body": "Welcome to Code Review, Is it possible to post more of the code here? There is not enough code here to show the context and usage of this function. It might be considered off-topic to some users of the site, please see https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T18:13:41.057",
"Id": "423779",
"Score": "0",
"body": "Sure. I think this time I provided enough information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T23:44:00.023",
"Id": "424387",
"Score": "0",
"body": "Maybe I'm missing something, but it seems to me there are no generics here... If so, I suggest removing the generics tag. Also, the Github link is not working."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:34:32.860",
"Id": "219375",
"Score": "3",
"Tags": [
"performance",
"go",
"generics",
"chess",
"n-queens"
],
"Title": "N-Queens problem using other pieces using Go"
} | 219375 |
<p>I've to calculate 50% of tax .<br>
So I approach it using two ways. </p>
<p>1) <code>public static void main(String[] args) {
new Double(500) / 100 * 50);
}</code> </p>
<p>2) <code>public static void main(String[] args) {
new BigDecimal(500).divide(new BigDecimal(100).multiply(new BigDecimal(50)));
}</code> </p>
<p>Using first way that's manually calculating percentage.<br>
And using second, methods of BigDecimal.<br>
So which one is performance wise best?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:03:54.657",
"Id": "423762",
"Score": "3",
"body": "You have 2 horses. Race them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:06:26.993",
"Id": "423763",
"Score": "0",
"body": "Which one is better over another I want to know so I can race only one instead both of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:25:32.143",
"Id": "423764",
"Score": "0",
"body": "Why don't you profile both in a test setup and decide afterwards which one to use in production?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:27:22.657",
"Id": "423765",
"Score": "0",
"body": "Ok I'll check and apply."
}
] | [
{
"body": "<p>The first one is more performant because you are creating a Double which is a primitive data type. \n<br><br>\nIn the second one, you are creating three BigDecimal objects which are not a primitive and a lot larger containing a lot more functionality.\n<br>\nThis is the code of Big Decimal Divide function.</p>\n\n<p><a href=\"https://github.com/frohoff/jdk8u-dev-jdk/blob/master/src/share/classes/java/math/BigDecimal.java\" rel=\"nofollow noreferrer\">To see all source code</a>\n<br></p>\n\n<pre><code> public BigDecimal divide(BigDecimal divisor) {\n /*\n * Handle zero cases first.\n */\n if (divisor.signum() == 0) { // x/0\n if (this.signum() == 0) // 0/0\n throw new ArithmeticException(\"Division undefined\"); // NaN\n throw new ArithmeticException(\"Division by zero\");\n }\n\n // Calculate preferred scale\n int preferredScale = saturateLong((long) this.scale - divisor.scale);\n\n if (this.signum() == 0) // 0/y\n return zeroValueOf(preferredScale);\n else {\n /*\n * If the quotient this/divisor has a terminating decimal\n * expansion, the expansion can have no more than\n * (a.precision() + ceil(10*b.precision)/3) digits.\n * Therefore, create a MathContext object with this\n * precision and do a divide with the UNNECESSARY rounding\n * mode.\n */\n MathContext mc = new MathContext( (int)Math.min(this.precision() +\n (long)Math.ceil(10.0*divisor.precision()/3.0),\n Integer.MAX_VALUE),\n RoundingMode.UNNECESSARY);\n BigDecimal quotient;\n try {\n quotient = this.divide(divisor, mc);\n } catch (ArithmeticException e) {\n throw new ArithmeticException(\"Non-terminating decimal expansion; \" +\n \"no exact representable decimal result.\");\n }\n\n int quotientScale = quotient.scale();\n\n // divide(BigDecimal, mc) tries to adjust the quotient to\n // the desired one by removing trailing zeros; since the\n // exact divide method does not have an explicit digit\n // limit, we can add zeros too.\n if (preferredScale > quotientScale)\n return quotient.setScale(preferredScale, ROUND_UNNECESSARY);\n\n return quotient;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:07:24.203",
"Id": "423784",
"Score": "0",
"body": "No problemo =) you should still look through the source code of big decimal if you need the functionality do not reinvent the wheel so to speak use it performance is everything most of the time development is more important."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:09:54.880",
"Id": "423785",
"Score": "0",
"body": "If it solved your answer can you upvote it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:09:55.750",
"Id": "423786",
"Score": "1",
"body": "`double` is a primitive. `Double` is not a primitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:10:22.187",
"Id": "423787",
"Score": "0",
"body": "@200_succes sorry i should of clarificated"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:12:29.200",
"Id": "423788",
"Score": "1",
"body": "Either way, please do not answer off-topic questions. This question will likely be closed soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:13:13.953",
"Id": "423789",
"Score": "1",
"body": "@200_success https://www.baeldung.com/java-primitives-vs-objects I read it wrong I understand that the object Double is larger than a primitive however BigDecimal has more overhead then Double."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:14:05.993",
"Id": "423790",
"Score": "0",
"body": "@200_success how is this off topic? he is asking a question on working code on how to improve it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:16:32.933",
"Id": "423791",
"Score": "2",
"body": "The code is purely hypothetical. The first code sample isn't even syntactically correct. And since the numbers are all hard-coded, it can all be replaced by a hard-coded `250`. Finally, we have no context for evaluating the code (information about what range or precision is required)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:01:56.003",
"Id": "219385",
"ParentId": "219376",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219385",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:42:39.353",
"Id": "219376",
"Score": "-2",
"Tags": [
"java",
"performance"
],
"Title": "Which is best choise performance wise Double or BigDecimal to calculate percentage of tax?"
} | 219376 |
<p>I was try to reimplement the native <code>call</code> method in JavaScript.
Here we need to handle the object which we pass in the call function and additional params. I handle the additional params using <code>eval()</code> method. Is there any more efficient way to write it?</p>
<pre><code>var name = {
name: "JavaScript",
version: "6",
}
function printName(location, district){
alert(this.name + ", " + this.version + ", " + location + ", " + district);
}
Function.prototype.myCall = function(...args){
var param = args.slice(1),
paramLength = param.length,
paramString = "JSONarg.myFun(";
for(var i = 1; i <= paramLength; i++){
paramString += "args["+i+"],";
}
paramString += ")";
if(typeof this != 'function'){
throw new Error(this + " is not a Function");
}
var JSONarg = {
...args[0],
myFun: this
}
return eval(paramString);
}
printName.myCall(name, "Chrome", "browser");
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T17:01:10.650",
"Id": "423761",
"Score": "0",
"body": "Hey this is an interesting post! It appears that the code above shows an alert with the message `undefined, undefined, Chrome, browser` - is that what you expected, or was there something else you intended to have it do?"
}
] | [
{
"body": "<h2>Review</h2>\n\n<p>To be quick I will just add comments to the code with some alternatives</p>\n\n<pre><code>// if you add to a built in prototype use Object.defineProperty or Object.defineProperties\n// using the default settings\n// Function.prototype.myCall = function(...args){ // use 2 parameters\nFunction.prototype.myCall = function(name, ...args){ \n\n // var param = args.slice(1), // is now second parameter \n\n // Should be a constant\n // paramLength = param.length, \n const paramLength = args.length;\n\n // not really a param string. Rather its a eval function\n // paramString = \"JSONarg.myFun(\";\n var evaledFunc = \"JSONarg.myFun(\";\n\n // The variable if defined in the loop should be let\n // Now starts at index 0 \n //for(var i = 1; i <= paramLength; i++){ \n for (let i = 0; i < paramLength; i++) { // add space for ( and ) {\n\n evaledFunc += \"args[\" + i + \"],\"; // use spaces between operators\n }\n evaledFunc += \")\";\n\n // This function is a prototype of Function. You would have to go hard \n // to have the next statement be true. Just let the native exception \n // generate the error\n /*if(typeof this != 'function'){\n throw new Error(this + \" is not a Function\");\n }*/\n\n // Does not change, thus should be a const\n // var JSONarg = {\n const JSONarg = { // would be best defined at the top of the function\n\n // args[0] is now the param name\n // ...args[0],\n ...name,\n myFun: this \n // } // there should be a ; here\n };\n return eval(evaledFunc);\n}\n</code></pre>\n\n<p>Removing the comments and some minor mods we get...</p>\n\n<pre><code>function myCaller(name, ...args) { \n const JSONarg = {...name, myFun: this};\n var func = \"JSONarg.myFun(\";\n for (let i = 0; i < args.length; i++) {\n func += \"args[\" + i + \"],\"; \n }\n func += \")\";\n return eval(func);\n}\n</code></pre>\n\n<p>Rather than <code>eval</code> you could also have use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function\" rel=\"nofollow noreferrer\"><code>new Function</code></a></p>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\"><code>Object.defineProperty</code></a></h2>\n\n<p>To prevent problems (<code>myCall</code> showing up in strange places) and as it is in a very often used native type.( All functions get the new property). <code>enumerable = true</code> can slow every function call just a little depending on JS engine and version.</p>\n\n<p>Add to prototype safely using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty\" rel=\"nofollow noreferrer\"><code>Object.defineProperty</code></a>. Default accessor <code>configurable</code>, <code>enumerable</code>, <code>writable</code> are <code>false</code></p>\n\n<pre><code>if (! Function.prototype.myCall) {\n Object.defineProperty(Function.prototype, myCall, {value: myCaller});\n}\n</code></pre>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind</code></a></h2>\n\n<p>With all that said there is a much easier way to do the same. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind</code></a> will bind a functions with an object (sets the functions <code>this</code>)</p>\n\n<pre><code>function printName(location, district){\n alert(this.name + \", \" + this.version + \", \" + location + \", \" + district);\n}\nprintName.bind({...name})( \"Chrome\", \"browser\");\n\n// or just use original name obj\n\nprintName.bind(name)( \"Chrome\", \"browser\");\n</code></pre>\n\n<p>The bound function is a new reference, the original function remains unbound</p>\n\n<pre><code>const printNameBound = printName.bind(name);\n\nprintNameBound(\"Chrome\", \"browser\");\n\nprintName(\"Chrome\", \"browser\"); // will fail as not bound to name object\n</code></pre>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"nofollow noreferrer\"><code>Function.call</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"nofollow noreferrer\"><code>Function.apply</code></a></h2>\n\n<p>You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call\" rel=\"nofollow noreferrer\"><code>Function.call</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply\" rel=\"nofollow noreferrer\"><code>Function.apply</code></a> to do the same. In this case there is no new reference to the function created. The binding is temporary.</p>\n\n<pre><code>printName.call(name, \"Chrome\", \"browser\"); \n\n// or\n\nprintName.apply(name, [\"Chrome\", \"browser\"]); // args as array\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T04:55:15.457",
"Id": "423820",
"Score": "0",
"body": "How can i use new Function instead of eval()?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:43:51.663",
"Id": "423882",
"Score": "0",
"body": "@Kallis `function myCaller(name, ...args) { return (new Function(\"name\", \"func\", \"args\", \"return ({...name, func})(...args);\")(name, this, ...args);}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T17:44:43.030",
"Id": "423922",
"Score": "0",
"body": "can you check this https://jsfiddle.net/gowtham25/m1gnLd6x/12/"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T00:26:08.477",
"Id": "219399",
"ParentId": "219377",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219399",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T16:49:23.347",
"Id": "219377",
"Score": "1",
"Tags": [
"javascript",
"json",
"reinventing-the-wheel"
],
"Title": "Reimplementation of call() method in JavaScript"
} | 219377 |
<p>My programs that I have written so far included only a few lines of source code. When I tried to write larger programs, it usually failed because I'm not a master of software engineering. This time, I want to play it safe and publish now from time to time parts of the program, which should be my first, successful major project.</p>
<p>I intend to write a textual role playing game.</p>
<p>In my role playing game, the environment should be represented as a two-dimensional field. All surrounding objects, such as houses, natural objects and NPCs should be represented as points on the field. With special commands you will also be able to see your inventory, stats etc. but that will come later.</p>
<p>So I've written a field class and a base class for all the entities that can appear on the field. It was a little bit more complex than I expected. I'd like to know if these two classes can be used as a starting point for representing the environment objects of the game, or if my code is inappropriate and should be improved, or even a completely different concept should be implemented.</p>
<p><strong>Entity.java</strong></p>
<pre><code>public class Entity {
public String name;
public char symbol;
public boolean walkable;
// decides if entity can appear on several positions simultaneously
public boolean multifarious;
public Entity(String name, char symbol, boolean walkable) {
this.name = name;
this.symbol = symbol;
this.walkable = walkable;
this.multifarious = false;
}
public Entity(String name, char symbol, boolean walkable, boolean multifarious) {
this(name, symbol, walkable);
this.multifarious = multifarious;
}
public boolean isWalkable() {
return walkable;
}
public boolean isMultifarious() {
return multifarious;
}
public String getName() {
return name;
}
public char getSymbol() {
return symbol;
}
@Override
public String toString() {
return name + ", " + symbol + ", walkable: " + walkable;
}
}
</code></pre>
<p><strong>Field.java</strong></p>
<pre><code>import java.util.List;
import java.util.ArrayList;
public class Field {
private int height;
private int width;
private List<List<List<Entity>>> positions;
private boolean multipleEntitiesOnPosition;
private char emptyPositionRepresentation;
private List<Entity> placedEntities;
public Field(int height, int width, boolean multipleEntitiesOnPosition) {
this.height = height;
this.width = width;
positions = new ArrayList<List<List<Entity>>>();
for (int i = 0; i < height; i++) {
positions.add(new ArrayList<List<Entity>>());
for (int j = 0; j < width; j++) {
positions.get(i).add(new ArrayList<Entity>());
}
}
this.multipleEntitiesOnPosition = multipleEntitiesOnPosition;
emptyPositionRepresentation = ' ';
placedEntities = new ArrayList<Entity>();
}
public Field(int height, int width, boolean multipleEntitiesOnPosition, char emptyPositionRepresentation) {
this(height, width, multipleEntitiesOnPosition);
this.emptyPositionRepresentation = emptyPositionRepresentation;
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public void addEntity(Entity entity, int x, int y) {
// check if coordinates are valid
if (x >= height) {
System.err.println("error: x is greater than height");
return;
}
if (y >= width) {
System.err.println("error: y is greater than width");
return;
}
if (x < 0 || y < 0) {
System.err.println("error: negative positions argument(s)");
return;
}
// check if entity is allready on field
if (placedEntities.contains(entity) && !entity.isMultifarious()) {
System.err.println("error: entity is allready on field");
return;
}
List<Entity> entityList = positions.get(x).get(y);
// check if entity is allready on that position
if (entityList.contains(entity)) {
System.err.println("error: entity is allready on that position");
return;
}
// check if entity is allready placed on position
if (!multipleEntitiesOnPosition && !entityList.isEmpty()) {
System.err.println("error: multiple entities on same position are forbidden");
return;
}
// check if entity gets placed on another entity that is not walkable
for (Entity ent : entityList) {
if (!ent.isWalkable()) {
System.err.println("error: entity can not be placed on an entity that is not walkable (" + entity + ")");
return;
}
}
placedEntities.add(entity);
entityList.add(entity);
}
public void removeEntity(Entity entity) {
if (!placedEntities.contains(entity)) {
System.err.println("This entity is not on the field.");
return;
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
List<Entity> entities = positions.get(i).get(j);
if (entities.contains(entity)) {
entities.remove(entity);
if (!entity.isMultifarious()) {
return;
}
}
}
}
}
public String toString() {
StringBuilder returnValue = new StringBuilder();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
List<Entity> entities = positions.get(i).get(j);
if (!entities.isEmpty()) {
// only the last entity of a list is drawed on the field
char lastSymbol = entities.get(entities.size() - 1).getSymbol();
returnValue.append(lastSymbol);
} else {
returnValue.append(emptyPositionRepresentation);
}
}
returnValue.append('\n');
}
return returnValue.toString();
}
}
</code></pre>
<p><strong>Main.java</strong> (Test class)</p>
<pre><code>// This class tests the functionality of "Field" and "Entity"
public class Main {
public static void main(String[] args) {
// first attempt
Field field = new Field(20, 40, true, '.');
Entity player = new Entity("Player 1", '#', true);
field.addEntity(player, 10, 20);
System.out.println(field.toString());
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T03:05:27.617",
"Id": "424049",
"Score": "0",
"body": "Not a review but a suggestion: add a class that manages \"all the entities\", and a factory method that can take a 2-d \"picture\" of a field and create the field with entities. (That is, something you can pass a string 2d map picture, and it builds the corresponding data structure.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:49:49.440",
"Id": "424061",
"Score": "0",
"body": "Yes, this will be essential for later use! This is also already planed :)"
}
] | [
{
"body": "<p>1: You are declaring your variables public and creating a getter in Entity</p>\n\n<pre><code> public String name;\n public String getName() {\n return name;\n}\n</code></pre>\n\n<p>2: You should not couple walkable and non-walkable objects together.</p>\n\n<pre><code>public interface Walkable {\n\nvoid walk();\n</code></pre>\n\n<p>}</p>\n\n<p>3: <code>private List<List<List<Entity>>> positions</code>;<br>\n You can create a two-dimensional array </p>\n\n<pre><code>Entity[][] EntityArray= new Entity[height][width];\n</code></pre>\n\n<p>and get entity at x and y on that array example</p>\n\n<pre><code>Entity entity = entityArray[x][y]\n</code></pre>\n\n<p>If null is given that point is empty.</p>\n\n<blockquote>\n <p>With special commands you will also be able to see your inventory, stats etc. but that will come later.\n If you want this functionality I highly suggest you make an abstract class like below</p>\n</blockquote>\n\n<pre><code>public abstract class EntityExample {\n\nprivate int x, y;\nprivate char symbol;\nprivate String name;\n\npublic EntityExample(int x, int y, char symbol, String name) {\n this.x = x;\n this.y = y;\n this.symbol = symbol;\n this.name = name;\n}\n\npublic String getName() {\n return name;\n}\n\npublic char getSymbol() {\n return symbol;\n}\n\n@Override\npublic String toString() {\n return name + \", \" + symbol;\n}}\n</code></pre>\n\n<p>all surrounding objects, houses, natural objects, and NPCs should extend this class as this is the bare minimum the Field object needs to display them.</p>\n\n<p>Then you should create a more abstract class that extends EntityExample for controllable characters, for example, NPC, etc.</p>\n\n<p>If this is your first big project You should create a UML and plan your OOP concepts in a way that follows <a href=\"https://itnext.io/solid-principles-explanation-and-examples-715b975dcad4\" rel=\"nofollow noreferrer\">Solid Principles</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:04:11.920",
"Id": "423793",
"Score": "0",
"body": "Oops, normally I make the members private, why I forgot that..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:16:49.367",
"Id": "423795",
"Score": "0",
"body": "No problem it happens Do you have any questions =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:48:12.390",
"Id": "219388",
"ParentId": "219386",
"Score": "1"
}
},
{
"body": "<p>I agree with Adam, that you shouldn't use a List of Lists of Lists internally. An ArrayList is useful, if you need to change the number of elements, but for a fixed size as here, it would be much easier to use a two-dimensional array. Using an ArrayList for multiple entities at a position is fine for now (*), because the number of entites change.</p>\n\n<p>(*) Later it may be more performant to use something else.</p>\n\n<pre><code>private List<Entity>[][] positions;\n\npublic Field(int height, int width, boolean multipleEntitiesOnPosition) {\n this.height = height;\n this.width = width;\n\n positions = new List<Entity>[height][width];\n\n // ...\n}\n</code></pre>\n\n<p>Unless you know you'll have at least one entity at almost every position, it also make sense not to initalize the List of entites until needed:</p>\n\n<pre><code>public void addEntity(Entity entity, int x, int y) {\n\n // ...\n\n if (positions[y][x] == null) {\n positions[y][x] = new ArrayList<Entity>();\n }\n\n // ...\n\n positions[y][x].add(entity);\n\n //\n\n}\n</code></pre>\n\n<hr>\n\n<p>The biggest problem currently is your use of System.err to write error messages. If this is just placeholder, then that would make your question off topic, so for now I'll assume that it's \"real\" :)</p>\n\n<p>Checking validity of the coordinates is pointless here. If the given coordinates are wrong, then you have a problem in the rest of the code anyway, so you just as well can have it run into an <code>IndexOutOfBoundsException</code>.</p>\n\n<p>And in the other error cases there is no way for the calling code to know what went wrong, so instead of writing a pointless error message return an error code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:33:53.880",
"Id": "424059",
"Score": "0",
"body": "That was a typo on my side. I've corrected it, but you shouldn't be using either :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:29:32.783",
"Id": "219411",
"ParentId": "219386",
"Score": "0"
}
},
{
"body": "<p>I'm going through your code from top to bottom.</p>\n\n<h2>Entity</h2>\n\n<ul>\n<li><p>In your current code, an entity does not change after it has been constructed. Therefore all its fields should be marked as <code>final</code>, for example:</p>\n\n<pre><code>private final String name;\n</code></pre></li>\n<li><p>Making the fields <code>final</code> will produce a compile error in one of the constructors. \nCurrently, the constructor with more arguments calls the constructor with fewer arguments. It should be the other way round: the simple constructors should call the more complete ones:</p>\n\n<pre><code>public Entity(String name, char symbol, boolean walkable) {\n this(name, symbol, walkable, false);\n}\n\npublic Entity(String name, char symbol, boolean walkable, boolean multifarious) {\n this.name = name;\n this.symbol = symbol;\n this.walkable = walkable;\n this.multifarious = false;\n}\n</code></pre></li>\n<li><p>The field name <code>walkable</code> sounds strange. I first thought you meant <code>canWalk</code>, but that guess was wrong. To avoid this confusion, you should add a short comment:</p>\n\n<pre><code>// If true, other entities can walk on this entity.\n</code></pre></li>\n<li><p>In the <code>toString</code> method, it might look more natural to say:</p>\n\n<pre><code>public String toString() {\n String walkableStr = walkable ? \"walkable\" : \"not walkable\";\n return name + \", \" + symbol + \", \" + walkableStr;\n}\n</code></pre></li>\n</ul>\n\n<h2>Field</h2>\n\n<p>My first thought was: what the hell is a <code>List<List<List<Entity>>></code>, and is it really intended? Then I saw that it is indeed needed. It just looks really complicated and overdesigned at first.</p>\n\n<p>To avoid this first impression, it helps when you add a comment to this variable:</p>\n\n<pre><code>// positions[x][y] lists the entities at that cell.\n</code></pre>\n\n<p>This comment has the added benefit of clearly saying whether <code>x</code> or <code>y</code> comes first. While the order <code>x, y</code> is most common, there's enough code out there that uses <code>y, x</code> or <code>row, col</code>. Therefore readers of your code cannot be sure until they see the actual code.</p>\n\n<p>Typo: <code>allready</code> should be <code>already</code>.</p>\n\n<p>If you have lots of entities, <code>List.contains</code> will become slow because it searches the complete list from the beginning until the end. Instead you should use a <code>HashSet<Entity></code> instead of the <code>List<Entity></code> since <code>Set.contains</code> is faster.</p>\n\n<p>No part of your program should write directly to <code>System.out</code> or <code>System.err</code>. If your game becomes successful one day, you probably want to port it to Android, iOS, Windows, Linux, other platforms. Not all of them have <code>System.out</code>, and they differ in how they accept input from the user. Therefore it's a good idea to define a <code>UserInterface</code> for everything related to user interaction:</p>\n\n<pre><code>interface UserInterface {\n\n void inform(String message);\n\n /* The user tried to make a mistake, such as placing an entity \n * on a cell where there already is another entity. */\n void error(String message);\n\n String ask(String prompt);\n\n /* An internal programming error has happened. This is not the user's fault. */\n void programmingError(String message);\n}\n</code></pre>\n\n<p>This can be used for talking to the user. The last method in that interface is when you as the programmer made a mistake, such as passing negative coordinates. You may still want to inform the user, but the user cannot do anything about the error anyway. An entirely different case is when the user tries to place an entity on an invalid location. Currently you handle these types of errors in the same way, but you shouldn't.</p>\n\n<p>The <code>removeEntity</code> method is unused.</p>\n\n<p>In <code>removeEntity</code> you forgot to remove the entity from <code>placedEntities</code>. Watch out when removing a multifarious entity that is on the field in several locations. It's probably better to use a <code>Multiset</code> (from Google Guava) or a <code>Map<Entity, Integer></code> to count how often each entity is on the field.</p>\n\n<p>To make adding or removing entities faster, you should store them in a different way, in order to avoid the 2-dimensional <code>for</code> loop in <code>removeEntity</code>. It's better to remember for each entity at which positions it is. Again, Google Guava is a great library that contains a <code>Table</code> class and a <code>Multimap</code> for exactly this purpose.</p>\n\n<p>While I'm here, by using Guava's Multimap you could also replace your <code>List<List<List<Entity>>></code> with a <code>Multimap<Location, Entity></code>, which explains more directly what the field really contains.</p>\n\n<p>In <code>Field.toString</code> you mention:</p>\n\n<pre><code>// only the last entity of a list is drawed on the field\n</code></pre>\n\n<p>This comment is deeply hidden. It should be placed right at the <code>positions</code> field. The whole positions field might then be:</p>\n\n<pre><code>/**\n * Stores the entities that are currently at the given location on the field.\n * Entities that are added later are placed \"on top\" of the previous entities.\n * All but the topmost entity must be walkable.\n */\nprivate final ListMultimap<Location, Entity> entities = ArrayListMultimap.create();\n</code></pre>\n\n<h2>Main</h2>\n\n<p>The main class is short and to the point. Very nice.</p>\n\n<p>In addition to the main class, it would be good to have some unit tests for the <code>Entity</code> and <code>Field</code> classes. It's easy to automatically test for invalid placements:</p>\n\n<pre><code>@Test\npublic void entity_cannot_be_placed_twice() {\n Field field = new Field(5, 5, true, ' ');\n Entity player = new Entity(\"Player\", '#', false);\n field.addEntity(player, 2, 2);\n\n try {\n field.addEntity(player, 2, 2);\n fail();\n } catch (IllegalArgumentException e) {\n assertEquals(\"the entity is already on the board\", e.getMessage());\n }\n\n try {\n field.addEntity(player, 0, 1);\n fail();\n } catch (IllegalArgumentException e) {\n assertEquals(\"the entity is already on the board\", e.getMessage());\n }\n}\n</code></pre>\n\n<p>As soon as you have these automatic tests and run them regularly, you don't have to worry about accidentally breaking code that used to work before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:44:25.487",
"Id": "219449",
"ParentId": "219386",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219449",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T19:10:25.453",
"Id": "219386",
"Score": "5",
"Tags": [
"java",
"role-playing-game"
],
"Title": "Field class as a basis for a role playing game"
} | 219386 |
<p>Assumptions for use:</p>
<ol>
<li><p>push() will only ever be called by a single thread.</p></li>
<li><p>pop() will only ever be called by a single thread.</p></li>
</ol>
<p>Requirements:</p>
<p>push() needs to be as fast as possible. Requirements are stringent enough that I've determined that I can't use std::mutex (at least not in any way I've attempted to) as it is far too slow. (some initial stress tests took 6-8 ms without and 26-60 ms with std::mutex)</p>
<p>Code:</p>
<pre><code>template<typename T>
class PCQueue {
const size_t size;
std::unique_ptr<T[]> contents;
std::atomic<size_t> head;
std::atomic<size_t> tail;
public:
explicit PCQueue(size_t s) : size(s), contents(new T[s]), head(0), tail(0) {}
//num of elements in ringbuffer (size - room())
size_t count() {
return (tail + size - head) % size;
}
//num of free spaces in ringbuffer (size - count())
size_t room() {
return (head + size - tail) % size;
}
void push(T t) {
size_t newTail = (tail + 1) % size;
if (newTail == head) {
throw std::runtime_error("Pushing Full PCQueue");
}
contents[tail] = t;
tail = newTail;//std::atomic implicitly memfences, so this op must occur after the "contents[tail] = t;"
}
T pop() {
if (tail == head) {
throw std::runtime_error("Popping Empty PCQueue");
}
T ret = contents[head];
size_t newHead = (head + 1) % size;
head = newHead;
return ret;
}
};
</code></pre>
<p>My testing has implied that this performs correctly (but I'd like to squeeze more speed out of it if possible), but I'm not entirely certain my assumption about the push method is correct (the comment regarding memory barriers), as I'm still getting a handle on those, and I'm not sure I understand how loads and stores can be reordered regarding atomic and non-atomic variables, with the various memory orders. sequential consistency (the default) should enforce the desired behavior I think?</p>
<p>I'm worried that it's just working by coincidence (as concurrent code has a tendency to do), so a verification that my code is valid would be appreciated, as well as any general tips to improve it both in readability and performance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:37:56.583",
"Id": "423800",
"Score": "0",
"body": "Just a suggestion, but put as much stress on the system and the implementation as you can and then see if it breaks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:44:13.817",
"Id": "423801",
"Score": "1",
"body": "@pacmaninbw definitely. My testing has been to have two threads dedicated to doing nothing except push()ing and pop()ing respectively. It's worked flawlessly thus far, but for example I've only tested on windows x86 with mingw gcc. I know x86 has some extra restrictions on store/load reordering, so I'd ideally like the code to work according to the standard, rather than just happen to work on my hardware/compiler combination. I've tested it a few different ways with either thread being faster than the other and all seems kosher thus far."
}
] | [
{
"body": "<h3>Design</h3>\n\n<p>The problem with your implementation of <code>pop()</code> is that it can not be implemented in an exception safe manner (for any type of T). This is why the standard implementation implements this as two different methods <code>top()</code> and <code>pop()</code>. The <code>top()</code> function simply returns the value while <code>pop()</code> does not return the value but simply removes the value from <code>head</code>.</p>\n\n<p>So usage would become:</p>\n\n<pre><code>T val = queue.top();\nqueue.pop();\n</code></pre>\n\n<h3>Code Review</h3>\n\n<p>Your code assumes that <code>T</code> has a default constructor.</p>\n\n<pre><code> std::unique_ptr<T[]> contents;\n</code></pre>\n\n<p>When you create the <code>content</code> with <code>contents(new T[s])</code> you are allocating and initializing all the elements in that array using the default constructor.</p>\n\n<p>In addition to this if <code>T</code> is very expensive you have just used a lot of effort to create the items that may never be used (or you wasted resources creating the objects that are just going to be destroyed when overwritten).</p>\n\n<p>I would consider changing this to <code>std::vector<T></code>. That way you don't create any un-required objects when first created.</p>\n\n<hr>\n\n<p>This is fine:</p>\n\n<pre><code> explicit PCQueue(size_t s) : size(s), contents(new T[s]), head(0), tail(0) {}\n</code></pre>\n\n<p>But you can make it more readable. Remember the point of code is to make the code maintainable.</p>\n\n<pre><code> explicit PCQueue(size_t s)\n : size(s)\n , contents(new T[s])\n , head(0)\n , tail(0)\n {}\n</code></pre>\n\n<hr>\n\n<p>Is this the real definition of the function?</p>\n\n<pre><code> //num of elements in ringbuffer (size - room())\n size_t count() {\n return (tail + size - head) % size;\n }\n</code></pre>\n\n<p>I would rename this function to reflect what the function is actually returning. I would also change the formula so it is easy to read. I would call this <code>availableSpace()</code>. The formula is: <code>size - (head - tail)</code>.</p>\n\n<hr>\n\n<p>This would be better named <code>freeSpace()</code>.</p>\n\n<pre><code> //num of free spaces in ringbuffer (size - count())\n size_t room() {\n return (head + size - tail) % size;\n }\n</code></pre>\n\n<hr>\n\n<p>You pass the parameter by value.</p>\n\n<pre><code> void push(T t) {\n</code></pre>\n\n<p>This causes a copy to be made to pass it to the parameter. You should pass this by const reference (so there is no copy). If you want to get more advanced you could also pass by r-value reference which would allow you to move the object into your buffer rather than copying it.</p>\n\n<pre><code> void push(T const& t) { // Pass by const reference\n void push(T&& t) { // Pass by r-value reference\n</code></pre>\n\n<hr>\n\n<p>The problem with the <code>pop()</code> as written you can not guarantee a clean removal. This is because you need to make several copies and if those copies fail you can leave the container in a bad state.</p>\n\n<pre><code> T pop() {\n T ret = contents[head]; // Here is a copy.\n size_t newHead = (head + 1) % size; \n head = newHead;\n return ret; // Here is another copy. \n }\n</code></pre>\n\n<p>You did not define <code>T</code> so you don't have control over the copy assignment constructor. That is why it is usually split into two functions.</p>\n\n<pre><code> // Return by reference\n // That way we can avoid any un-needed copies.\n T const& top() const {\n return contents[head];\n }\n // Simply remove the head item in the pop.\n void pop() {\n size_t newHead = (head + 1) % size; \n head = newHead;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:32:37.917",
"Id": "423990",
"Score": "0",
"body": "Thank you! All of this is quite useful, except I think you misunderstood the count() method. it is intended to return the number of elements currently in the queue (i.e. how many times pop() can be called at most) (and testing has verified that it does, or at least seems to, even if head and or tail have wrapped around back to the beginning). having an \"available space\" and a \"free space\" method seems redundant and confusing, could I get clarification?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:52:24.360",
"Id": "424005",
"Score": "0",
"body": "@Phi I think that confirms my point that the name of the function is not clear. :-) Function naming so that the intent is clear is a major part of the \"Self Documenting Code\" philosophy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T09:01:23.750",
"Id": "219415",
"ParentId": "219389",
"Score": "11"
}
},
{
"body": "<p>In addition to what has already been said I would add that </p>\n\n<ol>\n<li><p>what happens if <code>s</code> is zero? You might want to throw an exception in the constructor if that happens probably because any call to <code>count</code> of <code>room</code> would fail otherwise.</p></li>\n<li><p>you can definitely improve <code>const</code> correctness at least in a couple of places:</p></li>\n</ol>\n\n<p>in </p>\n\n<pre><code>explicit PCQueue(size_t s) :\n</code></pre>\n\n<p>you can make <code>s</code> <code>const</code>. </p>\n\n<pre><code>explicit PCQueue(const size_t s) :\n</code></pre>\n\n<hr>\n\n<p>You can do the same thing in <code>push</code> for the <code>newTail</code> variable.</p>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T10:49:29.923",
"Id": "219420",
"ParentId": "219389",
"Score": "5"
}
},
{
"body": "<p>This is sort of an extended comment on Martin York's reply.</p>\n\n<p>When you're doing any sort of parallel processing, I advise against re-designing <code>pop</code> so it requires two operations to actually remove an item from the queue, like:</p>\n\n<pre><code>T val = queue.top();\nqueue.pop();\n</code></pre>\n\n<p>With sufficient care, this <em>can</em> work for a single-producer/single-consumer situation, but has the potential to lead to problems even in that limited case.</p>\n\n<p>The minute you get multiple consumers involved, it's completely and irrevocably broken.</p>\n\n<p>My personal advice is that even if you're only currently planning for a single consumer, it's better to design the interface so you could support multiple consumers anyway. Then when/if you use more than one consumer, you don't have to rewrite all the existing code to do it.</p>\n\n<p>After several iterations through it, an interface I've found to work well is:</p>\n\n<pre><code>bool pop(T &);\n</code></pre>\n\n<p>The typical implementation is something like this:</p>\n\n<pre><code>bool pop(T &dest) { \n try { \n dest = data.top();\n data.pop();\n return true;\n }\n catch(...) { \n return false; \n }\n}\n</code></pre>\n\n<p>With this design, we retain exception safety: if <code>dest = data.top();</code> throws an exception, then we just return false, and the content of the queue remains exactly as it was before <code>pop</code> was called. If it succeeds, we call <code>data.pop();</code>.</p>\n\n<p>It's also (with appropriate use of a mutex or similar) safe for multiple consumers to use in parallel. In particular, we would normally plan on executing the <code>dest = data.top(); data.pop();</code> as an atomic operation, so if we get an item from the queue, we know we'll remove that item. We can't get two threads in parallel that read the same top of queue item, then each remove an item from the queue (one of which hasn't been read and can never be processed).</p>\n\n<p>Depending on the situation, it's often useful to add a timeout to reading, so if you attempt to read but there's nothing in the queue, you don't get stuck there forever.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:59:33.887",
"Id": "219458",
"ParentId": "219389",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "219415",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:18:07.727",
"Id": "219389",
"Score": "9",
"Tags": [
"c++",
"c++17",
"lock-free",
"producer-consumer",
"atomic"
],
"Title": "C++ lock free, single producer, single consumer queue"
} | 219389 |
<p>I'm a crop scientist and am currently building a <a href="https://aerial-analytics.us/locations/" rel="nofollow noreferrer">web app</a> that collects weather data then generates and displays modeled agriculturally relevant output. My question centers around an increasingly complex Django view and a desire to learn about a potentially superior implementation if one exists.</p>
<p>I have a Django view that allows the user to select a location from a Google maps layer when the page in initially rendered. Once a selection is made the view will check for <code>location</code> in URL request and render the template for an individual location. Once the individual location page is rendered the user has further options, like selecting a date range for desired data. The selection is made and submitted at which point the view will check for <code>selectstartdate</code> and <code>selectenddate</code> in the URL request and, if present, will render the single location view with data for the desired range. As I plan on adding several other interactive features, I'm beginning to realize that this <code>view</code> is going to get complicated quickly.</p>
<p>Is an intricate, conditionally driven Django view a reasonable implementation or is there a better way to do something like this?</p>
<h3>Code</h3>
<pre><code>import time
from django.shortcuts import render
from locations.models import Location
from metload.models import Obsset
from datetime import datetime
from ETo_py.eto import EToEstimator
def single_location(**kwargs):
"""
Process a bunch of weather parameters and return modeled output.
This function is not a view, just a helper function for processing data.
I have left out the lengthy inner workings of this function.
"""
return context
def index(request):
print('hello')
# Single location without date range selected.
if 'location' in request.GET and \
'selectstartdate' not in request.GET and \
'selectenddate' not in request.GET:
location = request.GET['location']
selectstartdate = None
selectenddate = None
params = {
'location': location,
'selectstartdate': selectstartdate,
'selectenddate': selectenddate,
}
context = single_location(**params)
return render(request, 'locations/location.html', context)
# Single location with a date range selected.
elif 'location' in request.GET and \
'selectstartdate' in request.GET and \
'selectenddate' in request.GET:
location = request.GET['location']
selectstartdate = request.GET['selectstartdate']
selectenddate = request.GET['selectenddate']
print(selectstartdate, selectenddate)
params = {
'location': location,
'selectstartdate': selectstartdate,
'selectenddate': selectenddate,
}
context = single_location(**params)
return render(request, 'locations/location.html', context)
# Initial page.
else:
# Get locations from db.
locations = Location.objects.all()
# Prepare locations dictionary for google map layer js.
locs_ls = []
for loc in locations:
lat = loc.latitude
lon = loc.longitude
name = loc.name
site_id = loc.site_id
locs_ls.append({'site_id': site_id, 'name': name, 'lat': lat, 'lon': lon})
context = {
'locs_ls': locs_ls,
}
return render(request, 'locations/index.html', context)
</code></pre>
| [] | [
{
"body": "<p>Not sure this will solve all your problems, but you can give those GET parameters default values in case they don't exist. In my example below, they are given the default value of None. This should simplify things a bit.</p>\n\n<pre><code>def index(request):\n\n print('hello')\n\n\n location = request.GET.get('location', None)\n selectstartdate = request.GET.get('selectstartdate', None)\n selectenddate = request.GET.get('selectenddate', None)\n\n if location is not None or selectstartdate is not None and selectenddate is not None:\n\n # Get locations from db.\n locations = Location.objects.all()\n\n # Prepare locations dictionary for google map layer js.\n locs_ls = []\n for loc in locations:\n lat = loc.latitude\n lon = loc.longitude\n name = loc.name\n site_id = loc.site_id\n\n locs_ls.append({'site_id': site_id, 'name': name, 'lat': lat, 'lon': lon})\n\n context = {\n 'locs_ls': locs_ls,\n }\n\n return render(request, 'locations/index.html', context)\n\n else:\n\n params = {\n 'location': location,\n 'selectstartdate': selectstartdate,\n 'selectenddate': selectenddate,\n }\n\n context = single_location(**params)\n\n return render(request, 'locations/location.html', context)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T12:47:28.520",
"Id": "423977",
"Score": "0",
"body": "Thanks for the feedback. I did not know that it was possible to assign default values to the GET parameters. This may be helpful. I do know that `if location is not None:` could also be written as `if location:`. I'll leave the question open for now and see what other suggestions may be offered."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T17:13:15.807",
"Id": "219452",
"ParentId": "219392",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219452",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T20:32:15.980",
"Id": "219392",
"Score": "4",
"Tags": [
"python",
"django"
],
"Title": "Django view to display weather measurements for selected location and dates"
} | 219392 |
<p>I have some long-time method (PrintInfo).</p>
<p>I need to know total steps of that method and track completed parts.</p>
<p>How to <strong>reuse</strong> same filtered query in:</p>
<ol>
<li><strong>TotalSteps</strong> (ex, Program: progressMonitor.TotalSteps = /* ... */)</li>
<li>method <strong>PrintInfo</strong>?</li>
</ol>
<p><strong>Description of example</strong>: .</p>
<p>I have BookLibrary with some hierarchy( BookCabinet → Box → Book → Words).</p>
<p>I need to print some information of filtered books and track completed parts. Printing can take long time.</p>
<p><strong>Entities</strong>: </p>
<pre><code>using System.Collections.Generic;
namespace TotalSteps
{
class BookCabinet
{
public string Category { get; set; }
public List<Box> Boxes { get; set; }
}
class Box
{
public string Category { get; set; }
public List<Book> Books { get; set; }
}
class Book
{
public string[] Authors { get; set; }
public List<string> Words { get; set; }
}
}
</code></pre>
<p><strong>ProcessMonitor</strong>:</p>
<pre><code>using System;
namespace TotalSteps
{
class ProcessMonitor
{
public int TotalSteps { get; set; }
private int completedSteps = 0;
public int CompletedSteps
{
get
{
return completedSteps;
}
set
{
completedSteps = value;
Console.WriteLine("Completed steps: " + completedSteps);
}
}
}
}
</code></pre>
<p><strong>BooksLibrary</strong>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace TotalSteps
{
class BooksLibrary
{
public void PrintInfo(IEnumerable<BookCabinet> cabinets, ProcessMonitor processMonitor)
{
if (!cabinets.Any())
{
return;
}
cabinets = cabinets.Where(cabinet => cabinet.Category == "Biology");
foreach (BookCabinet cabinet in cabinets)
{
IEnumerable<Box> boxes = cabinet.Boxes.Where(box => box.Category.Contains("fish"));
if (boxes.Any())
{
Console.WriteLine("BookCabinet category: " + cabinet.Category);
}
foreach (Box box in boxes)
{
IEnumerable<Book> books = box.Books.Where(book => book.Authors.Contains("Mick"));
if (books.Any())
{
Console.WriteLine("Box category: " + box.Category);
}
foreach (Book book in books)
{
IEnumerable<string> words = book.Words.Where(word => word.Contains("lionfish") || word.Contains("permission"));
if (words.Any())
{
Console.WriteLine("Book authors: " + string.Join(", ", book.Authors));
}
foreach (string word in words)
{
Console.WriteLine("word: " + word);
processMonitor.CompletedSteps++;
}
}
}
}
}
}
}
</code></pre>
<p><strong>Program</strong>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace TotalSteps
{
class Program
{
static void Main(string[] args)
{
ProcessMonitor progressMonitor = new ProcessMonitor();
List<string> words = new List<string>() { "lionfish", "permission", "trade" };
List<Book> books = new List<Book>() { new Book() { Authors = new string[] { "Mick", "John" }, Words = words } };
List<Box> boxes = new List<Box>() { new Box() { Category = "fish", Books = books }};
IEnumerable<BookCabinet> cabinets = new List<BookCabinet>()
{
new BookCabinet() { Category = "Archeology", Boxes = new List<Box>() { } },
new BookCabinet() { Category = "Biology", Boxes = boxes },
};
BooksLibrary librarty = new BooksLibrary();
progressMonitor.TotalSteps = cabinets.Where(cabinet => cabinet.Category == "Biology")
.SelectMany(cabinet => cabinet.Boxes.Where(box => box.Category.Contains("fish"))
.SelectMany(box => box.Books.Where(book => book.Authors.Contains("Mick"))))
.SelectMany(book => book.Words.Where(word => word.Contains("lionfish") || word.Contains("permission"))).Count();
Console.WriteLine("Total steps: " + progressMonitor.TotalSteps);
librarty.PrintInfo(cabinets, progressMonitor);
}
}
}
</code></pre>
<p>P.S.:
I duplicate code. It's not right.
Are there any better approaches to achieve what i want?</p>
<p>Maybe to store query in entities.</p>
<p>The problem is that If I edit method PrintInfo
i will forget to change method to count total steps.</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
namespace TotalSteps
{
class BookCabinet
{
public string Category { get; set; }
public List<Box> Boxes { get; set; }
public IEnumerable<Box> FilteredBoxes
{
get
{
return Boxes.Where(box => box.Category.Contains("fish"));
}
}
}
class Box
{
public string Category { get; set; }
public List<Book> Books { get; set; }
public IEnumerable<Book> FilteredBooks
{
get
{
return Books.Where(book => book.Authors.Contains("Mick"));
}
}
}
class Book
{
public string[] Authors { get; set; }
public List<string> Words { get; set; }
public IEnumerable<string> FilteredWords
{
get
{
return Words.Where(word => word.Contains("lionfish") || word.Contains("permission"));
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T00:37:44.717",
"Id": "423814",
"Score": "1",
"body": "What exactly are you asking?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T07:50:06.753",
"Id": "423958",
"Score": "0",
"body": "`PrintInfo` is doing 2 things: searching and printing. So when you say 'printing can take (a) long time', which of these 2 do you mean?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T21:01:59.717",
"Id": "219393",
"Score": "2",
"Tags": [
"c#",
"beginner",
"object-oriented"
],
"Title": "Total steps of of long process, track completed steps, reuse query"
} | 219393 |
<p>This is a very bare bones program where a population of blocks learn to reach a target on a 2d screen (My attempt at making a smart rockets program)</p>
<p>I've only used python for 2 weeks so i'm positive certain aspects of the program have extraneous lines of code and unnecessary junk, so what are some ways I can optimize the program/algorithm and make it more readable? </p>
<pre><code>import random
import math
import pygame
import time
WINDOW_SIZE = (600, 600)
COLOR_KEY = {"RED": [255, 0, 0, 10],
"GREEN": [0, 255, 0, 128],
"BLUE": [0, 0, 255, 128],
"WHITE": [255, 255, 255],
"BLACK": [0, 0, 0]}
target = [500, 500]
pop_size = 20
max_moves = 1500
mutation_rate = 30
class Block:
def __init__(self):
self.color = COLOR_KEY["GREEN"]
self.size = (40, 40)
self.move_set = []
self.position = [0, 0]
self.fitness = -1
self.target_reached = False
def evaluate(self):
dx = target[0] - self.position[0]
dy = target[1] - self.position[1]
if dx == 0 and dy == 0:
self.fitness = 1.0
else:
self.fitness = 1 / math.sqrt((dx * dx) + (dy * dy))
def move(self, frame_count):
if not self.target_reached:
self.position[0] += self.move_set[frame_count][0]
self.position[1] += self.move_set[frame_count][1]
if self.position[0] == target[0] and self.position[1] == target[1]:
self.target_reached = True
self.color = COLOR_KEY["BLUE"]
def create_pop():
pop = []
for block in range(pop_size):
pop.append(Block())
return pop
def generate_moves(population):
for block in population:
for _ in range(max_moves+1):
rand_x = random.randint(-1, 1)
rand_y = random.randint(-1, 1)
block.move_set.append([rand_x, rand_y])
return population
def fitness(population):
for block in population:
block.evaluate()
def selection(population):
population = sorted(population, key=lambda block: block.fitness, reverse=True)
best_fit = round(0.1 * len(population))
population = population[:best_fit]
return population
def cross_over(population):
offspring = []
for _ in range(int(pop_size/2)):
parents = random.sample(population, 2)
child1 = Block()
child2 = Block()
split = random.randint(0, max_moves)
child1.move_set = parents[0].move_set[0:split] + parents[1].move_set[split:max_moves]
child2.move_set = parents[1].move_set[0:split] + parents[0].move_set[split:max_moves]
offspring.append(child1)
offspring.append(child2)
return offspring
def mutation(population):
chance = random.randint(0, 100)
num_mutated = random.randint(0, pop_size)
if chance >= 100 - mutation_rate:
for _ in range(num_mutated):
mutated_block = population[random.randint(0, len(population) - 1)]
for _ in range(50):
if chance >= 100 - mutation_rate/2:
rand_x = random.randint(0, 1)
rand_y = random.randint(0, 1)
else:
rand_x = random.randint(-1, 1)
rand_y = random.randint(-1, 1)
mutated_block.move_set[random.randint(0, max_moves - 1)] = [rand_x, rand_y]
return population
def calc_avg_fit(population):
avg_sum = sum(block.fitness for block in population)
return avg_sum/pop_size
def ga(population):
fitness(population)
avg_fit = calc_avg_fit(population)
population = selection(population)
population = cross_over(population)
population = mutation(population)
returning = (avg_fit, population)
return returning
def main():
pygame.init()
window = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("AI Algorithm")
population = create_pop()
population = generate_moves(population)
my_font = pygame.font.SysFont("Arial", 16)
frame_count = 0
frame_rate = 0
t0 = time.process_time()
gen = 0
avg_fit = 0
while True:
event = pygame.event.poll()
if event.type == pygame.QUIT:
break
frame_count += 1
if frame_count % max_moves == 0:
t1 = time.process_time()
frame_rate = 500 / (t1-t0)
t0 = t1
frame_count = 0
data = ga(population)
avg_fit = data[0]
population = data[1]
gen += 1
window.fill(COLOR_KEY["BLACK"], (0, 0, WINDOW_SIZE[0], WINDOW_SIZE[1]))
for block in population:
block.move(frame_count)
for block in population:
window.fill(block.color, (block.position[0], block.position[1], block.size[0], block.size[1]))
window.fill(COLOR_KEY["RED"], (target[0] + 10, target[1] + 10, 20, 20), 1)
frame_rate_text = my_font.render("Frame = {0} rate = {1:.2f} fps Generation: {2}"
.format(frame_count, frame_rate, gen), True, COLOR_KEY["WHITE"])
fitness_text = my_font.render("Average Fitness: {0}".format(avg_fit), True, COLOR_KEY["WHITE"])
window.blit(fitness_text, (WINDOW_SIZE[0] - 300, 40))
window.blit(frame_rate_text, (WINDOW_SIZE[0] - 300, 10))
pygame.display.flip()
pygame.quit()
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T21:13:46.707",
"Id": "219394",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"genetic-algorithm"
],
"Title": "Simplified Smart Rockets using Genetic Algorithm"
} | 219394 |
<p>I implemented the cubic spline interpolation explained in<br>
<a href="https://en.wikipedia.org/wiki/Spline_interpolation" rel="noreferrer"><a href="https://en.wikipedia.org/wiki/Spline_interpolation" rel="noreferrer">https://en.wikipedia.org/wiki/Spline_interpolation</a></a> as a Python class. Of course, such an interpolation should exist already in some Python math libraries. However, this post is not about using an existing specific solution, but is rather about review of a code written <em>from scratch</em> that uses only standard functions.</p>
<p>Following the best practices, I protected my code with tests (I preferred doctest for this example). In this way, we are good to refactor now.</p>
<p>Could you please help my to improve the quality of the code? You may just share your overall feedback or suggest some improvements.</p>
<p>Thanks,<br>
Ivan</p>
<p><strong>Code</strong>: CubicSplineStruct.py</p>
<pre class="lang-py prettyprint-override"><code>"""
Natural cubic spline interpolation
Reference: https://en.wikipedia.org/wiki/Spline_interpolation
To run doc tests: python -m doctest CubicSplineStruct.py
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 4
>>> cubicSplineStruct.m_xvalues = [0.0, 10./3., 20./3., 10.]
>>> cubicSplineStruct.computeYtoKMatrix()
>>> cubicSplineStruct.m_yvalues = [128., -64., 128., -64.]
>>> cubicSplineStruct.computeKCoeffs()
>>> print(cubicSplineStruct.interpolate(10./3.))
-64.0
>>> print(cubicSplineStruct.interpolate(5.))
32.0
>>> print(cubicSplineStruct.interpolate(20./3.))
128.0
"""
import numpy as np
from bisect import bisect_left
class CubicSplineStruct:
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 3
>>> cubicSplineStruct.m_xvalues = [0., 10., 42.]
>>> cubicSplineStruct.computeYtoKMatrix()
>>> cubicSplineStruct.m_yvalues = [100., 75., 95.]
>>> cubicSplineStruct.computeKCoeffs()
>>> y = cubicSplineStruct.interpolate(30.)
"""
def __init__(self):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> print(cubicSplineStruct.m_n)
0
>>> print(cubicSplineStruct.m_xvalues)
[]
>>> print(cubicSplineStruct.m_yvalues)
[]
>>> print(cubicSplineStruct.m_kMatrix)
[]
>>> print(cubicSplineStruct.m_yMatrix)
[]
>>> print(cubicSplineStruct.m_ytoKMatrix)
[]
>>> print(cubicSplineStruct.m_kCoeffs)
[]
"""
self.m_n = 0
self.m_xvalues = []
self.m_yvalues = []
self.m_kMatrix = np.matrix(np.zeros(shape=(0,0)))
self.m_yMatrix = np.matrix(np.zeros(shape=(0,0)))
self.m_ytoKMatrix = np.matrix(np.zeros(shape=(0,0)))
self.m_kCoeffs = []
pass
def pushFirstEquationToKMatrix(self, x0, x1):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_kMatrix = np.matrix(np.zeros(shape=(1,5)))
>>> cubicSplineStruct.pushFirstEquationToKMatrix(1.0, 1.5)
>>> print(cubicSplineStruct.m_kMatrix[0, 0]) # 2./(x1 - x0)
4.0
>>> print(cubicSplineStruct.m_kMatrix[0, 1]) # 1./(x1 - x0)
2.0
"""
self.m_kMatrix[0, 0] = 2./(x1 - x0)
self.m_kMatrix[0, 1] = 1./(x1 - x0)
def pushLastEquationToKMatrix(self, xnm1, xn):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_kMatrix = np.matrix(np.zeros(shape=(5,5)))
>>> cubicSplineStruct.pushLastEquationToKMatrix(1.0, 1.5)
>>> print(cubicSplineStruct.m_kMatrix[-1, -1]) # 2./(xn - xnm1)
4.0
>>> print(cubicSplineStruct.m_kMatrix[-1, -2]) # 1./(xn - xnm1)
2.0
"""
self.m_kMatrix[-1, -1] = 2./(xn - xnm1)
self.m_kMatrix[-1, -2] = 1./(xn - xnm1)
def pushMiddleEquationToKMatrix(self, i, xim1, xi, xip1):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_kMatrix = np.matrix(np.zeros(shape=(4,5)))
>>> cubicSplineStruct.pushMiddleEquationToKMatrix(3, 1.0, 1.5, 1.75)
>>> print(cubicSplineStruct.m_kMatrix[3, 2]) # 1./(xi - xim1)
2.0
>>> print(cubicSplineStruct.m_kMatrix[3, 3]) # 2./(xi - xim1) + 2./(xip1 - xi)
12.0
>>> print(cubicSplineStruct.m_kMatrix[3, 4]) # 1./(xip1 - xi)
4.0
"""
self.m_kMatrix[i, i-1] = 1./(xi - xim1)
self.m_kMatrix[i, i] = 2./(xi - xim1) + 2./(xip1 - xi)
self.m_kMatrix[i, i + 1] = 1./(xip1 - xi)
def computeKMatrix(self):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 4
>>> cubicSplineStruct.m_xvalues = [1.0, 1.5, 1.75, 2.25]
>>> cubicSplineStruct.computeKMatrix()
>>> print(cubicSplineStruct.m_kMatrix)
[[ 4. 2. 0. 0.]
[ 2. 12. 4. 0.]
[ 0. 4. 12. 2.]
[ 0. 0. 2. 4.]]
"""
self.m_kMatrix = np.matrix(np.zeros(shape=(self.m_n, self.m_n)))
self.pushFirstEquationToKMatrix(self.m_xvalues[0], self.m_xvalues[1])
for i in range(1, self.m_n-1):
self.pushMiddleEquationToKMatrix(i, self.m_xvalues[i-1], self.m_xvalues[i], self.m_xvalues[i+1])
self.pushLastEquationToKMatrix(self.m_xvalues[-2], self.m_xvalues[-1])
def pushFirstEquationToYMatrix(self, x0, x1):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_yMatrix = np.matrix(np.zeros(shape=(1,5)))
>>> cubicSplineStruct.pushFirstEquationToYMatrix(1.0, 1.5)
>>> print(cubicSplineStruct.m_yMatrix[0, 0]) # -3./(x1 - x0)**2
-12.0
>>> print(cubicSplineStruct.m_yMatrix[0, 1]) # 3./(x1 - x0)**2
12.0
"""
self.m_yMatrix[0, 0] = -3./(x1 - x0)**2
self.m_yMatrix[0, 1] = 3./(x1 - x0)**2
def pushLastEquationToYMatrix(self, xnm1, xn):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_yMatrix = np.matrix(np.zeros(shape=(5,5)))
>>> cubicSplineStruct.pushLastEquationToYMatrix(1.0, 1.5)
>>> print(cubicSplineStruct.m_yMatrix[-1, -1]) # 3./(xn - xnm1)**2
12.0
>>> print(cubicSplineStruct.m_yMatrix[-1, -2]) # -3./(xn - xnm1)**2
-12.0
"""
self.m_yMatrix[-1, -1] = 3./(xn - xnm1)**2
self.m_yMatrix[-1, -2] = -3./(xn - xnm1)**2
def pushMiddleEquationToYMatrix(self, i, xim1, xi, xip1):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_yMatrix = np.matrix(np.zeros(shape=(4,5)))
>>> cubicSplineStruct.pushMiddleEquationToYMatrix(3, 1.0, 1.5, 1.75)
>>> print(cubicSplineStruct.m_yMatrix[3, 2]) # -3./(xi - xim1)**2
-12.0
>>> print(cubicSplineStruct.m_yMatrix[3, 3]) # 3./(xi - xim1)**2 - 3./(xip1 - xi)**2
-36.0
>>> print(cubicSplineStruct.m_yMatrix[3, 4]) # 3./(xip1 - xi)**2
48.0
"""
self.m_yMatrix[i, i-1] = -3./(xi - xim1)**2
self.m_yMatrix[i, i] = 3./(xi - xim1)**2 - 3./(xip1 - xi)**2
self.m_yMatrix[i, i + 1] = 3./(xip1 - xi)**2
def computeYMatrix(self):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 4
>>> cubicSplineStruct.m_xvalues = [1.0, 1.5, 1.75, 2.25]
>>> cubicSplineStruct.computeYMatrix()
>>> print(cubicSplineStruct.m_yMatrix)
[[-12. 12. 0. 0.]
[-12. -36. 48. 0.]
[ 0. -48. 36. 12.]
[ 0. 0. -12. 12.]]
"""
self.m_yMatrix = np.matrix(np.zeros(shape=(self.m_n, self.m_n)))
self.pushFirstEquationToYMatrix(self.m_xvalues[0], self.m_xvalues[1])
for i in range(1, self.m_n-1):
self.pushMiddleEquationToYMatrix(i, self.m_xvalues[i-1], self.m_xvalues[i], self.m_xvalues[i+1])
self.pushLastEquationToYMatrix(self.m_xvalues[-2], self.m_xvalues[-1])
def computeYtoKMatrix(self):
"""
Should be called when x knot values are updated
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 4
>>> cubicSplineStruct.m_xvalues = [0.0, 10./3., 20./3., 10.]
>>> cubicSplineStruct.computeYtoKMatrix()
>>> print(cubicSplineStruct.m_ytoKMatrix)
[[-0.38 0.48 -0.12 0.02]
[-0.14 -0.06 0.24 -0.04]
[ 0.04 -0.24 0.06 0.14]
[-0.02 0.12 -0.48 0.38]]
"""
self.computeKMatrix()
self.computeYMatrix()
self.m_ytoKMatrix = self.m_kMatrix.I*self.m_yMatrix
def computeKCoeffs(self):
"""
Should be called when y knot values are updated
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_n = 2
>>> cubicSplineStruct.m_ytoKMatrix = np.mat('1 2; 4 5')
>>> cubicSplineStruct.m_yvalues =[3., 4.]
>>> cubicSplineStruct.computeKCoeffs()
>>> print(cubicSplineStruct.m_kCoeffs)
[11.0, 32.0]
"""
kCoeffs = np.array(self.m_yvalues)*self.m_ytoKMatrix.T
self.m_kCoeffs = [kCoeffs[0, i] for i in range(self.m_n)]
def interpolateOnInterval(self, intervalIndex, x):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_xvalues = [None, 10., 42.]
>>> cubicSplineStruct.m_yvalues = [None, 128., -64.]
>>> cubicSplineStruct.m_kCoeffs = [None, 2., 6.]
>>> print(cubicSplineStruct.interpolateOnInterval(1, 10.))
128.0
>>> print(cubicSplineStruct.interpolateOnInterval(1, 18.))
98.0
>>> print(cubicSplineStruct.interpolateOnInterval(1, 34.))
-58.0
>>> print(cubicSplineStruct.interpolateOnInterval(1, 42.))
-64.0
"""
x1 = self.m_xvalues[intervalIndex]
x2 = self.m_xvalues[intervalIndex+1]
y1 = self.m_yvalues[intervalIndex]
y2 = self.m_yvalues[intervalIndex+1]
t = (x - x1)/(x2 - x1)
a = computeACoeff(x1, x2, y1, y2, self.m_kCoeffs[intervalIndex])
b = computeBCoeff(x1, x2, y1, y2, self.m_kCoeffs[intervalIndex+1])
return (1-t)*y1 + t*y2 + t*(1-t)*(a*(1-t)+b*t)
def interpolate(self, x):
"""
>>> cubicSplineStruct = CubicSplineStruct()
>>> cubicSplineStruct.m_xvalues = [None, 10., 42.]
>>> cubicSplineStruct.m_yvalues = [None, 128., -64.]
>>> cubicSplineStruct.m_kCoeffs = [None, 2., 6.]
>>> cubicSplineStruct.interpolate(18.)
98.0
"""
if len(self.m_xvalues) == 0:
return 0.
intervalLowerBound = findLowerBound(self.m_xvalues, x)
return self.interpolateOnInterval(intervalLowerBound, x)
def computeACoeff(x1, x2, y1, y2, k):
"""
>>> print(computeACoeff( 10., 42., 128., -64., 2.))
256.0
"""
return k*(x2 - x1) - (y2 -y1)
def computeBCoeff(x1, x2, y1, y2, k):
"""
>>> print(computeBCoeff(10., 42., 128., -64., 6.))
-384.0
"""
return -k*(x2 - x1) + (y2 -y1)
def findLowerBound(xvalues, x):
"""
>>> findLowerBound([10., 30.], 9.)
-1
>>> findLowerBound([10., 30.], 10.)
0
>>> findLowerBound([10., 30.], 15.)
0
>>> findLowerBound([10., 30.], 30.)
0
>>> findLowerBound([10., 30.], 31.)
1
>>> findLowerBound([10., 30., 40.], 9.)
-1
>>> findLowerBound([10., 30., 40.], 10.)
0
>>> findLowerBound([10., 30., 40.], 15.)
0
>>> findLowerBound([10., 30., 40.], 30.)
0
>>> findLowerBound([10., 30., 40.], 40.)
1
>>> findLowerBound([10., 30., 40.], 41.)
2
"""
if xvalues[-1] == x:
return len(xvalues) - 2
left = bisect_left(xvalues, x)
if left >= len(xvalues):
return len(xvalues) - 1
if (xvalues[left]==x):
return 0 if left == 0 else left - 1
return left - 1
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T21:47:37.183",
"Id": "219396",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"numpy",
"computational-geometry"
],
"Title": "Cubic spline interpolation in Python from scratch"
} | 219396 |
<p>I am using jQuery data Tables server processing to show some data to user. The <a href="https://datatables.net/manual/server-side" rel="nofollow noreferrer">documentation</a> instructs that the response that the server sends must have this data:</p>
<pre><code>recordsTotal
recordsFiltered
data
</code></pre>
<p>when I am trying to provide this data, I have to query the database 3 times! One for total document count, once for filtered data count and once for the data itself. The whole point of using serverSide processing is to increase the whole performance, but this is too much pain for the server. Any suggestions?</p>
<p><strong>PS1:</strong> I have around 6000 documents in Tests collection, so client side rendering is not an option.</p>
<p><strong>PS2:</strong> Because I am using $lookup I had to use aggregation for search</p>
<p><strong>PS3:</strong> I know the code is a mess right now! (But it's working)</p>
<pre><code>app.post('/getTests', (req, res) => {
var searchStr = {};
if (req.body.search['value']) {
var regex = new RegExp(req.body.search.value, "i");
searchStr = { $or: [{'name': regex }, {'user.lastName': regex}, {'category.title': regex }] };
}
const userLookup = {
$lookup: {
from: 'users',
localField: 'melliCode',
foreignField: 'melliCode',
as: 'user'
}
};
const categoryLookup = {
$lookup: {
from: 'categories',
localField: 'category',
foreignField: '_id',
as: 'category'
}
};
// QUERY NO 1
Test.find().estimatedDocumentCount({}, function(err, c) {
if(err) console.log(err);
let recordsTotal = c;
// QUERY NO 2
Test.aggregate([
userLookup,
categoryLookup,
{
$match: searchStr
},
{
$count: "filtered"
}
])
.then(count => {
const recordsFiltered = count[0].filtered;
// QUERY NO 3
Test.aggregate([
userLookup,
categoryLookup,
{
$unwind: '$user'
},
{
$unwind: '$category'
},
{
$match: searchStr
},
{
$skip: Number(req.body.start) || 0
},
{
$limit: Number(req.body.length),
}
])
.then(results => {
if(!results) return res.send('error');
res.json({
"draw": req.body.draw,
"recordsFiltered": recordsFiltered,
"recordsTotal": recordsTotal,
"data": results
});
})
.catch((error) => {
if(error) console.log(err);
res.send(error)
})
})
.catch((error) => {
console.log(error);
})
})
})
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:07:21.627",
"Id": "423864",
"Score": "0",
"body": "With some databases this can be done with one query. The result of query should tell you how many result rows there are (recordsFiltered) and give you the data. And some databases also have an option to see the total numbers of rows touched (recordsTotal). This is how I do it in PHP with MySQL.... not that that helps you in any way, but now you know it is at least \"possible\". One other thing: I guess you have checked your database indexes? These can have an enormous effect on the speed of queries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T14:49:27.133",
"Id": "423888",
"Score": "0",
"body": "that what I was thinking, there should be a way to get a count in an easier way in mongodb, and yes I have checked my indexes, but again this is not very efficient. @KIKOSoftware"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:27:18.577",
"Id": "219397",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"mongodb",
"jquery-datatables"
],
"Title": "jQuery datatables data rendering from mongodb"
} | 219397 |
<p>I'm trying to implement safe routes and checking if the user is authorized using only Context API.</p>
<p>I'm also trying to avoid that the user can see a <code>PrivateRoute</code>, but I'm not sure if I coverred all edge cases.</p>
<p>Also, is there a better way of doing this? Better implemantation or aproach to this?</p>
<p>I just don't want to use <code>Redux</code> or external libraries.</p>
<p>I made a <a href="https://gist.github.com/EduVencovsky/f8f6c275f42f7352571c92a59309e31d" rel="nofollow noreferrer">gist</a> but I'm also adding the full code here.</p>
<h1>Auth.jsx</h1>
<pre><code>import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { checkIsAuthenticated, authSignUp, authLogin, authLogout } from '../../services/auth'
export const AuthContext = React.createContext({})
export default function Auth({ children }) {
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
checkAuth()
}, [])
const checkAuth = () => checkIsAuthenticated()
.then(() => setIsAuthenticated(true))
.catch(() => setIsAuthenticated(false))
.then(() => setIsLoading(false))
const login = credentials => authLogin(credentials)
.then(setIsAuthenticated(true))
.catch(error => {
alert(error)
setIsAuthenticated(false)
})
const logout = () => {
authLogout()
setIsAuthenticated(false)
}
const signUp = credentials => authSignUp(credentials)
.then(setIsAuthenticated(true))
.catch(error => {
alert(error)
setIsAuthenticated(false)
})
return (
<AuthContext.Provider value={{ isAuthenticated, isLoading, login, logout, signUp }}>
{children}
</AuthContext.Provider>
)
}
Auth.propTypes = {
children: PropTypes.oneOfType([
PropTypes.func,
PropTypes.array
])
}
</code></pre>
<h1>PrivateRoute.jsx</h1>
<pre><code>import React, { useContext } from 'react'
import { Route, Redirect } from 'react-router-dom'
import PropTypes from 'prop-types'
import { AuthContext } from '../Auth/Auth'
import Loading from '../../views/Loading/Loading'
const PrivateRoute = ({ component: Component, ...otherProps }) => {
const { isAuthenticated, isLoading } = useContext(AuthContext)
return (
<Route
{...otherProps}
render={props => (
!isLoading
?
(
isAuthenticated
?
<Component {...props} />
:
<Redirect to={otherProps.redirectTo ? otherProps.redirectTo : '/signin'} />
)
:
<Loading />
)}
/>
)
}
PrivateRoute.propTypes = {
component: PropTypes.func.isRequired
}
export default PrivateRoute
</code></pre>
<h1>example.jsx</h1>
<pre><code>import React from 'react'
import { Switch, Route } from 'react-router-dom'
import PrivateRoute from './components/PrivateRoute/PrivateRoute'
import Auth from './components/Auth/Auth'
import Header from './components/Header/Header'
import HomePage from './views/HomePage/HomePage'
import SignUp from './views/SignUp/SignUp'
import SignIn from './views/SignIn/SignIn'
import FormList from './views/FormList/FormList'
import PageNotFound from './views/PageNotFound/PageNotFound'
export default function App() {
return (
<div>
<Auth>
<Header />
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/signup" component={SignUp} />
<Route path="/signin" component={SignIn} />
<PrivateRoute path="/forms" component={FormList} />
<Route component={PageNotFound} />
</Switch>
</Auth>
</div>
)
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T05:17:36.287",
"Id": "423824",
"Score": "0",
"body": "While there are bound to be more promising places to seek useful feedback on security implications, you are welcome to post your code here at Code Review to seek improvement when you are ready for feedback and criticism on [any aspect of the code](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:02:26.583",
"Id": "423846",
"Score": "0",
"body": "Here is the right place to ask about `Potential security issues`, so my post is correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:43:22.980",
"Id": "423869",
"Score": "1",
"body": "Basically, you are reducing your change of a good review by suggesting you're only interested in security. That's what graybeard is kindly warning you for. Less relevant: I was wondering about the optimistic `100% Secure implementation` in the title. One thing I have learned is that nothing is ever a 100% secure. The moment you start thinking that, the percentage has already dropped markedly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:50:58.880",
"Id": "423871",
"Score": "0",
"body": "@KIKOSoftware Thanks for your comment, now I understand much better, thanks for the advice!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-29T23:57:16.907",
"Id": "219398",
"Score": "1",
"Tags": [
"authentication",
"react.js",
"jsx",
"url-routing"
],
"Title": "Implementation of Private Route with Auth using react-router and Context API"
} | 219398 |
<p>I am writing a python password manager, and I know there's a lot of scrutiny that goes into storing passwords (don't worry, mine aren't plaintext). I was hoping that this community could help me improve style, use of libraries, or anything else. Any and all pointers are gladly accepted.</p>
<p>There were a few ideas that I implemented here:</p>
<ul>
<li>encrypting each password with a unique salt, even in memory</li>
<li>encrypting each database with a unique salt when they are stored long-term</li>
<li>be able to save to a database file (custom format)</li>
<li>be able to read from a database file (custom format)</li>
</ul>
<p>I know that there are a lot of services that do this kind of thing already, but I thought I'd give it a spin, to learn and have fun. Some samples of how to use the library are provided by the runner file.</p>
<p>As this got a lot of attention, my most recent code will be kept on <a href="https://github.com/AndroxxTraxxon/pypassman" rel="nofollow noreferrer">this GitHub repo</a>.</p>
<p>runner:</p>
<pre class="lang-py prettyprint-override"><code>import sys, os
from .passdb import PassDB
if __name__ == "__main__":
a = PassDB()
# print(a)
a.password = "password"
a.set_entry("user", "localhost", "sample_password")
# print(a.enc_str())
a_copy = PassDB.open_db(a.enc_str(), "password")
# print(a_copy.password)
if a_copy is not None:
print(a_copy.get_entry("user@localhost"))
print(a_copy.get_password("user@localhost"))
a_copy.save_as("tmp.passdb", "sample Password")
</code></pre>
<p><code>passdb.py</code>:</p>
<pre class="lang-py prettyprint-override"><code>import base64
import hashlib
import pandas
from Crypto import Random
from Crypto.Cipher import AES
import json
import re
from io import StringIO
import datetime
class PassDB(object):
_valid_init_fields = ["data", "path", "password", "settings"]
version = "Version 0.0.1"
settings: dict
data: pandas.DataFrame
_defaults = {
"salt_size": 64,
"block_size": 32, # Using AES256
"enc_sample_content": "The provided password is correct",
"salt": None,
"path": None,
"hash_depth": 9
}
_format = """### PYPASSMAN {version} ###
{settings}
### SAMPLE ###
{enc_sample}
### DATA ###
{data}
"""
def __init__(self, *args, **kwargs):
if len(args) > 3:
raise TypeError("Too Many Arguments")
if len(args) > 2:
self.data = args[2]
else:
self.data = None
if len(args) > 1:
self.password = args[1]
else:
self.password = None
if len(args) > 0:
self.path = args[0]
else:
self.path = None
for key, arg in kwargs.items():
if key in self._valid_init_fields:
setattr(self, key, arg)
if self.data is None:
self.data = pandas.DataFrame(
columns=[
"account",
"hostname",
"salt",
"password",
"hash_depth",
"dateModified",
"dateCreated"
]
)
if getattr(self, "settings", None) is None:
self.settings = self._defaults.copy()
if self.settings.get("salt", None) is None:
self.settings["salt"] = base64.b64encode(Random.new().read(
self.settings["salt_size"]
)).decode("utf-8")
for key in self._defaults.keys():
if key not in self.settings:
self.settings[key] = self._defaults[key]
@classmethod
def open_db(cls, raw, password):
settings, sample, data = (*map(
lambda string: string.strip(),
re.split(r"###.*###\n", raw)[1:]
),)
settings = json.loads(settings)
sample = cls._decrypt(sample, password, settings["salt"], settings["hash_depth"])
if not sample == settings["enc_sample_content"]:
raise ValueError(
"Cannot open PassDB: incorrect password provided")
data = cls._decrypt(data, password, settings["salt"], settings["hash_depth"])
data = pandas.read_csv(StringIO(data))
output = cls(
settings=settings,
data=data,
password=password
)
return output
def save_as(self, path, password):
settings_cp = self.settings.copy()
settings_cp["path"] = path
new_dict = self.__class__(
data = self.data,
path = path,
password = password,
settings = settings_cp
)
new_dict.save()
return True
def save(self):
with open(self.path, "w+") as dest:
enc_data = self._encrypt(
self.data.to_csv(index_label="index"),
self.password, self.settings["salt"],
self.settings["hash_depth"]
)
enc_sample = self._encrypt(
self.settings["enc_sample_content"],
self.password, self.settings["salt"],
self.settings["hash_depth"])
dest.write(self._format.format(
version=str(self.version),
settings=json.dumps(self.settings),
data=enc_data,
enc_sample=enc_sample
))
@classmethod
def _encrypt(cls, raw, password, salt, hash_depth):
raw = cls._pad(raw)
iv = Random.new().read(AES.block_size)
salt = base64.b64decode(salt)
key = hashlib.sha256(
str(password).encode() + salt
).digest()
for i in range(hash_depth):
key = hashlib.sha256(key + salt).digest()
cipher = AES.new(key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw)).decode("utf-8")
@classmethod
def _decrypt(cls, enc, password, salt, hash_depth):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
salt = base64.b64decode(salt)
key = hashlib.sha256(
password.encode() + salt
).digest()
for i in range(hash_depth):
key = hashlib.sha256(key + salt).digest()
cipher = AES.new(key, AES.MODE_CBC, iv)
try:
return cls._unpad(
cipher.decrypt(
enc[AES.block_size:]
)
).decode('utf-8')
except UnicodeDecodeError:
raise ValueError("Incorrect Password")
@classmethod
def _pad(cls, s):
bs = cls._defaults["block_size"]
return (
s + (bs - len(s) % bs) *
chr(bs - len(s) % bs)
)
@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def enc_str(self):
enc_data = self._encrypt(
self.data.to_csv(index_label="index"),
self.password, self.settings["salt"],
self.settings["hash_depth"]
)
enc_sample = self._encrypt(
self.settings["enc_sample_content"],
self.password, self.settings["salt"],
self.settings["hash_depth"]
)
return (self._format.format(
version=str(self.version),
enc_sample=enc_sample,
settings=json.dumps(self.settings),
data=enc_data
))
def __str__(self):
path = self.settings["path"]
return "PassDB <{} entries{}>".format(
len(self.data),
" at '{}'".format(path) if path is not None else ""
)
def set_entry(self, *args):
account, hostname, password = None, None, None
if len(args) == 1:
account, hostname_password = args[0].split("@")
hostname, password, other = hostname_password.split(":")
elif len(args) == 2:
account_hostname, password = args
account, hostname = account_hostname.split("@")
elif len(args) == 3:
account, hostname, password = args
else:
raise ValueError("""
PassDB.set_entry :: Too many arguments
usage(1): get_password(account, hostname, password)
usage(2): get_password("{account}@{hostname}", password)
usage(3): get_password("{account}@{hostname}:{password}") """
)
for char in (":", "@"):
for item in account, hostname, password:
if char in item:
raise ValueError("""
account, hostname, and password cannot contain colon (:) or at symbol (@)""")
if len(self.data) > 0:
for index, entry in self.data.iterrows():
if entry["account"] == account and entry["hostname"] == hostname:
salt = base64.b64encode(Random.new().read(
self.settings["salt_size"]
)).decode("utf-8")
password = self._encrypt(
password,
self.settings["salt"],
salt,
self.settings["hash_depth"]
)
self.data.loc[index] = (
account, hostname,
salt, password,
self.settings["hash_depth"],
str(datetime.datetime.utcnow().isoformat()),
str(datetime.datetime.utcnow().isoformat())
)
else:
salt = base64.b64encode(Random.new().read(
self.settings["salt_size"]
)).decode("utf-8")
password = self._encrypt(
password,
self.settings["salt"],
salt,
self.settings["hash_depth"]
)
self.data.loc[0] = (
account,
hostname,
salt,
password,
self.settings["hash_depth"],
str(datetime.datetime.utcnow().isoformat()),
str(datetime.datetime.utcnow().isoformat())
)
def get_entry(self, *args):
if len(args) == 1:
account, hostname = args[0].split("@")
elif len(args) == 2:
account, hostname = args
else:
raise ValueError("""
PassDB.get_entry :: Too many arguments
usage(1): get_entry(account, hostname)
usage(2): get_entry("{account}@{hostname}")""")
if(getattr(self, "password") is None):
raise ValueError("Cannot get entry when PassDB instance password is None")
if(len(self.data)) == 0:
return None
for index, entry in self.data.iterrows():
if entry["account"] == account and entry["hostname"] == hostname:
return entry
return None
def get_password(self, *args):
if len(args) == 1:
account, hostname = args[0].split("@")
elif len(args) == 2:
account, hostname = args
else:
raise ValueError("""
PassDB.get_password :: Too many arguments
usage(1): get_password(account, hostname)
usage(2): get_password("{account}@{hostname}")""")
entry = self.get_entry(account, hostname)
if isinstance(entry["password"], str):
return self._decrypt(entry["password"], self.settings["salt"], entry["salt"], entry["hash_depth"])
raise ValueError("Password for {account}@{hostname} in unexpected format".format(**entry))
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T19:11:37.950",
"Id": "423931",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this meta post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T23:12:14.777",
"Id": "423942",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ, sorry. I clearly need to take a closer look at the community guidelines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T00:03:04.083",
"Id": "423943",
"Score": "0",
"body": "Its okay - it happens to many users here..."
}
] | [
{
"body": "<p>Some general tips:</p>\n\n<ol>\n<li>The runner should use <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">argparse</a> to parse arguments. It most definitely should not hardcode passwords.</li>\n<li><code>(object)</code> is redundant in Python 3 class definitions.</li>\n<li><p>I'd recommend running <em>any</em> Python code through Black, flake8 and mypy with a strict configuration like this one:</p>\n\n<pre><code>[flake8]\ndoctests = true\nexclude =\n .git\nmax-complexity = 5\nmax-line-length = 120\nignore = W503,E203\n\n[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n<li>You reuse variable names with completely different semantics. This is a really bad idea for understanding what the code is doing and following along even otherwise trivial logic. For example, <code>settings = json.loads(settings)</code> means that settings is originally a <code>str</code>, effectively a serialized JSON object, and afterwards a <code>dict</code>. These have completely different semantics and interaction patterns. The easiest way to deal with this is to treat almost every variable as <em>immutable,</em> and naming the variables according to what they <em>really</em> are. For example, <code>settings = json.loads(serialized_settings)</code>.</li>\n<li>Names should be descriptive, for example <code>password_database = PasswordDatabase()</code>.</li>\n<li>Don't use <code>*args</code> and <code>**kwargs</code> unless you <em>need</em> dynamic parameter lists. Rather than indexing <code>*args</code> you should use named parameters. If they have default values those should go in the method signature.</li>\n<li><code>.get(foo, None)</code> can be simplified to <code>.get(foo)</code> - <code>get()</code> returns <code>None</code> by default.</li>\n<li><code>if foo is None</code> can in the vast majority of cases be changed to the more idiomatic <code>if foo</code>.</li>\n<li>I would highly recommend using a well-known open format such as the KeePass one for storing this data.</li>\n<li><p>This should not be in there:</p>\n\n<pre><code>if not sample == settings[\"enc_sample_content\"]:\n raise ValueError(\n \"Cannot open PassDB: incorrect password provided\")\n</code></pre></li>\n<li>There is a lot of encoding and decoding happening, which greatly obfuscates the state and looks unnecessary in several places.</li>\n<li>I would not trust this sort of code without a comprehensive test suite.</li>\n</ol>\n\n<p>With the caveat that I'm not a cryptographer:</p>\n\n<ol>\n<li>Salting does not make sense unless you're hashing the password (which you don't want to do in this case). I'll refrain from any other comments on how the salting is done unless someone corrects this.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T06:46:43.103",
"Id": "423831",
"Score": "0",
"body": "I support your note on salting symmetrically encrypted passwords. The random IV in AES CBC should be functionaly equivalent. (Disclaimer: also not a cryptographer here)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:47:53.210",
"Id": "423840",
"Score": "0",
"body": "+1 for #4 implying the validity of variable reuse in cases of tight semantic relevance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:25:28.403",
"Id": "423909",
"Score": "0",
"body": "Could you elaborate on #4? Maybe provide an example? I'm not sure that I understand what you mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:56:18.340",
"Id": "423973",
"Score": "0",
"body": "Regarding point 2 - what are your thoughts on the Zen of Python, specifically \"explicit is better than implicit\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:12:59.767",
"Id": "424035",
"Score": "0",
"body": "@AdamBarnes Yes, but simple is better than complex :) Seriously though, a lot of code would be much more verbose if we always specified the default. I expect `(object)` was removed from Python 3 precisely because it *doesn't* really add any useful information to the reader, while making the code just that little bit less verbose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:44:24.183",
"Id": "424039",
"Score": "0",
"body": "I guess. I suppose a similar argument could possibly be made for `return None` everywhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:24:46.847",
"Id": "424153",
"Score": "0",
"body": "[#8 contradicts PEP 8, at least partially: \"Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!\"](https://www.python.org/dev/peps/pep-0008/#id51)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T01:00:37.823",
"Id": "424163",
"Score": "0",
"body": "@SolomonUcko Hence the \"in the vast majority of cases\". And as you can see from the PEP8 text, it doesn't say \"don't do this,\" it says basically \"consider other falsy values when doing this.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T01:18:21.670",
"Id": "424164",
"Score": "0",
"body": "@l0b0 True. However, in the two cases I found, it is possible to have a (legal IMO) falsy value other than `None`. Also, in these cases, `hasattr` and `in` would respectively be better alternatives."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-23T23:38:23.717",
"Id": "446519",
"Score": "0",
"body": "Re: #7, I prefer including the `None` even though it's the default because [Explicit is better than implicit]. I also have trouble remembering the difference between `get()` and [`getattr()`](https://docs.python.org/3/library/functions.html#getattr) in this respect, because what they do wrt to its presence is inconsistent."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T02:54:11.893",
"Id": "219402",
"ParentId": "219400",
"Score": "19"
}
},
{
"body": "<p>Something about the cryptography:</p>\n\n<ul>\n<li>Do you still use the unmaintained PyCrypto library or the new PyCryptodome (a maintained mostly compatible drop-in-replacement)?</li>\n<li>You are using the CBC mode correctly (random IV for encryption), which is good.</li>\n<li>Data is not authenticated - even encrypted data can be changed without the possibility to detect. You can use HMAC (hash based message authentication code) or an AEAD (authenticated encryption with additional data) encryption mode.</li>\n<li>Your password derivation function has good ideas (Rounds + Salt), but is still a bit weak: Only 9 rounds by default are too less for todays standards. As the derivation functions apply the same ideas as for password storage, consider looking at those: E.g. PBKDF2 (which is included in Python) or Argon2 (one of the most modern).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:45:20.040",
"Id": "219434",
"ParentId": "219400",
"Score": "5"
}
},
{
"body": "<h3>concerning <code>is None</code></h3>\n\n<p>In case of <code>self.data</code> (pandas DataFrame) your usage of <code>if foo is None</code> is the only valid option. In the other cases I disagree with the opinion, that <code>if not foo</code> is better than <code>if foo is None</code>, as it is in no way generally correct to assume that an empty object should be handled by the if-clause. An <code>if foo is None</code> explicitley tells me, that there is only a single case, that needs special treatment. However, you have some rather strange constructs: I don't see the reason for using <code>getattr</code> in <code>if(getattr(self, \"password\") is None)</code> (also: redundant parentheses). This should be just <code>if self.password is None</code> - or <code>if not self.password</code> in case you also want to refuse empty passwords. There are other ones, but they mostly originate from you rather complicated <code>__init__</code> mechanisms.</p>\n\n<h3>concerning <code>__init__</code></h3>\n\n<p>Your constructor is too complicated. It either takes keyword arguments, that it maps, or maps arguments that may come via command line. I highly recommend to split the two cases: Create an alternative constructor as classmethod <code>from_cli</code> that parses the command line arguments (<code>argparse</code> or similar), and uses them as named arguments for the real constructor, that needs a clear signature like <code>__init__(self, data=None, path=None, password=None, settings=None)</code> and sets the member variables explicitely. That way it's much easier to grasp, what state an instance of <code>PassDB</code> is in after creation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T12:05:26.017",
"Id": "423974",
"Score": "0",
"body": "Thanks for your feedback! Due to the community guidelines, I'm not allowed to update the code once I've received my inital feedback. If you look on the repo I posted in the question, you'll see that I dramatically simplified my init method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T10:08:02.273",
"Id": "219484",
"ParentId": "219400",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219402",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T00:49:13.317",
"Id": "219400",
"Score": "12",
"Tags": [
"python",
"python-3.x",
"security",
"aes"
],
"Title": "Python password manager"
} | 219400 |
<p>A json i have provided which is actually i am getting by hitting a Rest Service.
To keep it simple I have provided that directly inside the method.
A modal with textarea and accepr/Reject button has been given.</p>
<pre><code>Input Json:{
"Reference No":"101",
"Date Of Reporting":"2019/04/29",
"Status":"",
"Comments":"",
"Organization Name":"ABC"
}
Conditons:
1.Set the data entered in the textarea value to "Comments" in json.
2.Transform the date format to 2019-04-29 and set it to "Date Of Reporting" by comaparing key name contains "date" .
3.set the status value as A or R based on the onclick button value passed to the method below.
4.Keep all other json data as same.
</code></pre>
<p>I have provided the code I have done and it is working fine.</p>
<p>Can anyone help me with some better optimal solutions?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function tansformJson(btn){
var jsonStr={
"Reference No":"101",
"Date Of Reporting":"2019/04/29",
"Status":"",
"Comments":"",
"Organization Name":"ABC"
}
var jsonData = {};
var y=document.getElementsByTagName('textarea');
for (var key in jsonStr) {
if (jsonStr.hasOwnProperty(key)) {
if(key=="Comments"){
jsonData[key] = y[0].value;
}
else if(key.toLowerCase().includes("date")){
var date = new Date(jsonStr[key]);
var value =date.getFullYear()+ '-' +(date.getMonth() + 1) + '-' + date.getDate();
jsonData[key]=value;
}else if(key=='Status'&& btn=='approve'){
jsonData[key]='A';
}else if(key=='Status'&&btn=='reject'){
jsonData[key]='R';
}else
jsonData[key]=jsonStr[key];
}
}
console.log(jsonData);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Comments</h5>
</div>
<div class="modal-body">
<textarea rows="3" cols="50"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="tansformJson('approve')">Accept</button>
<button type="button" class="btn btn-primary" onclick="tansformJson('reject')">Reject</button>
</div>
</div>
</div></code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T06:51:05.830",
"Id": "219405",
"Score": "1",
"Tags": [
"javascript",
"json"
],
"Title": "Code for checking several conditions for the below json transformation"
} | 219405 |
<p>I have an attendance list like this.</p>
<p><strong>problem:</strong> I need to set <code>In</code> and <code>Out</code> alternatively. but if I have only 3 records then I need to set 0 record In true. 1 record out is true. and 3 record has is both <code>In</code> <code>Out</code> is <code>false</code>. I tried like this its working fine. but I was checking is there any better way </p>
<pre><code>ObservableCollection<EmployeeAttandance> attendancesPerDay = new ObservableCollection<EmployeeAttandance>();
if (attendancesPerDay.Count % 2 == 0)
{
int counter = 0;
foreach (var attendance in attendancesPerDay)
{
if (counter % 2 == 0)
attendance.In = true;
else
attendance.Out = true;
counter++;
}
}
else
{
int counter = 0;
foreach (var attendance in attendancesPerDay)
{
if (attendancesPerDay.IndexOf(attendance) == attendancesPerDay.Count - 1)
continue;
if (counter % 2 == 0)
attendance.In = true;
else
attendance.Out = true;
counter++;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:05:09.880",
"Id": "423847",
"Score": "2",
"body": "It would be helpful for the review if the source of entire function was in the question. It would be even more helpful if the entire class and the definition of attendance was included in the question. We need more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:06:48.043",
"Id": "423848",
"Score": "0",
"body": "@pacmaninbw the class big"
}
] | [
{
"body": "<p>In the else clause it might be better to have an <code>if</code> statement with a block of code than a <code>continue</code> statement:</p>\n\n<pre><code> foreach (var attendance in attendancesPerDay)\n {\n if (attendancesPerDay.IndexOf(attendance) != attendancesPerDay.Count - 1)\n {\n if (counter % 2 == 0)\n attendance.In = true;\n else\n attendance.Out = true;\n counter++;\n }\n }\n</code></pre>\n\n<p>The logic is basically the same and it is easier to see the scope of the code.</p>\n\n<p>To reduce the repetition of the code there could be a short function that takes 2 parameters, <code>counter</code> and <code>attendance</code> and performs the assignment.</p>\n\n<p>As a personal choice I prefer to specify the real type in a <code>foreach</code> loop because it is self documenting, the user of <code>var</code> hides too much.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T10:03:46.010",
"Id": "423968",
"Score": "0",
"body": "`In` should have `out` lets say i have 4 records then no problem `0 is in= true` `1 is out=true`` 2 in = true` `3 out =true done`. in case I got only 3 records then` 0 in =true 1 out =true 2 both in and out is false`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T10:04:22.987",
"Id": "423969",
"Score": "0",
"body": "so this thing don`t set anything for last record always"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:33:34.893",
"Id": "219424",
"ParentId": "219407",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T07:20:41.807",
"Id": "219407",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Setting alternative records true if its even count else leave last record"
} | 219407 |
<p><strong>Question</strong></p>
<blockquote>
<p>Say you have an array for which the ith element is the price of a
given stock on day i.</p>
<p>If you were only permitted to complete at most one transaction (i.e.,
buy one and sell one share of the stock), design an algorithm to find
the maximum profit.</p>
<p>Note that you cannot sell a stock before you buy one.</p>
</blockquote>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1)
and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than
buying price.
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
</code></pre>
<p>My Approach is brute force.(Naive approach)
Take each element and iterate through right to see how much profit can be made.</p>
<pre><code>public int maxProfit(int[] prices) {
int size = prices.length;
if(size == 0 || size == 1) {
return 0;
}
int maxProfit = 0;
// Iterate through each right element.
for(int i =0; i<size; i++) {
for(int j = i+1; j<size; j++) {
if(prices[j] > prices[i]) {
int diff = prices[j] - prices[i];
if(diff > maxProfit) {
maxProfit = diff;
}
}
}
}
return maxProfit;
}
</code></pre>
<p>How can I improve this from <strong><em>O(n2)</em></strong> . Also, what if more than 1 transactions are allowed to get the profit.</p>
| [] | [
{
"body": "<p>I assume this assignment if for your own exercise, so giving you the source code of the solution is contraproductive. So I will only give you hints how to rewrite your code. Once done, post it here and we can compare it with my solution.</p>\n\n<ul>\n<li>You can avoid a whole inner loop cycle if you look ahead one item in your outer loop. In your example 1, your first loop would compare 7 with all others. Your second loop would compare 1 with all others. Since 1 < 7 you can skip comparing with all others in your first loop and only do the comparisons in your second loop. That means if it gets cheaper to buy every day, then skip until the day it becomes more expensive.</li>\n<li>You can avoid a whole inner loop cycle if you remember the old value from the outer loop and compare it to the current value. That means in your example, you compare buyPrice=1 and buyPrice=5. Because 1 < 5, you can skip the inner loop for 5 and just leave maxProfit as it is. In other words, the profit cannot become bigger if you buy it more expensive the next day(s) and sell it with the same price.</li>\n<li>Once you go through the inner loop, remember the maximum selling price and its position. The next time you go through the inner loop, you can reuse this maximum instead of iterating through all elements. (of course only if its position is still inside the new inner loop elements). </li>\n<li>Just delete the line \"if(prices[j] > prices[i])\". Subtracting two integers is as fast as comparing them in machine language. </li>\n<li>Follow DRY principle (clean code, red grade): instead of copy-pasting \"prices[j]\" just assign it to a variable with a meaningful name, for example \"int buyPrice=prices[j]\", in opposition to \"int sellPrice=prices[i]\".</li>\n<li>Guard your code: \"prices.length\" can throw a nullPointerException!</li>\n<li>\"if(size == 0 || size == 1)\" can be written faster and more clearly as \"if(size <= 1)\"</li>\n</ul>\n\n<p>The maxProfit from your example 1 is 6 - 1 = 5. If more than 1 transaction is allowed, you could buy for 1 (second day) and sell for 5 (third day), then you could again buy for 3 (fourth day) and sell for 6 (fifth day). You overall profit would be 5-1 + 6-3 = 7. That's much more than if only 1 transaction is allowed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:24:22.830",
"Id": "423965",
"Score": "0",
"body": "Thanks @Chaarman, your suggestions are really valuable."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T09:33:36.953",
"Id": "219416",
"ParentId": "219410",
"Score": "0"
}
},
{
"body": "<p>Your use of whitespace is inconsistent, which makes the code harder to read and understand. There should be whitespace between control flow statements and open parentheses, and there should be whitespace on both sides of operators.</p>\n\n<p>Your comment is noise and should be deleted.</p>\n\n<p>Unless leetcode promises you'll never get a null input, you should check to make sure the <code>prices</code> array is not null.</p>\n\n<p>It's cleaner to check if the array length is <code>< 2</code> rather than enumerating the cases. Also, your algorithm works correctly without the check, since the loop falls through correctly.</p>\n\n<p><code>size</code> should be marked as final since it does not change. There's also no real value in storing this in a variable, since it's obvious what <code>prices.length</code> is, and it's not a computed value.</p>\n\n<p>You can use <code>Math.max()</code> instead of doing subtraction and int comparison yourself. It makes the code easier to read.</p>\n\n<p>You can save a comparison in some cases by always doing the subtraction. It's easier to read, and in some cases will be faster.</p>\n\n<p>If you were to make all these changes, your code might look more like:</p>\n\n<pre><code>public int maxProfit(final int[] prices) {\n if (prices == null) {\n return 0;\n }\n\n int maxProfit = 0;\n\n for (int i = 0; i < prices.length; i++) {\n for (int j = i + 1; j < prices.length; j++) {\n maxProfit = Math.max(maxProfit, prices[j] - prices[i]);\n }\n }\n\n return maxProfit;\n}\n</code></pre>\n\n<p>As far as algorithmic performance, you can do this in <code>O(n)</code> time and <code>O(1)</code> space. Walk through the input array one time, tracking the minimum value seen so far and the current best profit. At each step, update those two values. </p>\n\n<pre><code>public int maxProfit(final int[] prices) {\n if (prices == null) {\n return 0;\n }\n\n int minPrice = Integer.MAX_VALUE;\n int maxProfit = 0;\n\n for (int i = 0; i < prices.length; i++) {\n maxProfit = Math.max(maxProfit, prices[i] - minPrice);\n minPrice = Math.min(minPrice, prices[i]);\n }\n\n return maxProfit;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:22:35.717",
"Id": "423963",
"Score": "0",
"body": "Thanks @Eric Stein for clean code approach, null pointer check ( we can add prices size as well, if its less than equal to 1 then also return 0), and traversing with pointers. This solution is much much better!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:23:42.107",
"Id": "423964",
"Score": "0",
"body": "Just wondering, how can we extend this solution to work for if multiple transactions are allowed to get maximum profit. Then what should be the max profit. (Can't buy stock without selling first)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:11:10.857",
"Id": "423984",
"Score": "0",
"body": "@Mosbius8 I believe both code blocks work correctly for arrays of size zero and one. No changes should be required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:12:21.887",
"Id": "423986",
"Score": "0",
"body": "As far as multiples go, I think you're going to need a Dynamic Programming solution. I don't believe a linear solution exists."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:59:00.500",
"Id": "219431",
"ParentId": "219410",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:27:02.043",
"Id": "219410",
"Score": "1",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Leeetcode - Best time to buy and sell stock to get maximum profit"
} | 219410 |
<p>This is my <code>Result</code> class:</p>
<pre><code>public class Result
{
public DateTime Checked { get; set; }
public bool IsWorking { get; set; }
}
</code></pre>
<p>Let's say I have theese results in list:</p>
<pre><code>Date: ..., IsWorking = true;
Date: ..., IsWorking = true;
Date: ..., IsWorking = false;
Date: ..., IsWorking = false;
Date: ..., IsWorking = true;
Date: ..., IsWorking = false;
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;
</code></pre>
<p>I want to split them as following:</p>
<pre><code>// group 1
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;
// group 2
Date: ..., IsWorking = false;
Date: ..., IsWorking = false;
// group 3
Date: ..., IsWorking = true;
// group 4
Date: ..., IsWorking = false;
// group 5
Date: ..., IsWorking = true;
Date: ..., IsWorking = true;
</code></pre>
<p>I've managed something like this:</p>
<pre><code>public static List<List<T>> SplitByEqualProperty<T>(this IEnumerable<T> inputs, string property)
{
List<List<T>> temp = new List<List<T>>();
temp.Add(new List<T>());
object previousSelector = null;
for (int i = 0; i < inputs.Count(); i++)
{
var current = inputs.ElementAt(i);
Type t = current.GetType();
PropertyInfo prop = t.GetProperty(property);
object currentSelector = prop.GetValue(current);
if (previousSelector == null)
{
temp.LastOrDefault().Add(current);
}
else
{
if (currentSelector.Equals(previousSelector))
{
temp.LastOrDefault().Add(current);
}
else
{
temp.Add(new List<T>() { current });
}
}
previousSelector = currentSelector;
}
return temp;
}
</code></pre>
<p>And this is working, but I don't like the code. Expecially part with <code>string property</code>. How can I improve that?</p>
| [] | [
{
"body": "<p>You've tagged this <a href=\"/questions/tagged/linq\" class=\"post-tag\" title=\"show questions tagged 'linq'\" rel=\"tag\">linq</a> so you're clearly aware of Linq, but this is not a Linq-like approach. The closest approximation in Linq is <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.groupby?view=netframework-4.8#System_Linq_Enumerable_GroupBy__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__\" rel=\"nofollow noreferrer\"><code>GroupBy</code></a>, so that can serve as a model:</p>\n\n<ol>\n<li>Instead of <code>string property</code> take <code>Func<TSource, TKey></code>.</li>\n<li>Instead of <code>List<List<T>></code> (which, apart from anything else, violates the principle of coding to the interface instead of the implementation) return <code>IEnumerable<IGrouping<TKey, TSource>></code> (or, if you don't care about the value itself, <code>IEnumerable<IEnumerable<TSource>></code>).</li>\n</ol>\n\n<p>Also, in Linq style, favour lazy implementation with <code>yield return</code>.</p>\n\n<p>I would advise you to rewrite from scratch with those principles in mind.</p>\n\n<hr>\n\n<p>But I must address one major problem in this code, lest you repeat it in the rewrite:</p>\n\n<blockquote>\n<pre><code> for (int i = 0; i < inputs.Count(); i++)\n {\n var current = inputs.ElementAt(i);\n</code></pre>\n</blockquote>\n\n<p>This is absolutely the wrong way to iterate over an <code>IEnumerable</code>. The right way is</p>\n\n<pre><code> foreach (var current in inputs)\n {\n</code></pre>\n\n<p>Otherwise if <code>inputs</code> is lazy you do far more work than necessary, and potentially execute side-effects more times than you might expect.</p>\n\n<hr>\n\n<p>Also,</p>\n\n<blockquote>\n<pre><code> if (previousSelector == null)\n</code></pre>\n</blockquote>\n\n<p>is problematic. What if this method is used with objects which actually have <code>null</code> as a value of the relevant property? I think the best approach is to use the current <code>IGrouping</code>: either initialise that to <code>null</code> and test whether it's null, or initialise it to a grouping with key <code>default(T)</code> and replace the special case with a special case which doesn't return an empty grouping.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:57:36.707",
"Id": "219414",
"ParentId": "219412",
"Score": "5"
}
},
{
"body": "<p>Here's a <code>Linq</code> approach that allows you to perform an <em>analytical function</em> on a collection, given a <em>order by</em> clause, and a <em>predicate</em> to determine whether the current item and the previous item (<em>analytical lag</em>) are in the same group. It can be extended to also take into account a <em>partition</em>, but that's out of scope to serve your purpose.</p>\n\n<p>This is a more generalized approach for the OP's <em>SplitByEqualProperty</em> method. I have augmented the problem into not just <em>equal property check</em>, but any kind of property check. Because of this generalization, I opt to use IEnumerable over IGrouping.</p>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Globalization;\n\npublic class Program\n{\n public static void Main()\n {\n var results = new List<Result> \n {\n Create(\"JAN\", true), Create(\"FEB\", true),\n Create(\"MAR\", false),\n Create(\"APR\", true),\n Create(\"MAY\", false), Create(\"JUN\", false), Create(\"JUL\", false),\n Create(\"AUG\", true),\n Create(\"SEP\", true), Create(\"OCT\", true),\n Create(\"NOV\", false), Create(\"DEC\", false),\n };\n\n var grouped = results.JoinBy(\n x => x.Checked, \n x => x.IsWorking, \n (previous, current) => previous == current);\n }\n\n internal static Result Create(string month, bool isWorking) {\n return new Result {\n Checked = DateTime.ParseExact(\"2019\" + month + \"01\", \"yyyyMMMdd\", CultureInfo.InvariantCulture),\n IsWorking = isWorking\n };\n }\n\n public class Result\n {\n public DateTime Checked { get; set; }\n public bool IsWorking { get; set; }\n }\n}\n</code></pre>\n\n<p><strong>Linq</strong></p>\n\n<pre><code>public static class LinqExtension\n{\n public static IEnumerable<IEnumerable<TSource>> JoinBy<TSource, TOrderKey, TKey>(\n this IEnumerable<TSource> source,\n Func<TSource, TOrderKey> orderBy,\n Func<TSource, TKey> keySelector,\n Func<TKey, TKey, bool> join) {\n var results = new List<List<TSource>>();\n var orderedSource = new List<TSource>(source).OrderBy(orderBy).ToArray();\n\n if (orderedSource.Length > 0) {\n var group = new List<TSource> { orderedSource[0] };\n results.Add(group);\n if (orderedSource.Length > 1) {\n for (int i = 1; i < orderedSource.Length; i++) {\n var lag = orderedSource[i - 1];\n var current = orderedSource[i];\n if (join(keySelector(lag), keySelector(current))) {\n group.Add(current);\n }\n else {\n group = new List<TSource> { current };\n results.Add(group);\n }\n }\n }\n }\n\n return results;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T12:29:50.687",
"Id": "425958",
"Score": "0",
"body": "Since this is about grouping, I think it would be better if the return value of `JoinBy` was `IEnumerable<IGrouping<TKey, TSource>>`. Oh, one more thing, you have presented an alternative version without mentioning anything in particular about OP's code... On Code Review this is _usually_ required..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T12:36:45.547",
"Id": "425959",
"Score": "1",
"body": "@t3ch0t Thanks for the tip about community guidelines. About the Grouping vs Enumerable dilemma: my code isn't necessarely a grouped-by-key collection, instead the 'join' clause can also group on any function between comparing two adjacent keys."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-18T11:58:46.347",
"Id": "220462",
"ParentId": "219412",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T08:34:43.817",
"Id": "219412",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "Group list into elements with same value"
} | 219412 |
<p>On my server I have a large json that is accessed by several applications. One application only needs a certain part of the json, so presenting the whole json to the application is an unnecessary increase of bandwith. (Original JSON: about 40 KB, Optimized JSON: about 500 b)</p>
<p>What I came up with is a php script to which every application sends the application name. The script then reads the json on the server and prints out the shrinked json for the application to read. It works, but I'm concerned about wheter the php script could possibly put the server processing capabilities to its limits. Is there a more efficient solution over mine?</p>
<p>Note:
The part before the "ids" object is needed by all applications, that's why the php script just echo it out.
If an application fails to send its name to the server, the server just outprints the raw json.</p>
<p>The raw JSON as it exists on the server: </p>
<pre><code>{
"a": 0,
"d": 0,
"pD": "ok",
"p": "ok",
"an": "123",
"slider_1": ["One Slider", "https://example.com/1"],
"slider_2": ["Two Slider", "https://example.com/2"],
"ids": {
"Application One": {
"info one": "210799155",
"info two": "1544002021777"
},
"Application Two": {
"info one": "211061341",
"info two": "0000000",
},
.
.
.
much more Applications
</code></pre>
<p>The PHP script to optimize:</p>
<pre><code><?php
//Read and decode the json file on the server
$txt = fread(fopen("json", "r"),filesize("json"));
$json =json_decode($txt,true);
//Echo the part needed by every applicaition
echo '{
"a": 0,
"d": 0,
"pD": "ok",
"p": "ok",
"an": "123",
"slider_1": ["One Slider", "https://example.com/1"],
"slider_2": ["Two Slider", "https://example.com/2"],
"ids": { "' . $_GET["id"] . '" :';
$s = json_encode($json["ids"][$_GET["id"]]);
//check if the application failed to send the name
if ($s === "null"){
ob_end_clean();
echo $txt;
exit();
}else{
//write the application specific part of the json
echo $s;
}
echo "}}";
</code></pre>
| [] | [
{
"body": "<p>The code can be slightly improved, but it won't make much of a difference overall. This whole approach seems a bit weird. Why does the JSON file exist in the first place?</p>\n\n<p>Here is the 'improved' version:</p>\n\n<pre><code><?php\n\n// read the json file on the server\n$txt = file_get_contents(\"json\");\n\n// get the id of the application\n$id = filter_input(INPUT_GET, \"id\", FILTER_SANITIZE_STRING); \nif (isset($id)) {\n // decode json\n $json = json_decode($txt, true);\n // remove all other ids from the list\n $appInfo = $json[\"ids\"][$id];\n unset($json[\"ids\"]);\n $json[\"ids\"][$id] = $appInfo;\n // encode and return json\n echo json_encode($json);\n}\nelse {\n // simply echo the content\n echo $txt;\n}\n</code></pre>\n\n<p>I sanatized the input by using <code>filter_input()</code>. That's not really needed, but always a good idea. I also simplified the code a bit more. </p>\n\n<p>This is only a tiny piece of code, so there's not much I can do. I have a feeling that more could be achieved if we knew why you do this in the first place. What is this JSON used for?</p>\n\n<p>=============================================</p>\n\n<p>I couldn't resist proposing the code below for the \"filechanger\".</p>\n\n<pre><code><?php\n\n// read the json file on the server\n$txt = file_get_contents(\"json\");\n// decode json\n$json = json_decode($txt, true);\n// get all application information\n$appInfos = $json[\"ids\"];\n// write the to separate files\nforeach ($appInfos as $appId => $appInfo) {\n // set application info\n unset($json[\"ids\"]);\n $json[\"ids\"][$appId] = $appInfo;\n // create file name\n $filename = str_replace(\" \", \"_\", $appId) . \".json\";\n // encode and save json\n file_put_contents($filename, json_encode($json));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:33:45.510",
"Id": "423855",
"Score": "0",
"body": "The Json exist to maintain the different applications from a server and to set customized content tailored to the individual applications"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:36:45.097",
"Id": "423856",
"Score": "0",
"body": "Yes, I got that, but, sorry for saying it like this, it is a bit vague. I do realize it is difficult to explain. But I could imagine having separate JSON files for each application. No need to go through PHP then. This is just an example, there could be many other ways of doing it better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:39:23.520",
"Id": "423857",
"Score": "0",
"body": "Then there would arise the following concerns: 1. what is more efficient: to have this script or to have 150 json files? 2. While having 150 files, maintaining the part that is needed by every application will become very hard (Unless I programm a \"Filechanger\"). Furthermore, the json can change 2 to 3 times a day, so having an agile way of doing this update task is crucial"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:41:40.570",
"Id": "423858",
"Score": "0",
"body": "The 150 JSON files will be more efficient, for sure. The part needed by every application could just be a separate JSON file. Each application then reads two file: the general file used by all applications and a file tailored to that application's needs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:44:35.300",
"Id": "423860",
"Score": "0",
"body": "Maybe I'll then go with the approach of a \"filechanger\". a php script that when runned reads the big json and then generates 150 small json files. that way I can alter the big json and then run the php script with ease. Seems efficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:44:48.330",
"Id": "423861",
"Score": "0",
"body": "Updating the JSON files is a whole other matter. But since that is done very infrequent, I don't see a real problem there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:45:48.613",
"Id": "423862",
"Score": "1",
"body": "Ah, yes, that is a good idea. I can support that completely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:46:12.350",
"Id": "423863",
"Score": "0",
"body": "Perfect, thanks for your time"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T11:28:52.590",
"Id": "219422",
"ParentId": "219417",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219422",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T09:46:02.403",
"Id": "219417",
"Score": "1",
"Tags": [
"php",
"json"
],
"Title": "Read and output a json object with the least server processing expenditure possible"
} | 219417 |
<p>I have a nested array that represents a parent child relationship, that I need to convert to a tree structure. </p>
<p><em>Example nested array</em></p>
<pre><code>list = [
['lvl-1 item-1', 'lvl-2 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-2'],
['lvl-1 item-2', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-2', 'lvl-2 item-2', 'lvl-3 item-2', 'lvl-4 item-1'],
]
</code></pre>
<p>Each tree node has the following structure. </p>
<pre><code>{
name: "item",
parent: "parent_name",
children: []
}
</code></pre>
<p>Each item in the nested array represents a level in the object.</p>
<p><em>Expected JSON</em></p>
<pre><code>{
"name": "0",
"parent": null,
"children": [
{
"name": "lvl-1 item-1",
"parent": "0",
"children": [
{
"name": "lvl-2 item-1",
"parent": "lvl-1 item-1",
"children": [
{
"name": "lvl-3 item-1",
"parent": "lvl-2 item-1",
"children": []
},
{
"name": "lvl-3 item-2",
"parent": "lvl-2 item-1",
"children": []
}
]
}
]
},
{
"name": "lvl-1 item-2",
"parent": "0",
"children": [
{
"name": "lvl-2 item-1",
"parent": "lvl-1 item-2",
"children": [
{
"name": "lvl-3 item-1",
"parent": "lvl-2 item-1",
"children": []
}
]
},
{
"name": "lvl-2 item-2",
"parent": "lvl-1 item-2",
"children": [
{
"name": "lvl-3 item-2",
"parent": "lvl-2 item-2",
"children": [
{
"name": "lvl-4 item-1",
"parent": "lvl-3 item-2",
"children": []
}
]
}
]
}
]
}
]
}
</code></pre>
<p>The code below is what I came up with, but there is a lot of room for improvement. </p>
<p>First I loop each item in the list and all of its children.</p>
<p>I add each level name to a parent array so I can navigate it later to find existing child objects. Once I hit the end of the child loop I add the current level to the parent for use on the next iteration. </p>
<p>Once I've reached the end of the parents for loop I check if the current name exists in the children and add it if not. </p>
<p>This was produced with a lot of trial and error, I'm struggling to explain it accurately.</p>
<p>Can someone help me to review this code, to better understand it and improve it. </p>
<p>I had trouble getting the initial structure to work, I ended up creating what I believe is a redundant object with a <code>children</code> field so that it matched the expected format.</p>
<p>Any help will be much appreciated. If there is anything I haven't explained clearly please let me know.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>list = [
['lvl-1 item-1', 'lvl-2 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-2'],
['lvl-1 item-2', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-2', 'lvl-2 item-2', 'lvl-3 item-2', 'lvl-4 item-1'],
];
console.log(nestedArrayToJson(list));
function nestedArrayToJson(structure) {
const top_item = '0';
let data = {
children: [
{
name: top_item,
parent: null,
children: [],
}],
};
for(let i = 0; i < structure.length; i++) {
let parents = [top_item];
for(let j = 0; j < structure[i].length; j++) {
let obj = data;
for(parent of parents) {
obj = obj.children.find(o => o.name === parent);
}
const name = structure[i][j];
if(!obj.children.find(o => o.name === name)) {
obj.children.push({
name,
parent,
children: [],
});
}
parents.push(structure[i][j]);
}
}
return data.children[0];
}</code></pre>
</div>
</div>
</p>
<h2>Updated Script</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>list = [
['lvl-1 item-1', 'lvl-2 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-1', 'lvl-2 item-1', 'lvl-3 item-2'],
['lvl-1 item-2', 'lvl-2 item-1', 'lvl-3 item-1'],
['lvl-1 item-2', 'lvl-2 item-2', 'lvl-3 item-2', 'lvl-4 item-1']
]
function createTree(arr, topItem = "Top") {
const node = (name, parent = null) => ({
name,
parent,
children: []
});
const addNode = (parent, child) => {
parent.children.push(child);
return child;
};
const findNamedNode = (name, parent) => {
for (const child of parent.children) {
if (child.name === name) {
return child
}
const found = findNamedNode(name, child);
if (found) {
return found
}
}
};
const top = node(topItem);
let current;
for (const children of arr) {
current = top;
for (const name of children) {
const found = findNamedNode(name, current);
current = found ? found : addNode(current, node(name, current.name));
}
}
return top;
}
console.log(createTree(list, 'lvl-0 item-1'))</code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Vernacular</h2>\n<p>Naming is very important and it starts by using the correct terminology.</p>\n<p>There is no such thing as a JSON object as you use the term. There are JSON strings and JSON files. There is also a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON\" rel=\"nofollow noreferrer\">JSON</a> built-in Object. It provides an API to help convert between Objects and JSON strings</p>\n<p>JavaScript uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\">Object</a> to store data in the form of properties.</p>\n<p>Objects can be converted to JSON string using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify\" rel=\"nofollow noreferrer\"><code>JSON.stringify</code></a>, or can be created from a JSON string using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"nofollow noreferrer\"><code>JSON.parse</code></a>. Not all object can be converted to JSON, while all valid JSON strings can be converted to an Object.</p>\n<p>Your question title makes no sense...</p>\n<blockquote>\n<p><em>"Convert nested array of values to a JSON object"</em></p>\n</blockquote>\n<p><em>"JSON object"</em> is more meaningfully as <a href=\"https://en.wikipedia.org/wiki/Tree_(data_structure)\" rel=\"nofollow noreferrer\">tree</a></p>\n<p>"Convert nested array into a tree"</p>\n<h2>Style</h2>\n<ul>\n<li>The variables <code>data</code> and <code>parent</code> should be declared as constants <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> as the references they hold do not change.</li>\n<li>The JavaScript naming convention is <a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a> try to avoid using <a href=\"https://en.wikipedia.org/wiki/Snake_case\" rel=\"nofollow noreferrer\">snake_case</a>. Eg the name <code>top_item</code> should be <code>topItem</code>\nThe only time that snake_case is used is for some types of constants, in which case we use use SNAKE_UPPER_CASE.</li>\n<li>When possible (you don't need the array index) use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loop rather than a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"nofollow noreferrer\"><code>for(;;)</code></a> loop</li>\n</ul>\n<h2>Code logic</h2>\n<h3>Functions</h3>\n<p>Good code tries to avoid doing too much in one function. Breaking the code into distinct tasks and assigning those tasks to functions make it easier to manage as the complexity starts to grow.</p>\n<p>You create the node object in two places. Good source code avoids repetition. The most conman way to avoid repetition is to create functions that do the same or similar things via a call.</p>\n<p>You need to search the node to locate where to add new child nodes. The simplest way to search a tree is via a recursive function. Recursive functions exploit the similarity of nested data to reduce the complexity of the code.</p>\n<h3>Avoid redundancies</h3>\n<p>There is no need to create the <code>data</code> object as a top level parent. The child of <code>data</code>, <code>data.children[0]</code> can serve as the top parent.</p>\n<h2>Rewrite</h2>\n<p>We can rewrite the code breaking it into smaller functions.</p>\n<p>There are 3 functions in the main one</p>\n<ol>\n<li><code>node</code> creates a new node</li>\n<li><code>addNode</code> adds a node to a parent node</li>\n<li><code>findNamedNode</code> will find a node with a name. If that node does not exist it returns <code>undefined</code></li>\n</ol>\n<p>The main body of the function just iterated each array, searching for each node by name. If one is found it moves to the next. If no node is found it creates and adds a new one.</p>\n<pre><code>function createTree(structure, topItem = "Top") {\n const node = (name, parent = null) => ({name, parent, children: []});\n const addNode = (parent, child) => (parent.children.push(child), child);\n const findNamedNode = (name, parent) => {\n for (const child of parent.children) {\n if (child.name === name) { return child }\n const found = findNamedNode(name, child);\n if (found) { return found } \n }\n }\n const TOP_NAME = "Top";\n const top = node(TOP_NAME);\n var current;\n\n for (const children of structure) {\n current = top;\n for (const name of children) {\n const found = findNamedNode(name, current);\n current = found ? found : addNode(current, node(name, current.name));\n }\n }\n return top;\n}\n</code></pre>\n<p>To make sure it all worked (no typos or idiotic coder intrusion) the snippet run it once on a simple data set.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>logTree(createTree(data()));\n\nfunction createTree(structure) {\n const node = (name, parent = null) => ({name, parent, children: []});\n const addNode = (parent, child) => (parent.children.push(child), child);\n const findNamed = (name, parent) => {\n for (const child of parent.children) {\n if (child.name === name) { return child }\n const found = findNamed(name, child);\n if (found) { return found } \n }\n }\n const TOP_NAME = \"Top\", top = node(TOP_NAME);\n for (const children of structure) {\n let par = top;\n for (const name of children) {\n const found = findNamed(name, par);\n par = found ? found : addNode(par, node(name, par.name));\n }\n }\n return top;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n function data() { return [['A1', 'B1'],['A1', 'B1', 'C1'],['A1', 'B1', 'C2'],['A2', 'B1', 'C1'],['A2', 'B2', 'C2', 'D1'],['A2', 'B2', 'C2', 'D2'],['A2', 'B2', 'C2', 'D3'],['A2', 'B2', 'C2', 'D4'],['A2', 'B2', 'C2', 'D5'],['A2', 'B3', 'C1', 'D1'],['A3', 'B1', 'C1', 'D1'],['A3', 'B1', 'C1', 'D2'], ['A3', 'B1', 'C1', 'D3']]; }\n\n\n\n\n\n/*=============================================================================*/\n// Support code unrelated to answer\nfunction log(textContent) {\n info.appendChild(Object.assign(document.createElement(\"div\"),{textContent}));\n} \nfunction logTree(parent, indent = \"\", end) {\n const tail = parent.children.length > 0 ? \"┬\" : \"─\";\n if(end){\n log(indent + \"└──┬─\" + \"►parent: \" + parent.parent);\n log(indent + \" └\" + tail + \"►name..: \" + parent.name);\n indent +=\" \";\n } else {\n log(indent + \"├──┬─\" + \"►parent: \" + parent.parent);\n log(indent + \"│ └\" + tail + \"►name..: \" + parent.name);\n indent +=\"│ \";\n }\n var idx = 0;\n for (const child of parent.children) {\n logTree(child, indent, (idx++ === parent.children.length -1));\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {background:black}\n#info {color:#CC0;font-size:smaller;white-space:pre-wrap;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"info\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:27:59.127",
"Id": "424020",
"Score": "0",
"body": "Definitely some good points here. Names of things are much simpler in Python, lists, dicts, tuples etc. everything JS is an object. I often call them associative arrays from my experience of PHP. Not sure why I went for JSON object, I thought it described the structure more clearly, perhaps not. Take your point on the underscore vs camel case, I've been writing a lot of python lately and it slipped in. Will have a read through the code properly and have another crack it thanks so much for the pointers. First up will make the switch to `for of`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:53:39.473",
"Id": "424025",
"Score": "0",
"body": "I've updated the title and description to more clearly describe what I'm doing. I see what you are doing with the functions at the top, it reads much more clearly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:51:17.927",
"Id": "424040",
"Score": "0",
"body": "Thanks so much for reviewing this, this is a really good, clean solution. There are a couple of points to improve. It should use either `topItem` or `TOP_NAME` to set the top item name, I've set it up to use the `topItem` so you have the option of changing it and removed the latter. I'm not sure of the meaning of `const addNode = (parent, child) => (parent.children.push(child), child);`. It looks like it should just push the child. I've removed `, child` after `push` and brackets. Lastly I renamed `structure` to `nested_array` to make that slightly clearer too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:59:14.740",
"Id": "424041",
"Score": "0",
"body": "Ah I see, I've had to put the `, child` part back in. I'll try to work out the meaning of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:35:01.907",
"Id": "424060",
"Score": "0",
"body": "So this is using `(parent, child) => (parent.children.push(child), child);` Comma Expression to return the child after it pushes it. Pretty cool. I've switched it out for a more verbose `(parent, child) => {parent.children.push(child); return child;};` which I find easier to understand. I can see myself coming to like Comma Expressions though, nice to know, thanks again."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:48:44.857",
"Id": "219516",
"ParentId": "219418",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T09:51:50.020",
"Id": "219418",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"array",
"tree"
],
"Title": "Convert nested array of values to a tree structure"
} | 219418 |
<p>I made a class to conviniently serialize/deserialize data. Now I'm stuck with the following question. Should I handle exceptions (use try-catch) inside <code>JsonStorage</code> or inside <code>ConfigManager</code> and other classes that might use <code>JsonStorage</code> in the future?</p>
<pre><code>public class JsonStorage : IDataStorage
{
private readonly IFileSystem fileSystem;
private readonly ILogger logger;
public JsonStorage(IFileSystem fileSystem, ILogger logger)
{
this.fileSystem = fileSystem;
this.logger = logger;
}
public T RestoreObject<T>(string path)
{
T result = default;
try
{
if (!fileSystem.Path.IsPathFullyQualified(path))
throw new ArgumentException("Invalid path.", nameof(path));
string json = fileSystem.File.ReadAllText($"{path}.json");
result = JsonConvert.DeserializeObject<T>(json);
}
catch (Exception ex)
{
logger.Log($"Object can't be restored. {ex.Message}");
}
return result;
}
public void StoreObject(object obj, string path)
{
string file = $"{path}.json";
try
{
if (!fileSystem.Path.IsPathFullyQualified(path))
throw new ArgumentException("Invalid path.", nameof(path));
fileSystem.Directory.CreateDirectory(fileSystem.Path.GetDirectoryName(file));
var json = JsonConvert.SerializeObject(obj, Formatting.Indented);
fileSystem.File.WriteAllText(file, json);
}
catch (Exception ex)
{
logger.Log($"Object can't be stored. {ex.Message}");
}
}
}
</code></pre>
<pre><code>public static class ConfigManager
{
private static readonly string configPath = @"SomePath\Config";
public static BotConfig LoadConfig()
{
return Unity.Resolve<IDataStorage>().RestoreObject<BotConfig>(configPath);
}
public static void SaveConfig(BotConfig config)
{
Unity.Resolve<IDataStorage>().StoreObject(config, configPath);
}
}
</code></pre>
<p><code>ConfigManager</code> - example class that holds a path to Config.json and loads/saves it (using <code>JsonStorage</code> internaly).</p>
<p>For now I'm catching exceptions inside <code>JsonStorage</code> and using a logger instance to print exception messages to the console.
I don't know if there's a downside to that. Should <code>JsonStorage</code> have its own logger? Should it throw an exception (just like <code>ReadAllText</code>/<code>WriteAllText</code>) when something goes wrong with path/files?
Or maybe there is a good practice and some better ways to handle exceptions (in my particular case)?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T20:34:15.890",
"Id": "423935",
"Score": "2",
"body": "[***\"Hint**: If your title contains a question, it is likely a bad title.\"*](https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions/2438#2438)"
}
] | [
{
"body": "<p>This is how I see things...</p>\n\n<ul>\n<li>Throwing <code>ArgumentException</code> insinde a <code>try/catch</code> that at the same time <em>swollows</em> it is pointless. You use <code>ArgumentException</code> to inform the user that he called your API in a wrong way. This is not something one should hangle because he won't see it until he looks at the logs. The app should crash in this case.</li>\n<li>The message of the <code>ArgumentException</code> is too generic. When it happens, the user already knows something is wrong. Tell him how to fix that by giving him a hint what the correct path should be and what path he actually used.</li>\n<li>The way you are handling exceptions that might be thrown by the json-serializer is unexpected (non-standard) because the user will wonder why he got a <code>null</code> without noticing anything. <code>public</code> library APIs should always <code>throw</code> unless they are called <code>TryDoSomething</code> and <code>return</code> a <code>bool</code>.</li>\n<li>Yet another flaw of this <em>pattern</em> is that it doesn't help anyone to find the source of the exception. You neither add the filename to it nor the object that it tried to de/serialize. This is very important piece of information and should be included. </li>\n</ul>\n\n<p>So, what you can/should do instead is to <code>throw</code> a new exception that adds more information about what happened e.g.:</p>\n\n<pre><code>public T RestoreObject<T>(string path)\n{\n if (!fileSystem.Path.IsPathFullyQualified(path))\n throw new ArgumentException($\"Invalid path: '{path}'. It must by fully qualified.\", nameof(path));\n\n try\n { \n string json = fileSystem.File.ReadAllText($\"{path}.json\");\n return JsonConvert.DeserializeObject<T>(json);\n }\n catch (Exception ex)\n {\n throw new JsonStorageException($\"Could not restore object '{typeof(T).Name}' from '{path}'.\", ex);\n }\n}\n</code></pre>\n\n<p>You'll be happy to see the type and file name when something goes wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:04:53.497",
"Id": "423898",
"Score": "0",
"body": "Thanks for good tips. But what if `ReadAllText` throws some IO exception? In your code it will be re-thrown as `JsonStorageException` and it also doesn't provide details about what went wrong there..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:05:48.130",
"Id": "423899",
"Score": "0",
"body": "@Glitch you pass the original exception as inner-exception. See the last parameter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:07:46.290",
"Id": "423900",
"Score": "0",
"body": "oh, didn't notice that. So you're also saying that I shouldn't have logger instance in my storages, and instead should handle thrown exceptions higher up the stack call?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:09:49.180",
"Id": "423902",
"Score": "0",
"body": "@Glitch exactly, otherwise you have to check the result against `null` and break the execution there by doing something else. It's easier to use an exception for this especially that you already have one and it doesn't cost anything."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:21:17.217",
"Id": "219438",
"ParentId": "219425",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "219438",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:08:12.793",
"Id": "219425",
"Score": "4",
"Tags": [
"c#",
"json",
"error-handling"
],
"Title": "Should my Json storage handle exceptions?"
} | 219425 |
<p>I made this in order to teach myself pygame.
This displays an images loop at the same speed on any computer (It will lag on a slow computer).</p>
<p>Is my time management good or do my datetime call could be optimized to loose less time while doing computation?</p>
<p>Any other remarks are welcolmed.</p>
<pre><code>#!/usr/bin/env python
#-*- coding: utf-8 -*-
import datetime
import os
import pygame
from os import listdir
from os.path import isfile, join
from pygame.locals import *
class ImageSequenceDisplayer():
"""
Display an image sequence independantly of the processing speed running this program
"""
def __init__(self, directory, time_between_frame_ms):
self.directory = directory
self.time_between_frame_ms = time_between_frame_ms
self._surfaces_to_display = self._load_images_as_surfaces(directory)
self._current_index = 0
self._last_time_a_surface_was_displayed = None
def _load_images_as_surfaces(self, directory):
print "ImageSequenceDisplayer : Loading images from : '{}'".format(directory)
surfaces_to_display = load_all_images_from(directory)
if len(surfaces_to_display) == 0:
raise Exception("No images found in '{}'".format(directory))
print "ImageSequenceDisplayer : Loading completed, {} images loaded".format(len(surfaces_to_display))
return surfaces_to_display
def _compute_ms_since_last_display(self, current_date):
timedelta_since_last_display = current_date - self._last_time_a_surface_was_displayed
# .microseconds does not contain the seconds, so we have to add them
return timedelta_since_last_display.seconds * 1000 + (timedelta_since_last_display.microseconds / 1000)
def display_next_image(self, surface_to_display_to, pos_to_display_to):
"""
Measure how much time has passed since the last image display and will choose the next image to display (for
example if we set the displayer to 50ms and 172ms have passed then we will skip 2 frames.
:param surface_to_display_to: the surface we want to display the image
:param pos_to_display_to: the position in "surface_to_display_to" where the image will be blitted
"""
if self._last_time_a_surface_was_displayed is None:
self._last_time_a_surface_was_displayed = datetime.datetime.now()
self._current_index = 0
else:
current_date = datetime.datetime.now()
ms_since_last_display = self._compute_ms_since_last_display(current_date)
if ms_since_last_display > self.time_between_frame_ms:
n_frame_to_advance = self.time_between_frame_ms/ms_since_last_display + 1
new_index = self._current_index + n_frame_to_advance
if new_index >= len(self._surfaces_to_display):
# int division, yes I want to discard the decimal part
n_to_remove = new_index/len(self._surfaces_to_display)
new_index = new_index - (n_to_remove * len(self._surfaces_to_display))
self._last_time_a_surface_was_displayed = current_date
else:
#not enought time has passed, we display the same old frame, without updating self._last_time_a_surface_was_displayed
new_index = self._current_index
self._current_index = new_index
surface_to_display = self._surfaces_to_display[self._current_index]
surface_to_display_to.blit(surface_to_display, pos_to_display_to)
def get_all_files_from(my_path):
file_list_without_path = [ f for f in listdir(my_path) if isfile(join(my_path,f)) and 'desktop.ini' not in f ]
return file_list_without_path
def load_all_images_from(my_path, resize_hw=None):
res = []
for im_name in get_all_files_from(my_path):
im_surface = pygame.image.load(os.path.abspath(join(my_path, im_name)))
if resize_hw is not None:
im_surface = pygame.transform.scale(im_surface, resize_hw)
res.append(im_surface)
return res
ball_position = 200, 200
main_window_size = 900, 750
background_color = (50 , 50, 50)
origin_position = (0, 0)
pygame.init()
window = pygame.display.set_mode(main_window_size)
background_surface = pygame.Surface(main_window_size)
background_surface.fill(background_color)
window.blit(background_surface, origin_position)
time_between_frames_ms = 40
directory_of_images_loop = "ball"
ball_displayer = ImageSequenceDisplayer(directory_of_images_loop, time_between_frames_ms)
doIt = True
while doIt:
for event in pygame.event.get():
if event.type == QUIT:
print "doIt is false"
doIt = False
ball_displayer.display_next_image(window, ball_position)
pygame.display.flip()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T12:18:38.433",
"Id": "219427",
"Score": "3",
"Tags": [
"python",
"python-2.x",
"image",
"animation",
"pygame"
],
"Title": "Pygame : processing speed independant image loop displayer"
} | 219427 |
<p>I am almost completing my BlackJack game in Javascript. But I realize that there must be a way to improve the performance for these two methods. Any pointers?</p>
<pre><code>const hasAceInHand = (cardsOnHand) => {
for (let key in cardsOnHand) {
let arr = cardsOnHand[key];
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
for (let prop in obj) {
if (prop === "face") {
if (obj[prop] === "A") {
return true;
}
}
}
}
}
return false;
}
const countHandValue = (cardsOnHand) => {
//console.log(hasAceInHand(cardsOnHand));
let sum = 0;
for (let key in cardsOnHand) {
let arr = cardsOnHand[key];
for (let i = 0; i < arr.length; i++) {
let obj = arr[i];
for (let prop in obj) {
if (prop === "faceValue") {
//console.log(prop + " = " + obj[prop]);
sum = sum + obj[prop];
debugger;
if (sum > 21 && hasAceInHand(cardsOnHand)) {
// Transfer Ace's face value from 11 to 1
sum = sum - 11;
sum = sum + 1;
}
}
}
}
}
return sum;
}
</code></pre>
<p>This <code>countHandValue</code> method is called at below:</p>
<pre><code>const cardSuit = ["hearts", "diams", "clubs", "spades"];
const cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];
// In JavaScript, functions are objects.
// You can work with functions as if they were objects.
function card(suit, face) {
this.suit = suit;
this.face = face;
switch (face) {
case "A":
this.faceValue = 11;
break;
case "J":
case "Q":
case "K":
this.faceValue = 10;
break;
default:
this.faceValue = parseInt(face);
break;
}
};
const deck = {
cards: []
}
var tempCard;
const player = {
cards: [],
handValue: 0
}
const dealer = {
cards: [],
handValue: 0
}
const dealOneCardToPlayer = () => {
// Take a card from the top deck to be assigned to tempcard.
tempCard = deck.cards.splice(0, 1);
player.cards.push(tempCard);
player.handValue = countHandValue(player.cards);
document.getElementById("handValuePlayer").innerHTML = player.handValue;
makeCardPlayer(tempCard[0]);
}
</code></pre>
<p>I have <a href="http://js.findingsteve.net/bj" rel="nofollow noreferrer">uploaded the whole program</a>.</p>
| [] | [
{
"body": "<p>I'd suggest using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loops to iterate over the cards, but before we can do that, there is an important point with the <code>dealOneCardToPlayer()</code> function:</p>\n\n<blockquote>\n<pre><code>tempCard = deck.cards.splice(0, 1);\n</code></pre>\n</blockquote>\n\n<p>Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\" rel=\"nofollow noreferrer\"><code>Array.splice()</code></a> returns \"<em>An array containing the deleted elements.</em>\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Return_value\" rel=\"nofollow noreferrer\">1</a></sup> and thus the name <code>tempCard</code> is misleading - perhaps a more appropriate name would be <code>tempCards</code>. </p>\n\n<p>This means that the next line:</p>\n\n<blockquote>\n<pre><code>player.cards.push(tempCard); \n</code></pre>\n</blockquote>\n\n<p>leads to <code>player.cards</code> having a nested array with that card. If instead the first element of that array returned from the call to <code>.splice()</code> was pushed into the players <code>cards</code> array, it would make those functions easier to work with, along with <code>for...of</code> loops. That way there is no need to create a counter variable, increment it after each iteration, and use it just to get the next element from the array. </p>\n\n<p>Also, shorthand assignment operations like <code>+=</code> and <code>-=</code> can be used instead of <code>sum = sum - 11</code> and <code>sum = sum + 1</code>.</p>\n\n<p>Also there is little need to loop through the properties:</p>\n\n<blockquote>\n<pre><code>for (let prop in obj) {\n if (prop === \"face\") {\n if (obj[prop] === \"A\") {\n</code></pre>\n</blockquote>\n\n<p>Just check the property directly:</p>\n\n<pre><code>if (obj.face === \"A\") {\n</code></pre>\n\n<p>If you want to ensure the property exists, use the <code>in</code> operator:</p>\n\n<pre><code>if ('face' in obj && obj.face === \"A\") {\n</code></pre>\n\n<p>Putting it all together:</p>\n\n<pre><code>const hasAceInHand = (cardsOnHand) => {\n for (const card of cardsOnHand) {\n if (card.face === \"A\") {\n return true;\n }\n }\n return false;\n}\n\nconst countHandValue = (cardsOnHand) => {\n let sum = 0;\n for (const card of cardsOnHand) {\n sum = sum + card.faceValue;\n if (sum > 21 && hasAceInHand(cardsOnHand)) {\n // Transfer Ace's face value from 11 to 1\n sum -= 10; // - 11 + 1\n }\n }\n return sum;\n}\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Return_value\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Return_value</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T07:24:01.573",
"Id": "445124",
"Score": "0",
"body": "Thanks a lot for the code review. After some thoughts, I think it is more efficient algorithm to transform Ace value during drawOneCard method. If total hand value plus current card draw card value is more than 21 and current draw card face is Ace, then transform current card value to 1. This applies to even the first two dealt cards because the first two cards could be Ace and Ace (double Aces)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-13T21:14:00.733",
"Id": "228993",
"ParentId": "219433",
"Score": "3"
}
},
{
"body": "<h3>Review</h3>\n\n<p>Function <code>hasAceInHand</code> could be boiled down to a one-liner using <code>array.find</code>. It returns the first element of the array that passes the condition <code>x => x.face === \"A\"</code> provided.</p>\n\n<pre><code>const hasAceInHand = (cardsOnHand) => {\n return cardsOnHand.find(x => x.face === \"A\") != null;\n}\n</code></pre>\n\n<p>Function <code>countHandValue</code> iterates the items, and calls the other function which iterates the items nested in the outer iteration <code>if (sum > 21 && hasAceInHand(cardsOnHand)) { ..</code>. You could just keep track of aces to avoid iterating the items more than once.</p>\n\n<h3>Alternative for <code>countHandValue</code></h3>\n\n<p>In black-jack, at most 1 ace could have value 11, all other aces in the hand must have value 1, else 21 would get exceeded (<code>11 + 11 > 21</code>). I would change the default value of an ace to 1.</p>\n\n<pre><code>switch (face) {\n case \"A\":\n this.faceValue = 1;\n break;\n</code></pre>\n\n<p>As a first step, <code>Array.reduce</code> could be used to calculate the sum of card values.</p>\n\n<pre><code>const countHandValue = (cardsOnHand) => {\n return cardsOnHand.reduce((sum, current) => {\n sum += current.faceValue;\n return sum;\n }, 0);\n}\n</code></pre>\n\n<p>Then we can implement a relaxation allowing at most 1 ace to get value 11.</p>\n\n<pre><code>const countHandValue = (cardsOnHand) => {\n let ace;\n let value = cardsOnHand.reduce((sum, current) => {\n ace |= current.faceValue === 1;\n sum += current.faceValue;\n return sum;\n }, 0);\n if (ace && value + 10 <= 21) {\n value += 10;\n }\n return value;\n}\n</code></pre>\n\n<p>And we also no longer need to call <code>hasAceInHand</code> as we're tracking the ace inline. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-14T07:20:19.023",
"Id": "229013",
"ParentId": "219433",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "229013",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T13:39:51.720",
"Id": "219433",
"Score": "5",
"Tags": [
"javascript",
"ecmascript-6",
"playing-cards",
"iteration"
],
"Title": "Blackjack game: Count Hand Value method"
} | 219433 |
<p>As you probably already know, the Unix I/O primitive <code>write</code> is not guaranteed to write out all of the data in the buffer you give it; you may be obliged to loop calling it on successive suffixes of the buffer until it's all gone. I'm trying to work out the cleanest way to write that loop in Rust. This is what I have:</p>
<pre><code>use ::nix;
use ::std::os::unix::io::RawFd;
pub fn write_all (fd: RawFd, s: &[u8]) -> nix::Result<()>
{
use ::libc::{write, c_void};
let mut p = s;
while p.len() > 0 {
let consumed = unsafe {
write(fd, p.as_ptr() as *const c_void, p.len())
};
if consumed < 0 {
return Err(nix::Error::last());
}
if (consumed as usize) >= p.len() { break }
let (_, x) = p.split_at(consumed as usize);
p = x;
}
Ok(())
}
</code></pre>
<p>This does the job, but this piece seems inelegant and I can't figure out a better way to write it:</p>
<pre><code> if (consumed as usize) >= p.len() { break }
let (_, x) = p.split_at(consumed as usize);
p = x;
</code></pre>
<p>The <code>if</code> eliminates a panic case that should be impossible (because <code>write</code> will never return a value greater than <code>p.len()</code>); I could live without it, but what I <em>want</em> here is for <code>split_at</code> to give me an empty trailing slice if the split point is at <em>or beyond</em> the end of the input.</p>
<p>The intermediate variable <code>x</code> is necessary because you can't write</p>
<pre><code> (_, p) = p.split_at(consumed as usize);
</code></pre>
<p>and I can't rebind <code>p</code> directly, because the loop control expression wouldn't see the change.</p>
<p>What suggestions do you have?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T14:54:40.787",
"Id": "423889",
"Score": "0",
"body": "Remove the if, it's useless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T14:55:05.063",
"Id": "423890",
"Score": "0",
"body": "why not use https://doc.rust-lang.org/std/io/trait.Write.html#method.write_all ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:05:46.633",
"Id": "423891",
"Score": "0",
"body": "@Stargateur Well, this is mostly a learning exercise for me, and what I want to understand is the proper way to do this sort of thing with slices; the goal of calling `write` in a loop is secondary. But also, there is no `impl Write for RawFd` in the stdlib (nor, as far as I can tell, in nix or libc) and, if someone were to add one, they would have to write this function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:16:19.933",
"Id": "423893",
"Score": "0",
"body": "just, use the correct, https://doc.rust-lang.org/std/os/unix/io/trait.FromRawFd.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:56:08.907",
"Id": "423896",
"Score": "0",
"body": "... what part of \"I want to understand the proper way to do this sort of thing with slices\" is unclear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:08:22.680",
"Id": "423901",
"Score": "0",
"body": "There is no correct way I think, here full functional, https://play.rust-lang.org/?version=stable&mode=release&edition=2018&gist=4b72015f6e03d2d22ea10dd26d052350. I like this one."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T14:46:20.030",
"Id": "219436",
"Score": "0",
"Tags": [
"rust"
],
"Title": "Idiom: replacing a slice with a suffix of that slice (write_all loop)"
} | 219436 |
<p>I finished <a href="https://docs.cs50.net/2018/fall/psets/6/bleep/bleep.html" rel="nofollow noreferrer">CS50's bleep.py</a> from pset6. I was hoping to get some feedback on my code (e.g., redundant code, bad practice, etc...).</p>
<p><b>Program function</b></p>
<ul>
<li>load in a dictionary of banned words </li>
<li>accept a message from the user</li>
<li><p>if words in the message appear in the banned list, censor the word with *</p>
<pre><code>from cs50 import get_string
from sys import argv, exit
def main():
# ensure correct usage
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# open dictionary of bad words
name = argv[1]
text = open(name, "r", encoding="latin_1")
if not text:
print("Could not open {}.".format(name))
exit(1)
# store banned words in list
bannedList = []
for ban in text:
ban = ban.replace('\n', '')
bannedList.append(ban)
# get user input to censor and split into words
toCensor = input("What message would you like to censor? ")
toCensor = toCensor.split()
# for censored phrase
final = []
# check if word needs to be censored
for word in toCensor:
if word.lower() in bannedList:
censored = word.replace(word, "*"*len(word))
final.append(censored)
else:
final.append(word)
print(' '.join(final))
if __name__ == "__main__":
main()
</code></pre></li>
</ul>
<p><b>EDIT</B></p>
<p>I implemented the suggestions, and I like it a lot better now. It even handles commas, periods, and other punctuation now. Thanks again!</p>
<pre><code>from cs50 import get_string
from sys import argv, exit
import re
def censor(text, banned_words):
# for censored phrase
final = []
# check if word needs to be censored
for word in text:
if (word.lower()).strip(",.!?") in banned_words:
censored = re.sub('[a-zA-Z]', '*', word)
final.append(censored)
else:
final.append(word)
#return censored phrase
return ' '.join(final)
def main():
# ensure correct usage
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
# open dictionary of bad words
name = argv[1]
with open(name, 'r', encoding="UTF-8") as f:
lines = [line.rstrip() for line in f]
# get user input to censor and split into words
to_censor = input("What message would you like to censor? ")
to_censor = to_censor.split()
#censor and obtain new phrase
censored = censor(to_censor, lines)
print(censored)
if __name__ == "__main__":
main()
</code></pre>
| [] | [
{
"body": "<p>Having a single <code>main</code> function that reads from <code>os.stdin</code> and writes the unrelated prompt to <code>os.stdout</code> is a bad architecture. In Python it is easy to create reusable modules, by using the following structure:</p>\n\n<pre><code>def censor(text, banned_words):\n \"\"\"\n Returns a copy of the given text in which all words from\n banned_words are replaced with asterisks of the same length.\n \"\"\"\n\n # TODO: insert some code here.\n\n\ndef main():\n # contains all the input/output stuff\n # TODO: insert some code here.\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Programmed this way, other Python code can just <code>import censor</code> and then use the censoring code, no matter where the set of banned words comes from.</p>\n\n<p>Having the code split into two separate functions also makes sense for understanding what the code does. If you're interested in how censoring works, look at the <code>censor</code> function. If you are interested in reading and writing to files, look in <code>main</code>.</p>\n\n<p>Some other random remarks:</p>\n\n<pre><code>text = open(name, \"r\", encoding=\"latin_1\")\n</code></pre>\n\n<p>Please don't use the latin_1 encoding if possible. It's been en vogue in the 1990, nowadays we prefer to use the full Unicode character set (including Arabic, Bengali, Chinese, Devanagari, Emoji, and many more) and UTF-8 to save Unicode text into byte-oriented files.</p>\n\n<p>Most probably that file contains only ASCII characters anyway since CS50 takes place in the USA, where foreign languages and writing systems are often ignored.</p>\n\n<pre><code>text = open(name, \"r\", encoding=\"latin_1\")\nif not text:\n ...\n</code></pre>\n\n<p>This will not work since the <code>open</code> function either succeeds by returning a file object, or it fails and throws an exception. It never returns <code>None</code>. That's probably a leftover from your last exercise in the C programming language. But Python is very different from C.</p>\n\n<p>Whenever you open a file, you must also close it when you're done with it. The simplest way is:</p>\n\n<pre><code>with open(name, 'r', encoding='UTF-8') as f:\n lines = f.readlines()\n</code></pre>\n\n<p>The <code>with</code> statement will automatically close the file at the end. It's not visible in the source code, you have to just know this.</p>\n\n<pre><code>toCensor = input(\"What message would you like to censor? \")\n</code></pre>\n\n<p>Be sure to only ever run this program in Python 3, since in Python 2 the <code>input</code> function behaves differently.</p>\n\n<p>The name <code>toCensor</code> should rather be <code>to_censor</code> since in Python variable names and function names are written in <code>snake_case</code> instead of <code>camelCase</code>.</p>\n\n<p>In the sentence <code>This is BAD, BAD, BAD.</code>, assuming that <code>BAD</code> is a bad word, what would the expected output be? How can you change your program to do the expected thing? What should it do about <code>BADABOOM</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:51:47.200",
"Id": "424004",
"Score": "0",
"body": "That was incredibly helpful, and I really appreciate you taking the time to write this! Do you know of any Python books that you would highly recommend?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T07:17:51.830",
"Id": "219481",
"ParentId": "219437",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:11:16.280",
"Id": "219437",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"homework"
],
"Title": "CS50 - Bleep suggestions"
} | 219437 |
<p>I've creating a working subscription workflow for my webpage, which heavily utilizes a set of functions I've created for this purpose.</p>
<p>However, after doing some testing (functionality works fine), I've discovered the way I've designed my system is taking a heavy toll on the web-page load speed. My current suspicions are aimed towards that the heavy amount of Stripe API calls are causing a lot of the problems. </p>
<p>I tried changing up the way I call variables, both as the code you see here, and where I utilize paramters instead; same result. </p>
<p>Any PHP gurus who can give me some pointers in how to optimize the load times of these scripts?</p>
<pre><code><?php
use \Stripe\Stripe;
\Stripe\Stripe::setApiKey("api_key");
function get_stripe_sub_id() {
global $current_user;
$userid = $current_user->ID;
$stripe_id = get_user_meta($userid, 'stripe_id');
$refer_user_obj = \Stripe\Customer::retrieve($stripe_id[0]);
if(isset($refer_user_obj->subscriptions->data[0]->id)) {
$sub_id = $refer_user_obj->subscriptions->data[0]->id;
return $sub_id;
} else {
return 'non_sub';
}
}
function get_sub_status() {
if(get_stripe_sub_id() == 'non_sub') {
return 'deactive';
} else {
$sub_obj = \Stripe\Subscription::retrieve(get_stripe_sub_id());
$sub_status = $sub_obj->status;
if($sub_status == 'trialing' || $sub_status == 'active') {
return 'active';
} else {
return 'deactive';
}
}
}
function is_customer() {
global $current_user;
$userid = $current_user->ID;
$is_customer = get_user_meta($userid, 'is_customer');
if(isset($is_customer[0])) {
if($is_customer[0] == '1') {
return true;
} else {
return false;
}
}
}
function redirect_if_non_sub() {
global $current_user;
$userid = $current_user->ID;
if(is_customer($userid) == true) {
if(get_sub_status() == 'deactive') {
$uri = $_SERVER['REQUEST_URI'];
if ($uri != '/cvhelpr/ingen-abonnement/') {
write_log('redirect me');
header('Location: /cvhelpr/ingen-abonnement');
exit;
}
}
}
}
function get_next_sub_invoice() {
if(get_stripe_sub_id() != 'non_sub') {
$sub_obj = \Stripe\Subscription::retrieve(get_stripe_sub_id());
$next_inv = $sub_obj->current_period_end;
$formatted_inv = gmdate("Y-m-d", $next_inv);
if(is_canceled() == true) {
return 'Dit abonnement udløber ' . (string)$formatted_inv;
} else {
return $formatted_inv;
}
} else {
return 'Denne bruger har intet abonnement.';
}
}
function is_canceled() {
$sub_obj = \Stripe\Subscription::retrieve(get_stripe_sub_id());
$is_canceled = $sub_obj->cancel_at_period_end;
if($is_canceled == 1) {
return true;
} else {
return false;
}
}
function reactivate_sub() {
$stripe_id = get_user_meta(get_current_user_id(), 'stripe_id');
write_log($stripe_id[0]);
$subscription = \Stripe\Subscription::create([
'customer' => $stripe_id[0],
'items' => [['plan' => 'cv_195']],
'trial_period_days' => 7
]);
header("Location: /my-account");
die();
}
add_action('wp_ajax_reactivate_sub', 'reactivate_sub');
add_action('wp_ajax_nopriv_reactivate_sub', 'reactivate_sub');
function cancel_sub() {
if(get_stripe_sub_id() != 'non_sub') {
$sub = \Stripe\Subscription::retrieve(get_stripe_sub_id());
\Stripe\Subscription::update(
get_stripe_sub_id(),
[
'cancel_at_period_end' => true
]
);
}
}
add_action('wp_ajax_cancel_sub', 'cancel_sub');
add_action('wp_ajax_nopriv_cancel_sub', 'cancel_sub');
function uncancel_sub() {
if(get_stripe_sub_id() != 'non_sub') {
$sub = \Stripe\Subscription::retrieve(get_stripe_sub_id());
\Stripe\Subscription::update(
get_stripe_sub_id(),
[
'cancel_at_period_end' => false
]
);
}
}
add_action('wp_ajax_uncancel_sub', 'uncancel_sub');
add_action('wp_ajax_nopriv_uncancel_sub', 'uncancel_sub');
?>
</code></pre>
<p>Edit: After doing some further research, it seem more and more what is really causing the slow load times is the Stripe API calls. Several other Stripe users have mentioned 3-10s load times when doing API calls.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T02:32:06.307",
"Id": "423948",
"Score": "0",
"body": "Is there a reason that you aren't calling `get_stripe_sub_id()` just one time and caching it for future script usage? What php version are you rockin'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-03T02:19:22.950",
"Id": "534604",
"Score": "0",
"body": "Sounds like you need something like Laravel Queue Jobs. Takes the burden off front end, and allows it to perform behind the scene to allow the user to as such."
}
] | [
{
"body": "<p>Disclaimer, I'm not a PHP guru. Just looked at your code and did a bit of optimization; I feel it needs more. By the way, you're right. The problem is in the function calls. </p>\n\n<pre><code><?php\n\nuse Stripe\\Stripe;\nuse Stripe\\Customer;\nuse Stripe\\Subscription;\n\nStripe::setApiKey(\"api_key\");\n\n/**\n * You could declare this at the top of the file\n * $stripeSubId = get_stripe_sub_id();\n * and then simply pass it as an argument to any function that requires it\n * e.g.,\n * function get_next_sub_invoice($stripeSubId) {\n * // rest of code directly uses $stripeSubId\n * }\n */\n\nfunction getUserId() {\n global $current_user;\n return $current_user->ID;\n}\n\nfunction get_stripe_sub_id() {\n $userid = getUserId();\n\n $stripe_id = get_user_meta($userid, 'stripe_id'); // get_user_meta() is unfortunately not in this file\n $refer_user_obj = Customer::retrieve($stripe_id[0]);\n\n if(isset($refer_user_obj->subscriptions->data[0]->id)) {\n\n return $refer_user_obj->subscriptions->data[0]->id;\n }\n return 'non_sub';\n\n}\n\nfunction get_sub_status() {\n $stripeSubId = get_stripe_sub_id(); // 1 function call is better than 3\n if($stripeSubId === 'non_sub') {\n return 'deactive';\n }\n\n $sub_obj = Subscription::retrieve($stripeSubId);\n $sub_status = $sub_obj->status;\n\n if($sub_status === 'trialing' || $sub_status === 'active') {\n return 'active';\n }\n return 'deactive';\n\n}\n\nfunction is_customer() {\n $userid = getUserId();\n\n $is_customer = get_user_meta($userid, 'is_customer');\n\n if(isset($is_customer[0])) {\n return ($is_customer[0] === '1');\n }\n return false;\n}\n\nfunction redirect_if_non_sub() {\n\n if(is_customer() && get_sub_status() === 'deactive') {\n $uri = $_SERVER['REQUEST_URI'];\n\n if ($uri !== '/cvhelpr/ingen-abonnement/') {\n write_log('redirect me'); // not in the file too\n header('Location: /cvhelpr/ingen-abonnement');\n exit;\n }\n }\n}\n\nfunction get_next_sub_invoice() {\n $stripeSubId = get_stripe_sub_id();\n\n if($stripeSubId !== 'non_sub') {\n $sub_obj = Subscription::retrieve($stripeSubId);\n $next_inv = $sub_obj->current_period_end;\n $formatted_inv = gmdate('Y-m-d', $next_inv);\n\n if(is_canceled() === true) {\n return 'Dit abonnement udløber ' . $formatted_inv;\n }\n return $formatted_inv;\n }\n\n return 'Denne bruger har intet abonnement.';\n}\n\nfunction is_canceled() {\n $sub_obj = Subscription::retrieve(get_stripe_sub_id());\n $is_canceled = $sub_obj->cancel_at_period_end;\n\n return $is_canceled === 1; // will return true if the expression matches, false otherwise\n}\n\nfunction reactivate_sub() {\n // get_current_user_id() is probably the same thing as getUserId() - see top of file\n $stripe_id = get_user_meta(get_current_user_id(), 'stripe_id');\n write_log($stripe_id[0]);\n\n $subscription = Subscription::create([\n 'customer' => $stripe_id[0],\n 'items' => [['plan' => 'cv_195']],\n 'trial_period_days' => 7\n ]);\n\n header(\"Location: /my-account\");\n die();\n}\nadd_action('wp_ajax_reactivate_sub', 'reactivate_sub');\nadd_action('wp_ajax_nopriv_reactivate_sub', 'reactivate_sub');\n\nfunction cancel_sub() {\n $stripeSubId = get_stripe_sub_id();\n if($stripeSubId !== 'non_sub') {\n $sub = Subscription::retrieve($stripeSubId); // var $sub is not used anywhere\n // you're getting an instance from the retrieve function, but not using it - why?\n // is it even necessary? The leaner your code, the better\n Subscription::update($stripeSubId,\n [\n 'cancel_at_period_end' => true\n ]\n );\n }\n}\nadd_action('wp_ajax_cancel_sub', 'cancel_sub');\nadd_action('wp_ajax_nopriv_cancel_sub', 'cancel_sub');\n\nfunction uncancel_sub() {\n $stripeSubId = get_stripe_sub_id();\n if($stripeSubId !== 'non_sub') {\n $sub = Subscription::retrieve($stripeSubId); // same thing here - try to comment it and see what happens\n Subscription::update($stripeSubId,\n [\n 'cancel_at_period_end' => false\n ]\n );\n }\n}\nadd_action('wp_ajax_uncancel_sub', 'uncancel_sub');\nadd_action('wp_ajax_nopriv_uncancel_sub', 'uncancel_sub');\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:09:49.783",
"Id": "423971",
"Score": "0",
"body": "Fair answer, it could be improved by more observations about the posters code rather than re-writing the code. You might want to check out this guide https://codereview.stackexchange.com/help/how-to-answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:32:46.470",
"Id": "423972",
"Score": "0",
"body": "Question definitely helped me clean up the code - but had very little to no impact on the pages load time. Thanks for the effort though!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T04:45:39.357",
"Id": "219475",
"ParentId": "219442",
"Score": "0"
}
},
{
"body": "<p>So the high delay was a result of the Stripe API calls, as it appears they have a limit of you pulling data.</p>\n\n<p>To improve this, I changed it so I pull all the data I need from the API into my database when specific actions are performed, then call the data I need from my own database instead of constantly bothering the API:</p>\n\n<pre><code>function update_stripe_meta() {\n $userid = getUserId();\n $stripe_id = get_user_meta($userid, 'stripe_id');\n update_user_meta($userid, 'customer_object', Customer::retrieve($stripe_id[0]));\n update_user_meta($userid, 'sub_object', Subscription::retrieve(get_stripe_sub_id()));\n}\n</code></pre>\n\n<p>Result is load times went from 10-12s to 3-4s when performing actions, and less than 1s when just surfing the webpage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T12:30:48.403",
"Id": "219491",
"ParentId": "219442",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219491",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:15:12.143",
"Id": "219442",
"Score": "1",
"Tags": [
"performance",
"php",
"wordpress",
"e-commerce"
],
"Title": "PHP subscription workflow"
} | 219442 |
<p>I am using the below code in Python to input a N*N matrix in its original form:</p>
<pre><code>n = int(input())
l=[]
for i in range(n):
x=input().split()
c=[]
for j in range(n):
c.append(int(x[j]))
l.append(c)
print(l)
</code></pre>
<p>Here's the output:</p>
<pre><code>2 #input n
1 3 #input row
1 5. # input another row
[[1, 3], [1, 5]] # final matrix
</code></pre>
<p>How can this code be improved? Is there a better way to take a matrix as input?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:46:35.680",
"Id": "423903",
"Score": "0",
"body": "The for loop can be a single line: `l.append([int(x) for x in input().split()])`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:48:45.203",
"Id": "423904",
"Score": "0",
"body": "Have a look at this question for some ideas: https://stackoverflow.com/questions/32466311/taking-nn-matrix-input-by-user-in-python"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:59:33.997",
"Id": "423905",
"Score": "0",
"body": "@JohnGordon than how can I incorporate the below for loop"
}
] | [
{
"body": "<p>The two main datatypes for storing matrices in Python (other that the nested list that you use here) are Numpy arrays and Pandas dataframes. Both Numpy and Pandas support reading files, for instance see these links for <a href=\"https://stackoverflow.com/questions/3518778/how-do-i-read-csv-data-into-a-record-array-in-numpy\">Numpy</a> and <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\" rel=\"nofollow noreferrer\">Pandas</a>. You can open a spreadsheet program such as Excel, write the values there, save it as a CSV, then read the CSV into Python.</p>\n\n<p>If you want to input from the console, you should give some output to let the user what you're expecting them to do. As it stands, running your program results in the program just sitting there with no indication what it's waiting for. If you know what format the user will be using, you can simplify the reading quite a bit. If the user simply enters the nested list (in this case <code>[[1,3],[1,5]]</code>), then doing <code>eval</code> on it will turn it from a string to a nested list. However, doing <code>eval</code> on arbitrary input from the user is dangerous. A safer alternative is given <a href=\"https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:00:43.553",
"Id": "219444",
"ParentId": "219443",
"Score": "1"
}
},
{
"body": "<p>Since the number of rows is to be equal to the number of columns, you can simply get the number of columns from the first input and stop taking input when the user enters the same number of rows:</p>\n\n<pre><code>l = []\nwhile not l or len(l) < len(l[0]):\n l.append(list(map(int, input().split())))\n</code></pre>\n\n<p>so that given an input of:</p>\n\n<pre><code>2 3 4\n1 2 3\n5 6 7\n</code></pre>\n\n<p><code>l</code> would become:</p>\n\n<pre><code>[[2, 3, 4], [1, 2, 3], [5, 6, 7]]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:04:47.117",
"Id": "219445",
"ParentId": "219443",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>Is there a better way to take a matrix as input?</p>\n</blockquote>\n\n<p>Well, if by \"better\" you mean fewer lines of code, then I have the solution for you!</p>\n\n<h1>The Solution</h1>\n\n<pre><code>(lambda N: [[int(x) for x in input().split()[:N]] for _ in range(N)])(int(input(\"Enter N: \")))\n</code></pre>\n\n<p>This one-liner is almost reminiscent of a Code Golf contest entry, or one of JavaScript's <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">immediately invoked function expressions</a>.</p>\n\n<h1>The Explanation</h1>\n\n<p>It's pretty hard to understand what all is going on in that one line, so let's dissect it piece-by-piece.</p>\n\n<p>First, we'll note the general structure is <code>(lambda expression)(argument)</code>, so that means we are defining an anonymous function and immediately calling it. The argument is the easier part, so let's start there.</p>\n\n<h2>What is the argument?</h2>\n\n<p>The argument is simply the size <em>N</em> of the matrix, where we convert the user input (prompted by <code>\"Enter N: \"</code>) to an integer.</p>\n\n<h2>What is the <code>lambda</code> expression?</h2>\n\n<p>If you're not already familiar with Python's <a href=\"https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions\" rel=\"nofollow noreferrer\">lambda expressions</a>, these are how you can create anonymous functions that take in certain parameters and return a value. In this case, we are taking in the parameter <code>N</code> and returning a 2D list (our matrix) formed via a \"<a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a>.\"</p>\n\n<p>If you don't know list comprehensions, what they do is construct lists of the form <code>[a for b in c]</code>. That is equivalent to the following:</p>\n\n<pre><code>L = []\nfor b in c:\n L.append(a)\nreturn L\n</code></pre>\n\n<p>Another note to make is that when <code>_</code> is used as the loop variable, that just means we don't intend to use it later on. In this case, the row number is unimportant.</p>\n\n<p>Finally, when we say <code>[int(x) for x in input().split()[:N]]</code>, this means we split the input row into integers and take only the first <em>N</em> elements, which (for better or worse) means that we can ignore any extra input on each line beyond the <em>N</em> integers we seek.</p>\n\n<h1>Conclusion</h1>\n\n<p>All things considered, this is probably not the way to do things. For evidence, consult <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">The Zen of Python</a>. This particular code is fairly ugly, complicated, nested, dense, and unreadable, even though it is short. However, I thought it was worth mentioning because it is a good demonstration of how short a useful Python script can be (and of lambda expressions and list comprehensions, for those who have not yet been introduced).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-31T06:40:58.503",
"Id": "221388",
"ParentId": "219443",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T15:41:44.613",
"Id": "219443",
"Score": "4",
"Tags": [
"python",
"matrix"
],
"Title": "Matrix input in N*N form in Python"
} | 219443 |
<p>This is a program written in Sinclair BASIC (48 BASIC) for the Sinclair ZX Spectrum. It uses a hardcoded key (null right now) as seen in the bottom and outputs a stream of integers generated with RC4. Is there any way I can improve this particularly to get around 48 BASIC using one-indexed arrays (which makes RC4 hard to do without a lot of integer additions)?</p>
<pre><code> 10 READ L
20 DIM K(L)
30 FOR I=1 TO L
40 READ K(I)
50 NEXT I
60 DEF FN M(A,B)=A-INT (A/B)*B
65 REM KSA
70 DIM S(256)
80 FOR I=0 TO 255
90 LET S(I+1)=I
100 NEXT I
110 LET J=0
120 FOR I=0 TO 255
130 LET T=S(I+1)+K(FN M(I,L)+1)
140 LET J=FN M(J+T,256)
150 GO SUB 250
160 NEXT I
165 REM PRGA
170 LET I=0
180 LET J=0
190 LET I=FN M(I+1, 256)
200 LET J=FN M(J+S(I+1),256)
210 GO SUB 250
220 LET T=S(I+1)+S(J+1)
230 PRINT S(FN M(T,256)+1)
240 GO TO 190
245 REM SWAP
250 LET T=S(I+1)
260 LET S(I+1)=S(J+1)
270 LET S(J+1)=T
280 RETURN
285 REM KEY
290 DATA 5
300 DATA 0,0,0,0,0
</code></pre>
<p>KSA is the Key Scheduling Algorithm which initializes a 256-element array <code>S</code> with a permutation based on the key <code>K</code> (an array of size <code>L</code>). PRGA is the Pseudo-Random Generator Algorithm which prints a single integer to the screen at a time based on the contents of <code>S</code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T02:15:37.820",
"Id": "467290",
"Score": "0",
"body": "Oh, this would have been so cool in the eighties! Now... *why, just why*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-03T02:20:58.200",
"Id": "467291",
"Score": "0",
"body": "Maybe try and implement it in Z80 assember? That would still be kinda cool, and it is rather easy to learn. 8 bit opcodes :)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:31:49.503",
"Id": "219447",
"Score": "2",
"Tags": [
"array",
"cryptography",
"basic-lang"
],
"Title": "RC4 in Sinclair BASIC; Working around one-indexed arrays"
} | 219447 |
<p>This is an extension of my other question <a href="https://codereview.stackexchange.com/questions/219228/combinable-filters/219234?noredirect=1#comment423497_219234">here</a>. I have applied suggestions from <code>200_success</code> in real-life problem at hand that deals with modelling extensible and combinable filter on Python Pandas dataframe structure. Is the code below reasonable and extensible, and are there areas I could improve this code on?</p>
<pre><code>import pandas as pd
# Create df
######################################################################
data = [['tom', 'M', 10, 160], ['nick', 'M', 15, 155], ['juli', 'F', 14, 123], ['tom', 'M', 13, 170],
['susan', 'F', 17, 99], ['trish', 'F', 45, 165], ['nash', 'M', 13, 213], ['nick', 'M', 15, 170],
['tom', 'M', 12, 188], ['trish', 'F', 16, 170]]
df = pd.DataFrame(data, columns=['Name', 'Sex', 'Age', 'Weight'])
''' Name Sex Age Weight
0 tom M 10 160
1 nick M 15 155
2 juli F 14 123
3 tom M 13 170
4 susan F 17 99
5 trish F 45 165
6 nash M 13 213
7 nick M 15 170
8 tom M 12 188
9 trish F 16 170'''
# Primitive filters
######################################################################
def age_at_least(var='Age', threshold=12):
def execute(df):
return df[df[var]>=threshold]
return execute
def age_at_max(var='Age', threshold=30):
def execute(df):
return df[df[var]<=threshold]
return execute
def remove_by_sex(var='Sex', threshold='M'):
def execute (df):
return df[df[var]!=threshold]
return execute
def weight_at_least(var='Weight', threshold=50):
def execute (df):
df['Weight_kg'] = df[var].apply(lb_to_kg)
return df[df['Weight_kg']>=threshold]
return execute
def lb_to_kg(lb):
return lb/2.20462
# Higher order function
######################################################################
def compose(*filters):
def composed(df):
for f in filters:
if f is not None:
df = f(df)
return df
return composed
def item_filtering(
filter_age_at_least = age_at_least(threshold=15),
filter_general = compose(age_at_max(), remove_by_sex(threshold='F')),
filter_specific = weight_at_least(),
):
return compose(filter_age_at_least, filter_general, filter_specific)
# Demonstration
######################################################################
ob = item_filtering()
print(ob(df))
# Output
''' Name Sex Age Weight Weight_kg
1 nick M 15 155 70.306901
7 nick M 15 170 77.110795
'''
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T16:48:14.793",
"Id": "219450",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"functional-programming"
],
"Title": "Combinable filters for Python Pandas dataframe structure"
} | 219450 |
<p>I want to iterate a map of map in a java 8 way and get the entry which contains 40 in the value in the inner map.</p>
<p>I have tried the following code in order to do that. But I still don't understand whether there is a better way to do this.</p>
<pre><code>import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapToMapOperation {
private Map<String, Map<String, Integer>> mapToMap = new HashMap<>();
MapToMapOperation() {
Map<String, Integer> dogMap = new HashMap<>();
dogMap.put("A", 50);
dogMap.put("B", 35);
dogMap.put("D", 40);
dogMap.put("C", 35);
mapToMap.put("dog", dogMap);
Map<String, Integer> catMap = new HashMap<>();
catMap.put("C", 35);
catMap.put("D", 40);
catMap.put("M", 40);
catMap.put("E", 70);
catMap.put("H", 35);
mapToMap.put("cat", catMap);
Map<String, Integer> donkeyMap = new HashMap<>();
donkeyMap.put("A", 52);
donkeyMap.put("E", 70);
donkeyMap.put("F", 80);
donkeyMap.put("S", 40);
donkeyMap.put("G", 90);
mapToMap.put("donkey", donkeyMap);
}
public Map<String, Integer> get(String type) {
return mapToMap.get(type);
}
public List<String> get(Map<String, Integer> map, Integer value) {
if (!map.containsValue(value)) {
return Collections.emptyList();
}
return keys(map, value).collect(Collectors.toList());
}
public Map<String, List<String>> getFullMapBasedOnValue(Integer value) {
Map<String, List<String>> resultMap = new HashMap<String, List<String>>();
java.util.Iterator<Entry<String, Map<String, Integer>>> iterator =
mapToMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Map<String, Integer>> entry = iterator.next();
Map<String, Integer> subMap = entry.getValue();
if (subMap.containsValue(value)) {
List<String> list = keys(subMap, value).collect(Collectors.toList());
resultMap.put(entry.getKey(), list);
}
}
return resultMap;
}
public <K, V> Stream<K> keys(Map<K, V> map, V value) {
return map.entrySet().stream().filter(entry -> value.equals(entry.getValue())).map(Map.Entry::getKey);
}
public static void main(String[] args) {
MapToMapOperation mapOp = new MapToMapOperation();
mapOp.get("dog").forEach((s, k) -> System.out.println(s + " " + k));
System.out.println(mapOp.get(mapOp.get("cat"), 35));
System.out.println(mapOp.getFullMapBasedOnValue(40));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:00:04.537",
"Id": "423926",
"Score": "1",
"body": "What's the background or the motivation for doing this? Maps aren't designed for reverse lookups, so there's a limit to how good this code can be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:29:03.010",
"Id": "423927",
"Score": "0",
"body": "Sorry, I dont understand you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T03:16:06.767",
"Id": "423951",
"Score": "1",
"body": "Can you add a little more explanation of what the code is supposed to do, and how it is doing it?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T17:11:51.513",
"Id": "219451",
"Score": "1",
"Tags": [
"java"
],
"Title": "Map of Map iteration in java 8"
} | 219451 |
<p>This is my code for my SqlDataAdapter which is similar to the code example given in the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldataadapter.deletecommand?view=netframework-4.8#System_Data_SqlClient_SqlDataAdapter_DeleteCommand" rel="nofollow noreferrer">docs</a>:</p>
<pre><code>public static int CommitBirdData(DataSet pDataSet)
{
int rowsAffected = 0;
using (SqlConnection conn = new SqlConnection(connString))
using (SqlDataAdapter birdDataAdapter = new SqlDataAdapter())
{
SqlCommand cmd = new SqlCommand(
"INSERT INTO [dbo].[Bird] ([BirdID], [Name], [Description]) " +
"VALUES (@BirdID, @Name, @Description)"
, conn);
cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");
birdDataAdapter.InsertCommand = cmd;
cmd = new SqlCommand(
"UPDATE [dbo].[Bird] " +
"SET [BirdID] = @BirdID, [Name] = @Name, [Description] = @Description " +
"WHERE [BirdID] = @BirdID"
, conn);
cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name");
cmd.Parameters.Add("@Description", SqlDbType.NVarChar, 200, "Description");
birdDataAdapter.UpdateCommand = cmd;
cmd = new SqlCommand(
"DELETE FROM [dbo].[BirdCount] WHERE [BirdID] = @BirdID " +
"DELETE FROM[dbo].[Bird] WHERE[BirdID] = @BirdID"
, conn);
cmd.Parameters.Add("@BirdID", SqlDbType.NVarChar, 10, "BirdID");
birdDataAdapter.DeleteCommand = cmd;
rowsAffected = birdDataAdapter.Update(pDataSet, "Bird");
return rowsAffected;
}
</code></pre>
<p>I noticed that this code is repetitive and I was just wondering whether there is a more efficient way to initialize the commands of the SqlDataAdapter with or without the using statements.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:52:17.150",
"Id": "423928",
"Score": "0",
"body": "You can always try to use Dapper or Entity Framework. Have you tried them already?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T19:06:18.883",
"Id": "423930",
"Score": "0",
"body": "I haven't worked with either of those technologies but I will check them out, thank you for listing them. Is there a way to clean this code up without the help of other technologies?"
}
] | [
{
"body": "<p>With the following, you'll only add each parameter a single time and just change the command text before assigning it to the adapter command, allowing you to reuse the existing cmd object.</p>\n\n<pre><code>using (SqlDataAdapter birdDataAdapter = new SqlDataAdapter())\n{\n SqlCommand cmd = new SqlCommand(\"DELETE FROM [dbo].[BirdCount] WHERE [BirdID] = @BirdID; DELETE FROM[dbo].[Bird] WHERE[BirdID] = @BirdID\",conn);\n cmd.Parameters.Add(\"@BirdID\", SqlDbType.NVarChar, 10, \"BirdID\");\n\n birdDataAdapter.DeleteCommand = cmd;\n\n cmd.Parameters.Add(\"@Name\", SqlDbType.NVarChar, 50, \"Name\");\n cmd.Parameters.Add(\"@Description\", SqlDbType.NVarChar, 200, \"Description\");\n\n cmd.CommandText=\"INSERT INTO [dbo].[Bird] ([BirdID], [Name], [Description]) VALUES (@BirdID, @Name, @Description)\";\n birdDataAdapter.InsertCommand = cmd;\n\n cmd.CommandText= \"UPDATE [dbo].[Bird] SET [BirdID] = @BirdID, [Name] = @Name, [Description] = @Description WHERE [BirdID] = @BirdID\"; \n birdDataAdapter.UpdateCommand = cmd;\n\n rowsAffected = birdDataAdapter.Update(pDataSet, \"Bird\");\n\n return rowsAffected;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T18:59:14.687",
"Id": "430825",
"Score": "0",
"body": "_With this approach_ - do you mean your code or OP's? I'm not sure it's a good review... could you summarize what you have improved exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T19:39:15.323",
"Id": "430833",
"Score": "1",
"body": "Edited for clarity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T11:14:38.713",
"Id": "440337",
"Score": "0",
"body": "I wound up using Entity Framework but this approach does reduce the code by a bit, thank you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-18T18:29:25.447",
"Id": "222542",
"ParentId": "219454",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222542",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:48:44.040",
"Id": "219454",
"Score": "1",
"Tags": [
"c#",
"beginner",
"t-sql",
"ado.net"
],
"Title": "Initialize various commands for the SqlDataAdapter"
} | 219454 |
<p>I was wondering how I could streamline the following code. This was the project assigned to us:</p>
<blockquote>
<p>The Canadian Forest Service wants to do a simple simulation of the growth and pruning of forests. Each forest has a name and exactly 10 trees. The trees are planted when they are 1' to 5' tall, and each tree has a individual growth rate of 50%-100% per year. For the simulation new trees are constructed randomly within these bounds. A forest is reaped (by lumberjacks) on demand - all trees above a specifed height are cut down and replaced with new trees.</p>
<p>The user interface to the simulation must allow the user to:</p>
<ul>
<li>Display the current forest (with tree heights to 2 decimal places)</li>
<li>Discard the current forest and create a new forest</li>
<li>Simulate a year's growth in the current forest</li>
<li>Reap the current forest of trees over a user specified height, replacing the reaped trees with random new trees.</li>
<li>Save the information about the current forest to file (named after the forest)</li>
<li>Discard the current forest and load the information about a forest from a file.</li>
</ul>
</blockquote>
<pre><code>import java.util.Scanner;
import java.util.*;
import java.io.*;
public class Main {
private static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
//initialize variables for Forest object, name, height and other inputs
Forest thisForest = null;
char userInput = ' ';
String forestName;
int height = 0;
String loadName = null;
while((userInput != 'x') && (userInput != 'X' )){
switch (userInput) {
//sets the first prompt
case ' ':
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
break;
//Displays the output but only if the forest exists
case 'D':
case 'd':
if(thisForest != null){
thisForest.display();
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}else{
System.out.println("No Forrest.\n");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}
break;
case 'N':
case 'n':
System.out.print("What is the name of the forest: ");
forestName = scan.next();
thisForest = new Forest(forestName);
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
break;
case 'Y':
case 'y':
//grows the equivalent of a "year".
if(thisForest != null){
thisForest.yearGrowth();
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}else{
System.out.print("No forest exists.\n");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}
break;
case 'R':
case 'r':
//reaps, but only if the forest exists. Catches possible exceptions.
if(thisForest != null){
try{
System.out.print("What height to reap at :");
height = scan.nextInt();
}catch(NumberFormatException e){
System.out.println("ERROR: Invalid height\n");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
scan.nextLine();
userInput = scan.next().charAt(0);
break;
} catch(InputMismatchException e){
System.out.println("ERROR: Invalid height\n");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
scan.nextLine();
userInput = scan.next().charAt(0);
break;
}
//end of try-catch
thisForest.reap(height);
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
scan.nextLine();
userInput = scan.next().charAt(0);
break;
//output if there is no forrest
}else{
System.out.print("There is no forest to reap.\n");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
scan.nextLine();
userInput = scan.next().charAt(0);
}
break;
case 'S':
case 's':
//saves the program
if(thisForest != null){
try{
Forest.saveForest(thisForest);
}catch(IOException e){
System.out.println("Cannot save.");
}
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}else{
System.out.println("No Forrest exists to save.");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
}
break;
case 'L':
case 'l':
// loads the program
try{
System.out.print("What is the name of the Forest: ");
loadName = scan.next();
thisForest = Forest.loadForest(loadName);
}catch(IOException e){
System.out.println("Cannot load.");
}
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
break;
default:
System.out.println("ERROR: Invalid Option.");
System.out.print("(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :");
userInput = scan.next().charAt(0);
break;
}
}
//after x is received and the while loop breaks.
System.out.println("Goodbye");
}
}
</code></pre>
<p>Second Class:</p>
<pre><code>import java.io.*;
import java.util.*;
public class Forest implements Serializable{
//creates variables and constants
private final int MAX_NUM_TREES = 10;
private String name;
private Tree[] arrayOfTrees;
int index;
public Forest(String forestName){
index = 0;
name = forestName;
arrayOfTrees = new Tree[MAX_NUM_TREES];
for(index = 0; index < arrayOfTrees.length; index++){
arrayOfTrees[index] = new Tree();
}
}
public void display(){
// displays the array of trees and the index
index = 0;
if(name != null){
System.out.println(name);
for(index = 0; index < arrayOfTrees.length; index ++){
System.out.printf("%2d : %s\n", (index + 1), arrayOfTrees[index]);
}
}else{
System.out.println("No forest.");
}
}
public void yearGrowth(){
//grows each tree in the array
index = 0;
for(index = 0; index < arrayOfTrees.length ; index ++){
arrayOfTrees[index].grow();
}
}
public void reap(int reapHeight){
//reaps the trees and prints out the old and new information
index = 0;
for(index = 0; index < arrayOfTrees.length; index++){
if(arrayOfTrees[index].getHeight() >= reapHeight){
System.out.println("Cut " + (index+1) + " : " + arrayOfTrees[index] );
arrayOfTrees[index] = new Tree();
System.out.println("New " + (index+1) + " : " + arrayOfTrees[index] );
}
}
}
public static void saveForest(Forest forest) throws IOException {
//saves the forest
String name = forest.getName();
ObjectOutputStream toStream;
toStream = new ObjectOutputStream(new FileOutputStream(name));
toStream.writeObject(forest);
toStream.close();
}
public static Forest loadForest(String fileName) throws IOException {
//loads the forest
ObjectInputStream fromStream = null;
Forest local;
fromStream = new ObjectInputStream(new FileInputStream(fileName));
try {
local = (Forest)fromStream.readObject();
}catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
return(null);
}finally{
try {
if (fromStream != null) {
fromStream.close();
}
} catch (IOException e) {
System.out.println(e.getMessage());
return(null);
}
}
return(local);
}
public String getName(){
return (name);
}
}
</code></pre>
<p>Third Class</p>
<pre><code>import java.util.Random;
import java.util.*;
import java.io.*;
public class Tree implements Serializable{
//creates the variables as the
private double height;
private double growthRate;
private static Random rand = new Random();
final double MIN_HEIGHT = 1;
final double MIN_GROWTH_RATE = 0.5;
final double MAX_HEIGHT = 5;
final double MAX_GROWTH_RATE = 1.0;
public Tree() {
//creates tree with a height and a growth rate
Random rand = new Random();
height = (MIN_HEIGHT + ((Math.random() * (MAX_HEIGHT - MIN_HEIGHT))));
growthRate = (MIN_GROWTH_RATE + (Math.random() * (MAX_GROWTH_RATE - MIN_GROWTH_RATE)));
}
public double grow(){
//tree grows and returns height
height = height * (1 + growthRate);
return height;
}
public double getHeight(){
return (height);
}
public double getGrowthRate(){
return (growthRate);
}
public String toString(){
//toString formats the output with height and growthrate
return (String.format("%7.2f (%2d%% pa)", height, ((int)(growthRate * 100))));
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<p>In your Forest class I don't like how the <code>int index;</code> variable is used. I realize that it's working for you because you always set it to 0 before looping, but local variables are that are scoped to a function is the standard way of doing it.</p>\n\n<p>This</p>\n\n<pre><code> index = 0;\n\n\n for(index = 0; index < arrayOfTrees.length; index++){\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code> for(int index = 0; index < arrayOfTrees.length; index++){\n</code></pre>\n\n<p>That will do the same thing and yet be less confusing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T01:25:38.770",
"Id": "219472",
"ParentId": "219456",
"Score": "1"
}
},
{
"body": "<p><a href=\"https://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow noreferrer\">Javadoc, Javadoc, Javadoc!</a></p>\n\n<hr>\n\n<pre><code>import java.util.*;\nimport java.io.*;\n</code></pre>\n\n<p>I'm not a fan of wildcard imports. You might actually end up with the wrong function being imported. Also any modern IDE will happily manage the imports for you.</p>\n\n<hr>\n\n<pre><code>private static Scanner scan = new Scanner(System.in);\n</code></pre>\n\n<p><code>scan</code> is an action, <code>scanner</code> would be a better name.</p>\n\n<hr>\n\n<pre><code>Forest thisForest = null;\nchar userInput = ' ';\nString forestName;\nint height = 0;\nString loadName = null;\n</code></pre>\n\n<p>Either you initialize variables with default values, or you don't, be consistent.</p>\n\n<hr>\n\n<pre><code>System.out.print(\"(D)isplay, (N)ew, (Y)ear, (R)eap, (S)ave, (L)oad, e(X)it :\");\nuserInput = scan.next().charAt(0);\n</code></pre>\n\n<p>You repeat this all over your code, find a way to do this only once (for example at the start of the <code>while</code>).</p>\n\n<hr>\n\n<pre><code>}catch(IOException e){\n System.out.println(\"Cannot save.\");\n}\n</code></pre>\n\n<p>Now that is helpful. If you do not know how to handle exceptions then do a <code>e.printStackTrace()</code> or <code>System.err.println(e.getMessage())</code>, because then the user at least has a chance to figure out <em>why</em> it did not work.</p>\n\n<p>Swallowing and silencing exceptions is only acceptable if you <em>really</em> know <em>why</em> you want this.</p>\n\n<hr>\n\n<pre><code>private final int MAX_NUM_TREES = 10;\n</code></pre>\n\n<p>I know this has been declared in the description, but a better way would be to have the <code>Forest</code> accept the number of trees and the growth rate in the constructor and have the constant in the <code>Main</code> class. That way your <code>Forest</code> class can be easier reused.</p>\n\n<hr>\n\n<pre><code>int index;\n</code></pre>\n\n<p>Nice idea to reuse the constantly used <code>int</code>. However, I hate to break it to you that is completely unnecessary, actually it is the opposite of helpful because it makes your code more error prone and a little bit harder to read. If you start reading the class you see <code>index</code> and wonder why the <code>Forest</code> requires to hold an index of itself.</p>\n\n<p>Whether or not the JVM has to allocate <em>one</em> integer doesn't matter. More so, as <code>int</code> is not an <code>Object</code>, neither does its allocation influence garbage collection in away. It is way fucking cheap to allocate an <code>int</code>, always. Well, if you have something like a million <code>int</code>s or so, we can start talking about having them cached, but not a single one.</p>\n\n<hr>\n\n<pre><code>private Tree[] arrayOfTrees;\n</code></pre>\n\n<p>Consider using a <code>List</code> instead of an array, as it has more convenience functions and is easier to handle.</p>\n\n<p>You still enforce the limit on the number of trees anyway.</p>\n\n<hr>\n\n<pre><code>public Forest(String forestName){\n name = forestName;\n</code></pre>\n\n<p>Normally you'd do this:</p>\n\n<pre><code>public Forest(String name){\n this.name = name;\n</code></pre>\n\n<p>Don't try to repeat already available information, for example if you have a class which handles the user-input, don't try to have this chain:</p>\n\n<pre><code>org.yourdomain.application.inputhandling.InputHandler.handleInput(InputStream)\n</code></pre>\n\n<p>You constantly repeat yourself and add nothing of value to the names.</p>\n\n<p>org.yourdomain.application.ui.StreamHandler.process(InputStream)</p>\n\n<p>So I know it is part of the \"user interface\" package, so the class handles the input from a stream, and then it processes the input.</p>\n\n<p>Naming is hard, though, takes a lot of practice to get halfway good at it.</p>\n\n<hr>\n\n<pre><code>public void display(){\n</code></pre>\n\n<p>Ideally you would only provide means to get the needed information from <code>Forest</code> and the main class would handle displaying it.</p>\n\n<p>That decouples your class from the environment it is being used in.</p>\n\n<hr>\n\n<pre><code>if(name != null){\n</code></pre>\n\n<p>What? How or why is this a valid state?</p>\n\n<pre><code>public Forest(String name){\n if (name == null || name.trim().isEmpty()) {\n throw new IllegalArgumentException(\"The forest must have a name.\");\n }\n</code></pre>\n\n<hr>\n\n<pre><code>public static void saveForest(Forest forest) throws IOException {\n</code></pre>\n\n<p>Why static? If this would be an instance method, extending classes would have a chance to implement their own logic.</p>\n\n<p>Moreover, this should accept a directory (<code>null</code> for current).</p>\n\n<hr>\n\n<pre><code>ObjectOutputStream toStream;\n\ntoStream = new ObjectOutputStream(new FileOutputStream(name));\n</code></pre>\n\n<p>Why not directly assign it? Moreover, you should use a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try with resources</a> statement to make sure that the stream is always closed.</p>\n\n<p>Creating filestreams has the potential to leak file handles if they have not been closed.</p>\n\n<hr>\n\n<pre><code>return(local);\n</code></pre>\n\n<p>Random parenthesis? <code>return</code> is a keyword, not a function.</p>\n\n<hr>\n\n<pre><code>final double MIN_HEIGHT = 1;\nfinal double MIN_GROWTH_RATE = 0.5;\nfinal double MAX_HEIGHT = 5;\nfinal double MAX_GROWTH_RATE = 1.0;\n</code></pre>\n\n<p>Ideally these would also be properties handed to the Forest. Consider the following structure:</p>\n\n<pre><code>class Forest\n public static final int DEFAULT_MAX_TREES = 10;\n public static final double DEFAULT_MIN_TREEHEIGHT = 0.5d;\n ...\n\n public Forest(name) {\n this(name, DEFAULT_MAX_TREES, DEFAULT_MIN_TREEHEIGHT, ...)\n }\n\n public Forest(name, int maximumTrees, double minTreeHeight) {\n trees.add(new Tree(minTreeHeight, ...)\n</code></pre>\n\n<p>But I like that the <code>Tree</code> is responsible for its growing, that gives extending classes a chance to easily change the logic and also gives you the possibility to mix different <code>Tree</code> classes in the <code>Forest</code>.</p>\n\n<pre><code>trees.add(new Tree(...));\ntrees.add(new SlowGrowingTree(...));\ntrees.add(new FastGrowingTree(...));\ntrees.add(new SickTree(...));\n</code></pre>\n\n<hr>\n\n<pre><code>Random rand = new Random();\n</code></pre>\n\n<p>As a heads up, please always be aware how the default constructor of a PRNG works! In this case this usage is okay because the default constructor of <code>Random</code> tries <em>very, very</em> hard to not give you to matching instances <em>ever</em>. However, the .NET <code>Random</code> class for example is (or at least was for a decade) initialized with the current timestamp in seconds, so if you did this:</p>\n\n<pre><code>Random a = new Random();\nRandom b = new Random();\nRandom c = new Random();\nRandom d = new Random();\n</code></pre>\n\n<p>All four instances would return the same numbers.</p>\n\n<p>That's something to keep in mind, always check the documentation if you are safe or not.</p>\n\n<hr>\n\n<p>Overall looks quite nice, good job.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:29:09.343",
"Id": "219483",
"ParentId": "219456",
"Score": "0"
}
},
{
"body": "<p>You can toUppercase() your userInput. This will reduce the complexity. No need to check if 'a' or 'A', etc.</p>\n\n<p>You should use an ENUM for userInput. Instaed of </p>\n\n<p><code>case 'D':</code></p>\n\n<p>you'd have:</p>\n\n<p><code>case UserChoice.DISPLAY:</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T23:11:01.960",
"Id": "219536",
"ParentId": "219456",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T18:53:06.037",
"Id": "219456",
"Score": "4",
"Tags": [
"java",
"simulation"
],
"Title": "Simulation of forest growth and pruning"
} | 219456 |
<p>I wrote a simple function that finds a word in a string without use of the <code>re</code> module.</p>
<p>My function looks like this:</p>
<pre class="lang-py prettyprint-override"><code>def find_in_string(string, word):
Indices = ()
wordlength = len(word)
for i in range(0, len(string)):
if string[i:i + wordlength] == word:
Indices += (i,)
return Indices
</code></pre>
<p>Is there any way to improve it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T01:21:58.460",
"Id": "423946",
"Score": "0",
"body": "How exactly do you define a \"word\"? Do you simply mean finding occurrences of a substring within a string?"
}
] | [
{
"body": "<ul>\n<li>I don't like the name of your function. Find <em>what</em> in string? Something like <code>find_all_substring_indices()</code> better describes what the function does</li>\n<li>You aren't finding words, you're finding substrings. Your code would find the word \"car\" twice in \"carcar\" even though we would consider \"carcar\" a single word. You mention the re package. Presumably, you're talking about word boundaries. They behave a little differently (punctuation can be a word separator). But, since your original question doesn't behave that way, it is not a refactoring for me to suggest how to do that (nor is it on topic, \"how do I replicate regex word boundaries?\" is a question for StackOverflow)</li>\n<li><code>Indices</code> should be <code>snake_case</code>. Only class names are <code>UpperCamelCase</code></li>\n<li>Don't use a tuple for <code>indices</code>! Every time you append to it you have to create a new object because tuples are immutable. In fact, you are creating two: one for the <code>(i,)</code> and then another one when you do <code>indices + (i,)</code>. Use a list: <code>indices = []</code> then <code>indices.append(i)</code>! That's what they're meant for!</li>\n<li><code>range(0, len(string))</code> can just be <code>range(len(string))</code></li>\n<li><code>string[i:i+wordlength] == word</code> is the same thing as (and much less clear than) <code>string[i:].beginswith(word)</code></li>\n<li>All of this slicing is really inefficient, especially given there is also a string method that does what you want: <code>index</code></li>\n<li>You should <code>unittest</code> your code! I suspect you have a bug in that if your \"word\" is \"FooFoo\" it will be found twice in \"Little bunny FooFooFoo\" (once at the beginning of \"FooFooFoo\" and once three characters into \"FooFoo\"). Surely, words shouldn't be able to overlap like this.</li>\n<li>Add <code>\"\"\"Docstrings.\"\"\"</code> to document what your function does.</li>\n</ul>\n\n<p>You should just be repeatedly using <code>index</code> until you read the end of the string. This is more efficient than doing slicing by yourself or sliding the substring character by character along your string. <a href=\"https://stackoverflow.com/a/4665027/568785\">Stealing mostly from SO</a>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def find_all_substrings(string, sub):\n start = 0\n\n while True:\n try:\n start = string.index(sub, start)\n except ValueError:\n break\n\n yield start\n start += len(sub)\n</code></pre>\n\n<p>This is a generator, if you still want a tuple returned you can just build one up instead (but at a list first!):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def find_all_substrings(string, sub):\n indices = []\n start = 0\n\n try:\n while True:\n start = string.find(sub, start)\n indices.append(start)\n start += len(sub)\n except ValueError:\n pass\n\n return tuple(indices)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T03:18:02.893",
"Id": "219473",
"ParentId": "219460",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T19:38:02.933",
"Id": "219460",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "Python snippet for finding word in string"
} | 219460 |
<p>I've been doing a Java for beginners course for a few weeks (2 hours a week), we had an exam question.</p>
<blockquote>
<p>Take a sentence as an input from a user for twitter. Using only String
Arrays and String Buffers (do not use split() or any other methods not
covered in class yet). Separate the sentence into words and add to an
array. Then change any instance of the word "cannot" with "can't".
Must use an instantiable class and all relevant set, compute, get
methods covered. Comment all code to show you understand what
everything you've used is doing.</p>
</blockquote>
<p>This is the code I submitted (it works), looking for feedback before the results come out to see what I can expect. </p>
<p>Thanks</p>
<p><strong>App Class</strong>
enter code here</p>
<pre><code>public class tweetApp{
public static void main(String arg[]){
//decalre variables
String sentence;
//create an array for the new sentence
String [] newSentence;
//instaniate classes
tweet myTweet;
Scanner input;
//creat classes
myTweet = new tweet();
input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
sentence = input.nextLine();
//set method for the sentence inputted from the user
myTweet.setSentence(sentence);
//compute method for chaging the sentence given by the user
myTweet.computeSentence();
//set the array to the new changed sentence
newSentence = myTweet.getNewSentence();
//output each section of the array and a space, to print out the entire message
for(int y = 0; y < newSentence.length; y++){
System.out.print(newSentence[y]+" ");
}
//end the program by adding a blank print line to make sure the command line looks ok.
System.out.println();
}
}
enter code here
</code></pre>
<p><strong>Instantiable class</strong></p>
<pre><code>enter code here
public class tweet{
//declare variables
private String sentence;
private int strlen;
private StringBuffer word;
private String newSentence[];
private String newWord;
private int wordCount;
//create constuctor
public tweet(){
sentence = " ";
strlen = 0;
word = new StringBuffer();
wordCount = 1; //starting at 1 if user enters 1 word
newSentence = new String[wordCount];
newWord = " ";
}
//set method
public void setSentence(String sentence){
this.sentence = sentence;
}
//compute method
public void computeSentence(){
strlen = sentence.length();//get length of sentence
for(int x = 0; x < strlen; x++){//transverse the string,
if(sentence.charAt(x)==' '){//calculate word count
wordCount = wordCount +1;
}
}
newSentence = new String[wordCount]; //use word count to set size of the array
for(int j = 0; j < newSentence.length; j++){//transverse the array,
for(int i = 0; i< strlen; i++){//transverse string,
if(sentence.charAt(i) == ' '){//check if char is a space,
j = j+1;//if so,increment j by 1
word = new StringBuffer();//start a new buffer
}
else{
word.append(sentence.charAt(i));//char at i, append to buffer,
newWord = word.toString();//convert buffer to string,
newSentence[j] = newWord;//add to j'th place of array
}
}
}
for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't
if(newSentence[x].equalsIgnoreCase("cannot")){
newSentence[x] = "can't";
}
}
}
//get method, returning new sentence to app class
public String[] getNewSentence(){
return newSentence;
}
}
</code></pre>
| [] | [
{
"body": "<p>Thanks for sharing your code,</p>\n\n<p>This looks very good for just having a few weeks' experience.</p>\n\n<p>Let's start with a some small things,</p>\n\n<h1>1 Initialization vs declaration</h1>\n\n<p>this line of code <code>tweet myTweet;</code> declares a variable, while this line of code <code>myTweet = new tweet();</code> instantiates it. When possible it's preferable to do both on the same line. This has a few benefits.</p>\n\n<ul>\n<li>There's less change for things to go wrong. In a larger application, there could be many things happening between <code>declaration</code> and <code>initialization</code> leading to potentially difficulty to track down bugs.</li>\n<li>It makes the code easier to follow for other developers (and future you)</li>\n</ul>\n\n<p>for these reasons, I would prefer to see</p>\n\n<ul>\n<li><code>tweet myTweet = new tweet();</code></li>\n<li><code>Scanner input = new Scanner(System.in);</code></li>\n<li><code>String sentence = input.nextLine();</code></li>\n</ul>\n\n<p>etc.</p>\n\n<h1>2 Java naming conventions</h1>\n\n<p>Classes should start with a capital letter. You'll notice all the standard library classes begin with a capital letter (String, List, Scanner etc.) while primitive types (int, float, double) start with a lower case letter. With this in mind, it would be better to have your class called <code>Tweet</code></p>\n\n<h1>3-0 Add setters to classes only if you absolutely need to</h1>\n\n<p>If your code, you call <code>myTweet.setSentence(sentence);</code> setters generally exist when you <code>need</code> to update the state of an object some time after its creation, in this case, we update it right away! Why not simply pass <code>sentence</code> as another constructor argument, it could look like this.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Scanner input = new Scanner(System.in);\nString sentence = input.nextLine();\nTweet myTweet = new Tweet(sentence);\n</code></pre>\n\n<p>No need to update the <code>Tweet</code> once it has been created.</p>\n\n<h1>3-1</h1>\n\n<p>Staying on the topic of unnecessary mutation, we call <code>myTweet.computeSentence();</code> the first thing I notice about this method is that it has a <code>void</code> return type. This usually means one thing. <code>side effects</code>. In this context, a side effect means we call a method and something else is happening (in this case, we're mutating the state of the object.)</p>\n\n<p>One other potential problem, is that in order for me to get the expected result from <code>myTweet.getNewSentence();</code> I need to remember to call <code>myTweet.computeSentence();</code> first! In a small program, not a big deal, but as our objects get more and more complicated, this becomes more of an issue. What if my entire main method could look like this.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n System.out.print(\"Enter a sentence: \");\n String sentence = input.nextLine();\n Tweet myTweet = new Tweet(sentence);\n String [] newSentence = myTweet.getNewSentence();\n for(int y = 0; y < newSentence.length; y++){\n System.out.print(newSentence[y]+\" \");\n }\n System.out.println();\n}\n</code></pre>\n\n<p>This is <strong>very</strong> similar to what you already have. But there area few notable changes.\n1. I declare and initialize variables at the same time.\n2. I pass all <code>dependencies</code> to the <code>Tweet</code> constructor (the sentence) at creation time.\n3. I don't need to remember to call certain setup methods (computeState)\n4. Conform to Java naming standards (<code>Tweet</code> vs <code>tweet</code>)</p>\n\n<h1>4 Storing unneeded instance variables</h1>\n\n<p>Let's take a quick look at the Tweet class, so we store all these</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private String sentence;\nprivate int strlen;\nprivate StringBuffer word;\nprivate String newSentence[];\nprivate String newWord;\nprivate int wordCount;\n</code></pre>\n\n<p>I was curious as to why we need to store all these. In our constructor, we initialize a lot of them. Why not just do that in the <code>getNewSentence</code> method instead</p>\n\n<p>We end up with a <code>Tweet</code> class that looks like </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Tweet {\n\n private String sentence;\n\n public Tweet(String sentence){\n this.sentence = sentence;\n }\n\n //get method, returning new sentence to app class\n public String[] getNewSentence(){\n StringBuffer word = new StringBuffer();\n String newWord = \" \";\n int wordCount = 1;\n\n\n int strlen = sentence.length();//get length of sentence\n for(int x = 0; x < strlen; x++){//transverse the string,\n if(sentence.charAt(x)==' '){//calculate word count\n wordCount = wordCount +1;\n }\n }\n String[] newSentence = new String[wordCount]; //use word count to set size of the array\n for(int j = 0; j < newSentence.length; j++){//transverse the array,\n for(int i = 0; i< strlen; i++){//transverse string,\n if(sentence.charAt(i) == ' '){//check if char is a space,\n j = j+1;//if so,increment j by 1\n word = new StringBuffer();//start a new buffer\n }\n else{\n word.append(sentence.charAt(i));//char at i, append to buffer,\n newWord = word.toString();//convert buffer to string,\n newSentence[j] = newWord;//add to j'th place of array\n }\n }\n }\n for(int x = 0; x < newSentence.length; x++){//change any instance of cannot to can't\n if(newSentence[x].equalsIgnoreCase(\"cannot\")){\n newSentence[x] = \"can't\";\n }\n }\n return newSentence;\n }\n}\n</code></pre>\n\n<p>With this class, we don't need to worry about who used it before, or how they used it. <code>It will never be in a bad state</code> we can call <code>getNewSentence</code> all day long and it will always return the same thing, no need to worry about set up with <code>setSentence</code> or <code>computerState</code></p>\n\n<p>Hopefully you found this review useful, I'd like to reiterate again that this looks very good for just a few weeks! Keep it up!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T00:47:01.693",
"Id": "423944",
"Score": "0",
"body": "Thank you for the review, extremely useful! Even though I've already submitted the code for grading I'm going to rewrite with the pointers you've given me and hopefully I can learn a bit more from it, very much appreciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T00:19:38.863",
"Id": "219468",
"ParentId": "219465",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "219468",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-30T22:53:49.650",
"Id": "219465",
"Score": "1",
"Tags": [
"java",
"beginner"
],
"Title": "Splitting a String into words and add to an array, Only using StringBuffer and String Array"
} | 219465 |
<p>I am learning how to program in opencl and I made a simple program that simply takes an array and adds 1 to every element. I want to run it many times (this is just so that i can benchmark how it does against my cpu, I understand it is a dumb application).</p>
<p>I feel like the way I am doing it right now is inefficient because i seem to be instructing the gpu to do each iteration one by one instead of telling it from the start that it has to do it many times.</p>
<p>Here is my code (Please look for the comment "RELEVANT PART STARTS HERE":</p>
<pre><code>#include <iostream>
#include <CL/cl.hpp>
int main(){
//get all platforms (drivers)
std::vector<cl::Platform> all_platforms;
cl::Platform::get(&all_platforms);
if(all_platforms.size()==0){
std::cout<<" No platforms found. Check OpenCL installation!\n";
exit(1);
}
cl::Platform default_platform=all_platforms[0];
std::cout << "Using platform: "<<default_platform.getInfo<CL_PLATFORM_NAME>()<<"\n";
//get default device of the default platform
std::vector<cl::Device> all_devices;
default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices);
if(all_devices.size()==0){
std::cout<<" No devices found. Check OpenCL installation!\n";
exit(1);
}
cl::Device default_device=all_devices[0];
std::cout<< "Using device: "<<default_device.getInfo<CL_DEVICE_NAME>()<<"\n";
cl::Context context({default_device});
cl::Program::Sources sources;
// kernel calculates for each element C=A+B
std::string kernel_code=
" void kernel simple_add(global int* A){ "
" A[get_global_id(0)]=A[get_global_id(0)]+1; "
" } ";
sources.push_back({kernel_code.c_str(),kernel_code.length()});
cl::Program program(context,sources);
if(program.build({default_device})!=CL_SUCCESS){
std::cout<<" Error building: "<<program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(default_device)<<"\n";
exit(1);
}
const int N = 1e5 ;
// create buffers on the device
cl::Buffer buffer_A(context,CL_MEM_READ_WRITE,sizeof(int)*N);
int A[N] ;
for(int i = 0;i<N;i++){
A[i] = i;
}
//create queue to which we will push commands for the device.
cl::CommandQueue queue(context,default_device);
queue.enqueueWriteBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);
int C = 1e5;
// RELEVANT PART STARTS HERE !!!
for(int i = 0;i<C;i++){
cl::Kernel kernel_add=cl::Kernel(program,"simple_add");
kernel_add.setArg(0,buffer_A);
queue.enqueueNDRangeKernel(kernel_add,cl::NullRange,cl::NDRange(N),cl::NullRange);
queue.finish();
}
// RELEVANT PART ENDS HERE !!!
queue.enqueueReadBuffer(buffer_A,CL_TRUE,0,sizeof(int)*N,A);
printf("%d\n",A[N-4]);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Sorry, but this is a general review and will not answer your specific question. While this is a simple test program, it is good to develop some habits in writing C or C++ programs.</p>\n\n<p><strong>Complexity</strong><br>\nOne of the good habits to keep in mind is the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> which states </p>\n\n<blockquote>\n <p>\"every module, class, or function should have responsibility over a\n single part of the functionality provided by the software, ...\".</p>\n</blockquote>\n\n<p>The Single Responsibility Principle is the first pillar in <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> programming. SOLID programming is a set of principles that generally improve object oriented programming.</p>\n\n<p>The code is too complex to be in one function, <code>main()</code> could be divided into may functions that would make it easier to read and debug. Generally <code>main()</code> should do the following when necessary:<br>\n - call a function to process command line arguments.<br>\n - call functions to set up for any processing<br>\n - call one function to do the processing, this function may call\n many other functions<br>\n - call functions to clean up after processing</p>\n\n<p>In this program there doesn't seem to be any command line arguments so that function isn't necessary. Some possible functions called by <code>main()</code>:<br>\n - Set Up Platforms<br>\n - Set Up Devices<br>\n - Set Up Program<br>\n - Set Up Queues<br>\n - Execute Program<br>\nAny or all of these functions can return bool or int to indicate success or failure</p>\n\n<p><strong>Use System Defined Constants to Make Code More Readable</strong><br>\nRather than using <code>return(1);</code> or <code>return(0)</code> in main there are constants defined in <code>cstdlib</code> or <code>stdlib.h</code> that indicate success or failure of a program, these are <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\">EXIT_SUCCESS and EXIT_FAILURE</a>. Since they are system defined they are more portable than <code>zero</code> or <code>one</code>. They also make the code self documenting:</p>\n\n<pre><code> return(EXIT_SUCCESS);\n\n return(EXIT_FAILURE);\n</code></pre>\n\n<p><strong>Avoid the Use of the Exit Function in C++ and C</strong><br>\nThe code is good in that it only calls <code>std::exit()</code> <code>from main()</code>, however, it is generally a bad idea to call <code>std::exit()</code> especially from functions that are not <code>main()</code>. When calling exit from a function other than main no cleanup code will be called and if the program is a program that shouldn't terminate such as an operating system there can be dire side effects. Even calling exit from main may not clean up after processing as explained in this <a href=\"https://stackoverflow.com/questions/30250934/how-to-end-c-code\">stackoverflow.com question</a>. The accepted practice is to call return from main. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:47:32.327",
"Id": "219498",
"ParentId": "219467",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T00:03:14.593",
"Id": "219467",
"Score": "4",
"Tags": [
"c++",
"opencl"
],
"Title": "Repeatedly incrementing array elements using OpenCL"
} | 219467 |
<p>I found a Go language code to do RGB to YCbCr conversion from <a href="https://golang.org/src/image/color/ycbcr.go" rel="nofollow noreferrer">here</a>! I ported it to Java:</p>
<pre><code>private byte[] generateColorBar(int width,int height) {
final int COL[][] =
{
{ 255, 255, 255 }, // 100% White
{ 255, 255, 0 }, // Yellow
{ 0, 255, 255 }, // Cyan
{ 0, 255, 0 }, // Green
{ 255, 0, 255 }, // Magenta
{ 255, 0, 0 }, // Red
{ 0, 0, 255 }, // Blue
{ 0, 0, 0 }, // Black
};
int columnHeight = height / COL.length;
byte[] arr = new byte[width*height*3/2];
int yOffset = 0;
int uvOffset = width*height;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
int idx = j / columnHeight;
int R = COL[idx][0];
int G = COL[idx][1];
int B = COL[idx][2];
int yIndex = j*width+i;
int uvIndex = j*width/2+i;
int Y = (19595*R + 38470*G + 7471*B + (1<<15)) >> 16;
int Cb = -11056*R - 21712*G + 32768*B + (257<<15);
if ((Cb & 0xff000000) == 0) {
Cb >>= 16;
} else {
Cb = 0xffffffff ^ (Cb >> 31);
}
int Cr = 32768*R - 27440*G - 5328*B + (257<<15);
if ((Cr & 0xff000000) == 0) {
Cr >>= 16;
} else {
Cr = 0xffffffff ^ (Cr >> 31);
}
arr[yOffset + yIndex] = (byte) Y;
if (i%2 == 0 && j%2 == 0) {
arr[uvOffset + uvIndex] = (byte) Cb;
arr[uvOffset + uvIndex + 1] = (byte) Cr;
}
}
}
return arr;
}
</code></pre>
<p>Please help review it.</p>
<p>The original Go language code is below:</p>
<blockquote>
<pre><code>// RGBToYCbCr converts an RGB triple to a Y'CbCr triple.
func RGBToYCbCr(r, g, b uint8) (uint8, uint8, uint8) {
// The JFIF specification says:
// Y' = 0.2990*R + 0.5870*G + 0.1140*B
// Cb = -0.1687*R - 0.3313*G + 0.5000*B + 128
// Cr = 0.5000*R - 0.4187*G - 0.0813*B + 128
// https://www.w3.org/Graphics/JPEG/jfif3.pdf says Y but means Y'.
r1 := int32(r)
g1 := int32(g)
b1 := int32(b)
// yy is in range [0,0xff].
//
// Note that 19595 + 38470 + 7471 equals 65536.
yy := (19595*r1 + 38470*g1 + 7471*b1 + 1<<15) >> 16
// The bit twiddling below is equivalent to
//
// cb := (-11056*r1 - 21712*g1 + 32768*b1 + 257<<15) >> 16
// if cb < 0 {
// cb = 0
// } else if cb > 0xff {
// cb = ^int32(0)
// }
//
// but uses fewer branches and is faster.
// Note that the uint8 type conversion in the return
// statement will convert ^int32(0) to 0xff.
// The code below to compute cr uses a similar pattern.
//
// Note that -11056 - 21712 + 32768 equals 0.
cb := -11056*r1 - 21712*g1 + 32768*b1 + 257<<15
if uint32(cb)&0xff000000 == 0 {
cb >>= 16
} else {
cb = ^(cb >> 31)
}
// Note that 32768 - 27440 - 5328 equals 0.
cr := 32768*r1 - 27440*g1 - 5328*b1 + 257<<15
if uint32(cr)&0xff000000 == 0 {
cr >>= 16
} else {
cr = ^(cr >> 31)
}
return uint8(yy), uint8(cb), uint8(cr)
}
</code></pre>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T01:42:16.537",
"Id": "423947",
"Score": "1",
"body": "Use this formula instead: int Y = 16 + (((R<<6) + (R<<1) + (G<<7) + G + (B<<4) + (B<<3) + B)>>8);\n int Cb = 128 + ((-((R<<5) + (R<<2) + (R<<1)) - ((G<<6) + (G<<3) + (G<<1)) + (B<<7) - (B<<4))>>8);\n int Cr = 128 + (((R<<7) - (R<<4) - ((G<<6) + (G<<5) - (G<<1)) - ((B<<4) + (B<<1)))>>8);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:13:01.910",
"Id": "424006",
"Score": "1",
"body": "I see you removed the statement \"_Not sure if it caused by int overflow in java! I try to change it to long but still not helpful!_\" and added the statement \"_The output sounds good for my color bar, please help review if it's good._\". Is the java code working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:53:23.623",
"Id": "424012",
"Score": "0",
"body": "Yes, it works now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-07T08:14:43.423",
"Id": "424691",
"Score": "0",
"body": "is there any reason why you use java? one benefit of java is the OOP and i can't see much objects in your code..."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T01:15:35.797",
"Id": "219470",
"Score": "4",
"Tags": [
"java",
"algorithm",
"bitwise",
"unit-conversion"
],
"Title": "RGB to YCbCr conversion in Java"
} | 219470 |
<p>I have created an open source project that uses Rspec to validate the formatting of AWS::CloudFormation::Init YAML blocks in CloudFormation templates.<sup>1</sup></p>
<p>My project is <a href="https://github.com/alexharv074/cfn-init-validate/blob/9195d27e83eb9014e68b8357fb2ce3d5ef3c71bb/spec/validate_spec.rb" rel="nofollow noreferrer">here</a>.</p>
<p>Some general concerns:</p>
<ul>
<li><p>Is this a valid use-case for using Rspec?</p></li>
<li><p>Is the documentation in the code okay?</p></li>
</ul>
<p>I have some specific concerns about the code. Concerning the recursive <code>compare()</code> method:</p>
<pre class="lang-ruby prettyprint-override"><code># Method: compare
#
# Recursively compare real blocks in a CloudFormation template
# with the spec defined in $types.
#
# @param data [Hash] The real data in the template.
# @param spec [Hash] The reference data corresponding to this
# key in $types.
#
def compare(data, spec)
if spec.is_a?(Hash)
check_keys(data.keys, spec.keys)
end
data.each do |k,v|
context k do
if spec == Array
it "#{k} should match Array" do
expect(v.class).to eq Array
end
elsif spec[k] == Hash
it "#{k} should match Hash" do
expect(v.class).to eq Hash
end
elsif spec == {String => Array} or
spec == {String => String}
it "#{k}=>#{v} should match #{spec}" do
expect(k.class).to eq spec.keys.first
expect(v.class).to eq spec[spec.keys.first]
end
elsif spec.has_key?(k)
if v.is_a?(Hash)
compare(v, spec[k]) # recurse.
elsif spec[k].is_a?(Regexp)
it "#{k} should match #{spec[k]}" do
expect(v).to match spec[k]
end
elsif spec[k] == String
# Actually, an Array of Strings joined by CloudFormation
# is also okay.
#
it "#{k} should match #{spec[k]}" do
expect([String, Array].include?(v.class)).to be true
end
elsif spec[k] == Fixnum
it "#{k} should match (or be cast to) #{spec[k]}" do
expect { v.to_i }.to_not raise_error
end
elsif [Array, TrueClass, FalseClass]
.include?(v.class)
it "#{v} should be a #{spec[k]}" do
expect(v).to be_a spec[k]
end
end
elsif v.is_a?(Hash)
spec_key = spec.keys.first
compare(v, spec[spec_key]) # recurse.
else
raise "Something went wrong"
end
end
end
end
</code></pre>
<ul>
<li>Can this conditional logic be simplified in any way?</li>
</ul>
<p>The <code>compare()</code> method compares input data against this reference spec:</p>
<pre class="lang-ruby prettyprint-override"><code>module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end
# Supporting Ruby < 2.4.
#
if not defined?(Fixnum)
class Fixnum < Integer; end
end
# This hash defines the expected format of
# config sets in AWS::CloudFormation::Init blocks.
#
# Data types and regular expressions used as
# placeholders for real values.
#
# Based on documentation here:
#
# https://docs.aws.amazon.com/AWSCloudFormation/
# latest/UserGuide/aws-resource-init.html
#
$types = {
'packages' => {
'apt' => {String => Array},
'msi' => {String => String},
'python' => {String => Array},
'rpm' => {String => String},
'rubygems' => {String => Array},
'yum' => {String => Array},
},
'groups' => {
String => {'gid' => Fixnum},
},
'users' => {
String => {
'groups' => Array,
'uid' => Fixnum,
'homeDir' => String,
},
},
'sources' => {String => String},
'files' => {
String => {
'content' => String,
'source' => /^http/,
'encoding' => /plain|base64/,
'group' => String,
'owner' => String,
'mode' => Fixnum,
'authentication' => String,
'context' => String,
},
},
'commands' => {
String => {
'command' => String, # TODO. Apparently the only mandatory
'env' => Hash, # attribute.
'cwd' => String,
'test' => String,
'ignoreErrors' => Boolean,
'waitAfterCompletion' => Boolean,
},
},
'services' => {
/sysvinit|windows/ => {
String => {
'ensureRunning' => Boolean,
'enabled' => Boolean,
'files' => Array,
'sources' => Array,
'packages' => Array,
'commands' => Array,
},
},
},
}
</code></pre>
<ul>
<li>Is the use of a global variable okay there? I chose that just to make it stand out. </li>
</ul>
<p>And any general feedback most welcome.</p>
<hr>
<p><sup>1</sup> There is some confusion in the comments about what I actually "implemented" - i.e. where the code-under-test is. <em>I haven't implemented anything</em>. I am using RSpec purely to make assertions about the formatting of YAML files that could come from anywhere. I hope that clarifies this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:14:54.673",
"Id": "424083",
"Score": "0",
"body": "I feel weird using RSpec for the final solution. What are the benefits of using RSpec to do the comparison over putting the comparison logic into classes and using RSpec to test those classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:17:13.687",
"Id": "424084",
"Score": "0",
"body": "@PeterToth-Toma, I'm not sure what you mean. If I understand you, then that would be \"testing the tests\" wouldn't it? CloudFormation is an Amazon product and I'm not the author of that. The intention here is to provide a layer of automated testing that goes beyond what CloudFormation itself can do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:32:56.677",
"Id": "424088",
"Score": "0",
"body": "I mean, you provide a tool that does something. But how do you make sure it works? Usually with automated tests by using a test framework like RSpec. If you create this tool only for yourself to make your life easier, then it's perfectly alright. But if you are thinking to provide it to a wider audience, then I would suggest to use RSpec to test your implementation, which is to validate config files. So I wouldn't use RSpec for implementing the validation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T11:30:43.677",
"Id": "424097",
"Score": "0",
"body": "@PeterToth-Toma, I think you are misunderstanding what I have done. Did you look in my test runner?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:45:30.737",
"Id": "424104",
"Score": "0",
"body": "Ahhha, so the `test_runner.sh` represents the tests for the implementation, which is in the folder for testing. Well, when I come across a project and want to know its behaviour I like to take a look at the tests. They are usually in the `tests` or in the `rspec` folder. But in our case we find the implementation there instead of the real tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T23:29:19.013",
"Id": "424161",
"Score": "0",
"body": "@PeterToth-Toma, I read this all again today and it all makes sense what you're saying now. Great. That's the feedback I needed. Thanks. Having said that, my expectation was that people would simply copy my RSpec code into their project rather than actually try to use this project as a library."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T01:23:16.273",
"Id": "219471",
"Score": "3",
"Tags": [
"ruby",
"validation",
"rspec",
"installer",
"amazon-web-services"
],
"Title": "Validating Amazon CloudFormation templates using Rspec"
} | 219471 |
<p>How can I do this in a more performant way? I'm concerned that throwing the data in a queue like this is defeating the purpose of <code>yield</code> from the <code>open()</code> and also how about handling the shared reference to file handle?</p>
<pre><code>import hashlib
import sys
from threading import Thread
import queue
class HashWorker(Thread):
def __init__(self, queue, fp_out):
Thread.__init__(self)
self.queue = queue
self.fp_out = fp_out
def run(self):
while True:
password = self.queue.get()
try:
hash_threaded(password, self.fp_out)
finally:
self.queue.task_done()
def main(argv):
if sanitize(argv) is False:
return -1
# fp = open(argv[1], "r")
fp_out = open("sha256hashes.txt", "a+")
myqueue = queue.Queue()
for x in range(8):
worker = HashWorker(myqueue, fp_out)
worker.daemon = True
worker.start()
for l in open(argv[1], "r"):
myqueue.put(l)
myqueue.join()
print("Done.")
fp_out.close()
def sanitize(argv):
if len(argv) != 2:
print("USAGE: {} filename.txt".format(argv[0]))
return False
return True
def hash_threaded(password, fp_out):
line_bytes = bytes(password, "ascii")
output_line = hashlib.sha256(line_bytes).hexdigest()
fp_out.write("{}\n".format(output_line))
# print(".", end='')
if __name__ == '__main__':
main(sys.argv)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T05:19:50.793",
"Id": "219477",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"multithreading",
"concurrency"
],
"Title": "Take a list of ascii strings from a file and hash them using python threading"
} | 219477 |
<p>The program needs to only keep directories that have at least 1 .osu (.ini like) file with certain restrictions in them.
It also needs to delete duplicate .osu files.
But since duplicate files are only in duplicate directories (never in the same directory), we can also just delete all but one directories with a similar name.
If you know a better way of achieving this, I'd love to hear it though</p>
<p>I currently achieve it by:</p>
<ul>
<li>look at first few indexes of directory name
<ul>
<li>if they match any of the first few indexes of the other directory names, delete them</li>
</ul></li>
<li>read every .osu file line by line
<ul>
<li>if they contain x keyword and x value, set correctFile boolean true</li>
<li>delete every file where the boolean is false</li>
</ul></li>
<li>delete every directory that doesn't contain an .osu file</li>
</ul>
<p>My code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DeleteAllUnnecesaryOsuBeatmaps
{
class Program
{
static void Main(string[] args)
{
// variables //
string path = @"D:\Games\New folder\Songs"; // change to your songs folder
List<string> thingsToDel = new List<string>();
// delete duplicate directories //
string[] allDirs = Directory.GetDirectories(path);
// the amount of characters (counting from the beginning of the dir name) that have to match before it's counted as a duplicate
int indexesToCheck = 8;
for (int i = 0; i < allDirs.Length; i++)
{
// makes a substring with 'indexesToCheck' amount of characters from the directory name
string dirStart = allDirs[i].Substring(path.Length + 2, indexesToCheck);
// the +2 is because the path allDirs[i] has an additional '//'
// goes trough every dir above i and compares it to 'dirStart'
for (int j = i + 1; j < allDirs.Length; j++)
{
// makes another substring
string otherDirStart = allDirs[j].Substring(path.Length + 2, indexesToCheck);
// if they match, the dir of index i will be deleted later on
if (dirStart == otherDirStart)
{
thingsToDel.Add(allDirs[i]);
break;
}
}
}
// deletes everything in 'thingsToDel'
foreach (string thing in thingsToDel)
{
Directory.Delete(thing, true);
// the true stands for deleting directories, even if they have subdirectories/files
}
thingsToDel.Clear();
// delete files that do not match my needs //
string[] allFiles = Directory.GetFiles(path, "*.osu", SearchOption.AllDirectories);
// .osu files are comparable to .ini files
// if true, the file will not be deleted
bool fileIsCorrect = false;
// if true, the file has mania as mode and needs an aditional check
bool modeIsMania = false;
// checks for each file, if it should be deleted
foreach (string file in allFiles)
{
fileIsCorrect = false;
modeIsMania = false;
string[] lines = File.ReadAllLines(file);
foreach (string line in lines)
{
// format is: Mode = (number between 0 and 3)
if (line.Contains("Mode"))
{
if (line.Contains("0")) // change to your gamemode/s (add || line.Contains("x") to add one)
{
fileIsCorrect = true;
}
else if (line.Contains("3")) // delete these 4 rows if you don't want mania maps
{
modeIsMania = true;
}
}
else if (modeIsMania && (line.Contains("CircleSize") && (line.Contains("4") || line.Contains("7") || line.Contains("10"))))
{ // circlesize is an additional check that only mode mania/3 needs
fileIsCorrect = true;
}
}
if (!fileIsCorrect)
{
thingsToDel.Add(file);
}
}
foreach (string thing in thingsToDel)
{
File.Delete(thing);
}
thingsToDel.Clear();
// delete directories without .osu files //
allDirs = Directory.GetDirectories(path);
foreach (string dir in allDirs)
{
// if a dir does not have at least 1 .osu file in it, it will be delete later
if (Directory.GetFiles(dir, "*.osu").Length == 0)
{
thingsToDel.Add(dir);
}
}
foreach (string thing in thingsToDel)
{
Directory.Delete(thing, true);
}
thingsToDel.Clear();
// end of program //
Console.WriteLine(
"The Program is finished!\n" +
"Press any key to exit...");
Console.ReadKey();
}
}
}
</code></pre>
<p>test environment:
<a href="https://drive.google.com/file/d/15ipqiXoUTeC5s7KLgzPi1Pmht-fbfLcz/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/15ipqiXoUTeC5s7KLgzPi1Pmht-fbfLcz/view?usp=sharing</a>
.osu file example:
<a href="https://drive.google.com/file/d/174SCGPA3fM47SxoNs7dnbQZRQp51mmJs/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/174SCGPA3fM47SxoNs7dnbQZRQp51mmJs/view?usp=sharing</a></p>
<p>the problem is that most users will delete up to thousands of directories with each an average of 3 .osu files in them so it NEEDS to be efficient.
If you know of any way to optimize my methode or the functions I use/my code, please let me know!</p>
<p>Edit:
I'm still a beginner so any tips about structure, comments, naming, expandability etc. would be much appreciated as well!</p>
<p>Edit 2:
Added a test environment and .osu file example</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:26:04.083",
"Id": "423966",
"Score": "1",
"body": "Could you post the complete method instead just the body please? It'd be great if you also coud add a usage example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:38:49.480",
"Id": "423967",
"Score": "2",
"body": "@t3chb0t done :) feel free to ask if you need anything else"
}
] | [
{
"body": "<p>Look into using HashSets. If you want to see if an item is already in a list, you have to search through thousands of list items. With HashSets, it can perform the check instantly. </p>\n\n<p>Go through your list of directory names alphabetically. Every time you look at a directory name, pass it through a method that will remove \" - Copy...\" etc from the end using substring methods. If that processed directory name is not part of the hash set, then add it. If it is already part of the hash set, delete it. </p>\n\n<p>Are the OSU files identical (e.g., there are no minor differences like different white spacing)? If so, you can pass them through a <a href=\"https://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file\">checksum algorithm</a> to compare them. Basically, a file will produce a hash string based on its contents. If another file has the exact same contents, it will produce an identical hash string. If you change just one character, the hash string will be completely different. It's a fast and efficient way to tell if files are identical.</p>\n\n<p>To see if you've encountered a file before, you can add file hash strings to a hash <em>set</em> (sorry for the confusing terminology). If a hash string already exists in your set, you can know for sure that you've seen the file before. </p>\n\n<p>Hope this helps. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T18:59:10.927",
"Id": "424017",
"Score": "0",
"body": "I'm not sure where a `HashSet` would be useful here. Could you clairfy which part of the code it would replace?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:52:48.093",
"Id": "424024",
"Score": "0",
"body": "@t3chb0t Comparing the folder names. It's far better to standardize the names by removing the \"- copy\" business, and then add it to a hash set to see if the folder has been encountered yet. I might use a HashSet to create quick and dirty keys to compare OSU file settings too (e.g. just hash on the relevant settings), but it's probably easier just to a checksum."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:48:28.377",
"Id": "219503",
"ParentId": "219482",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T09:15:53.943",
"Id": "219482",
"Score": "1",
"Tags": [
"c#",
"beginner",
"console",
"file-system",
"io"
],
"Title": "Program that deletes near duplicate directories and directories that have .ini like files"
} | 219482 |
<p>I'm trying to use scrapy to find image URLs that are used more than once on a website across all pages.</p>
<p>This is my spider:</p>
<pre><code># -*- coding: utf-8 -*-
from collections import defaultdict
import scrapy
from scrapy import signals
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class ExampleSpider(CrawlSpider):
handle_httpstatus_list = [403, 404]
name = 'Example'
allowed_domains = ['url.com']
start_urls = ['http://url.com/']
custom_settings = {
'LOG_LEVEL': 'INFO'
}
count_image_occurrences = defaultdict(int)
rules = (
Rule(LinkExtractor(tags='a', attrs='href', unique=True),
callback='parse_item', follow=True),
)
def parse_item(self, response):
# Remember images.
for image in response.xpath('//img/@src').extract():
self.count_image_occurrences[image] += 1
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(ExampleSpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.spider_closed,
signal=signals.spider_closed)
return spider
def spider_closed(self, spider):
spider.logger.info(self.count_image_occurrences)
</code></pre>
<p>Is there a more (speed / memory / code length) efficient way to do this?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T10:52:34.367",
"Id": "219485",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"scrapy"
],
"Title": "Use Scrapy to find duplicate images across pages"
} | 219485 |
<p>I have created a logical AI for a Tic-Tac-Toe game. I want a review about how good or bad it is. Here the computer AI will defend all your attacks as well as try to attack whenever it gets a chance.</p>
<pre><code>import java.util.Random;
import java.util.Scanner;
public class TicTac {
static {
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t ________________________ _______________________");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t |___ ___|___ ___| ____| |___ ___| _ | ____|");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t | | | | | | ____ | | | |_| | |");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t | | | | | | |____| | | | _ | |");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t | | __| |__| |___ | | | | | | |___");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t |__| |________|______| |__| |__| |__|______|");
System.out.println("\n\n");
}
private Scanner sc = new Scanner(System.in);
private char board[] = new char[9];
private char turn = 'X';
private Random random = new Random();
private int winX = 0;
private int winO = 0;
private String name;
private char myChoice = 'O';
public static void main(String[] args) {
TicTac t = new TicTac();
int numberOfGames = 1;
long start, end;
start = System.currentTimeMillis();
do {
t.play();
numberOfGames--;
System.out.println("\t\t\t\t\t\t\t\t\t\t\t----------------------------------------------------------------");
} while (numberOfGames > 0);
end = System.currentTimeMillis();
System.out.println("\n\t\t\t\t\t\t\t\t\t\t\tTime taken by the program to execute is : " + (end - start));
}
private void playersTurn() {
int r;
boolean check = false;
do {
System.out.println("\n\n\t\t\t\t\t\t\t\twhere do you wnt to play , select from 1 - 9 :");
try {
r = getChoice();
if (!(r > 0 && r < 10)) {
Thread.sleep(1000);
throw new NumberFormatException("Invalid Number");
}
r -= 1;
if (board[r] == ' ') {
board[r] = turn;
check = true;
} else if (board[r] == myChoice) {
System.out.println("you already played there");
} else {
System.out.println("computer played there");
}
} catch (Exception e) {
System.out.println("invalid choice. \t " + e);
}
} while (!check);
}
private int getChoice() {
String x = "1";
try {
x = sc.nextLine();
if (x.matches("^[1-9]$")) {
} else {
throw new NumberFormatException("Invalid Number");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return Integer.parseInt(x);
}
private void initializeBoard() {
for (int i = 0; i < 9; i++) {
board[i] = ' ';
}
}
private void switchPlayer() {
if (turn == 'X') {
turn = 'O';
} else if (turn == 'O') {
turn = 'X';
}
}
private boolean win() {
for (int i = 0; i < 9; i++) {
if (board[i] == ' ') {
board[i] = turn;
if (checkWin()) {
return true;
} else {
board[i] = ' ';
}
}
}
return false;
}
private void attack() {
boolean check = false;
do {
int r = random.nextInt(9);
if (r == 1 || r == 3 || r == 5 || r == 7 || r != 4) {
r = random.nextInt(9);
}
if (board[r] == ' ') {
board[r] = turn;
check = true;
}
} while (!check);
}
private boolean defence() {
switchPlayer();
for (int i = 0; i < 9; i++) {
if (board[i] == ' ') {
board[i] = turn;
if (checkWin()) {
switchPlayer();
board[i] = turn;
return true;
} else {
board[i] = ' ';
}
}
}
switchPlayer();
return false;
}
private boolean filled() {
for (int i = 0; i < 9; i++) {
if (board[i] == ' ') {
return false;
}
}
return true;
}
private void play() {
initializeBoard();
do {
if (win()) {
switchPlayer();
} else if (defence()) {
switchPlayer();
} else {
attack();
switchPlayer();
}
display();
if (turn == myChoice && !checkWin() && !filled()) {
playersTurn();
switchPlayer();
display();
}
/*try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
System.out.println("\n");
} while (!filled() && !checkWin());
if (checkWin()) {
switchPlayer();
if (turn == 'O') {
winO++;
} else {
winX++;
}
System.out.println();
display();
System.out.println("\n");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t " + turn + " has won");
} else {
System.out.println();
display();
System.out.println("\n");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t game is draw... ");
}
}
private boolean checkWin() {
return (board[0] == board[1] && board[1] == board[2] && board[0] != ' ' || board[3] == board[4] && board[4] == board[5] && board[3] != ' ' || board[6] == board[7] && board[7] == board[8] && board[6] != ' ' || board[0] == board[4] && board[4] == board[8] && board[0] != ' ' || board[2] == board[4] && board[4] == board[6] && board[2] != ' ' || board[0] == board[3] && board[3] == board[6] && board[0] != ' ' || board[1] == board[4] && board[4] == board[7] && board[1] != ' ' || board[2] == board[5] && board[5] == board[8] && board[2] != ' ');
}
private void display() {
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[0] + " | " + board[1] + " | " + board[2] + " PLAYER 'O' | CPU 'X'");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t---|---|--- ---------|---------");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[3] + " | " + board[4] + " | " + board[5] + " |");
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t---|---|---" + "\t \t\t\t\t" + winO + "\t|\t" + winX);
System.out.println("\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t " + board[6] + " | " + board[7] + " | " + board[8] + " |");
}
}
</code></pre>
| [] | [
{
"body": "<p>Nice work. I got pretty distracted playing a few games before starting the review.</p>\n\n<p>Your 'Tic-Tac' display should be put inside a method, and called on the constructor. This way you're explicitly stating when the title will be printed, rather than leaving it up to the JVM. (The static block will be executed the first time the class is referenced).</p>\n\n<p>I believe you should use a for-loop instead of a while loop;</p>\n\n<pre><code>for (int i = 0; i < numberOfGames; i++)\n</code></pre>\n\n<p>You should declare a variable for all of your whitespace. This will make it easier to edit/maintain:</p>\n\n<pre><code>private static final WHITESPACE = \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\";\n</code></pre>\n\n<p>It's very rare for one character long variable names to be considered acceptable. 'r' is a bad variable name for the users choice.</p>\n\n<p>'check' should also be renamed to 'validChoice' or similar.</p>\n\n<p>If you need to initialize a variable, set it to <code>null</code>, not <code>\"1\"</code>.</p>\n\n<p>Rename 'x' to something more meaningful, such as 'userChoice'.</p>\n\n<p>Get rid of the empty if statement E.G:</p>\n\n<pre><code>if (!x.matches(\"^[1-9]$\")) {\n throw new NumberFormatException(\"Invalid Number\");\n}\n</code></pre>\n\n<p>Actually, you don't need to throw an exception. You should use Exceptions for exceptional cases and avoid them when possible. Throwing / catching exceptions is also very slow.</p>\n\n<p>Your if statement could be made more clear by changing it from:</p>\n\n<pre><code>if (!(r > 0 && r < 10)) {\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if (r <= 0 || r >= 10) {\n</code></pre>\n\n<p>Your <code>switchPlayer</code> method can be simplified to use a ternary E.G:</p>\n\n<pre><code>turn = turn == 'X' ? 'O' : 'X'\n</code></pre>\n\n<p>This if statement can be simplified from:</p>\n\n<pre><code>if (win()) {\n switchPlayer();\n} else if (defence()) {\n switchPlayer();\n} else {\n attack();\n switchPlayer();\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>if (!win() && !defence()) {\n attack();\n}\nswitchPlayer();\n</code></pre>\n\n<p>Your 'checkWin' method could be broken down. For example, if you had a list of possibilities for wins such as: <code>{0, 1, 2}</code>, <code>{3, 4, 5}</code> etc.</p>\n\n<p><strong>Feature consideration:</strong></p>\n\n<p>You could add numbers indicating the location of the squares. For example:</p>\n\n<pre><code> X | O | 3 \n---|---|---\n 4 | 5 | 6\n---|---|---\n 7 | 8 | X \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T23:49:38.660",
"Id": "219538",
"ParentId": "219486",
"Score": "3"
}
},
{
"body": "<p><code>getChoice</code> can be optimized as such. My code uses <code>Character</code> input as opposed to a string value. In the previous case, user can enter a <code>String</code> which is a costly operation and the previous code has an empty <code>if</code> block, which is not good coding practice.</p>\n\n<pre><code>private int getChoice() {\n char x = '1';\n\n try {\n x = sc.next().charAt(0);\n if(x < 48 || x > 57) {\n throw new NumberFormatException(\"Invalid Number\");\n }\n } catch (Exception e) {\n System.out.println(e.getMessage());\n }\n return Character.getNumericValue(x); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T02:00:34.170",
"Id": "223226",
"ParentId": "219486",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219538",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T10:55:19.323",
"Id": "219486",
"Score": "3",
"Tags": [
"java",
"game",
"tic-tac-toe",
"ai"
],
"Title": "Tic-Tac-Toe Player vs Computer"
} | 219486 |
<p>We have a</p>
<pre><code>string text =
"SOME OTHER TEXT
WHITE SPACES AND NEW LINES
[HitObjects]
109,192,7241,1,0,0:0:0:0:
256,192,7413,1,0,0:0:0:0:
475,192,75865,1,0,0:0:0:0:
329,192,86524,1,0,0:0:0:0:
182,192,256242,1,0,0:0:0:0:
256,192,306521,1,2,0:0:0:0:
WHITE SPACES AND NEW LINES
"
</code></pre>
<p>The third number of every row is the milliseconds.
I need to know the seconds between the first time and last time.
Right now I'm doing it like this:</p>
<pre><code>text = text.Substring(text.IndexOf("Objects]") + 8).Trim();
string[] lines = text.Split('\n');
string[] firstLine = lines[0].Split(',');
string[] lastLine = lines[lines.Length - 1].Split(',');
int length = Convert.ToInt32(lastLine[2]) - Convert.ToInt32(firstLine[2]);
length = length / 1000;
</code></pre>
<p>I need to do this with thousands of 'text's though. Any optimalization or other methodes possible?</p>
<p>more information on the request of @Slothario:</p>
<ul>
<li>the string text is the full text of 1 file</li>
<li>file type: .osu </li>
<li>average file size: 25KB</li>
<li>average characters: 30000</li>
<li>SOME OTHER TEXT - HitObjects ratio: 1 - 100</li>
<li>average amount of files to check: 500</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:23:14.510",
"Id": "423979",
"Score": "1",
"body": "This code is perfectly fine, I can't think of better solution for your case. Though it would be more convinient to use JSON/XML for that kind of stuff."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:31:27.650",
"Id": "423989",
"Score": "0",
"body": "How big is each text file? Are they relatively small? Can we get some numbers like the average size of the text files vs. the number of texts you need to read? Why do you want to optimize? What's the application? If we have answers to those questions I could probably be of more help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T15:01:09.863",
"Id": "423991",
"Score": "0",
"body": "@Slothario All done"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T15:03:41.490",
"Id": "423992",
"Score": "0",
"body": "Have you tested how long this will take on 500 files? My guess is it will be pretty fast. Why do you need speed improvements? Do you have to run it several times over and over again?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T15:08:12.490",
"Id": "423994",
"Score": "0",
"body": "This doesn't look very efficient (`Substring`, `Trim` and `Split` all create copies that are not really needed). With custom parsing you could skip all this copying, but will make the code much less simple. That said have you tested if this parsing is the bottleneck, usually when reading files from disk a little inefficiency in the processing won't matter too much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:38:23.433",
"Id": "424000",
"Score": "0",
"body": "I've tested it and it's fast enough indeed. Since it's a personal project it doesn't matter that much anyway. I am always trying to find better ways of doing things and since it's a very specific case I thought asking it here would be appropriate. Thanks to everyone for the help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T22:21:32.203",
"Id": "424152",
"Score": "0",
"body": "A good principle to remember is that [longer strings are found faster than short ones](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). Your call to `IndexOf` could specify `\\n[HitObjects]\\n` and cut the search effort nearly in half."
}
] | [
{
"body": "<p>If you want to support an insane large file with a small hardware footprint you should use streaming. Something like</p>\n\n<pre><code>public static class Program\n{\n public static void Main(string[] args)\n {\n string text =\n @\"SOME OTHER TEXT\nWHITE SPACES AND NEW LINES\n\n[HitObjects]\n109,192,7241,1,0,0:0:0:0:\n256,192,7413,1,0,0:0:0:0:\n475,192,75865,1,0,0:0:0:0:\n329,192,86524,1,0,0:0:0:0:\n182,192,256242,1,0,0:0:0:0:\n256,192,306521,1,2,0:0:0:0:\n\nWHITE SPACES AND NEW LINES\n\";\n\n Task.Run(async () =>\n {\n using (var reader = new StringReader(text)) //This should be streamed from a disk or network stream or similar\n {\n string line;\n var inScope = false;\n int? start = null;\n int last = 0;\n\n while ((line = (await reader.ReadLineAsync())) != null)\n {\n if (inScope)\n {\n var values = line.Split(',');\n if (values.Length != 6)\n break;\n\n last = int.Parse(values[2]);\n\n if (!start.HasValue)\n start = last;\n\n } else if (line.StartsWith(\"[HitObjects]\"))\n inScope = true;\n } \n Console.WriteLine(last - start);\n }\n });\n\n Console.ReadLine();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T08:14:01.410",
"Id": "219627",
"ParentId": "219487",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:21:48.960",
"Id": "219487",
"Score": "1",
"Tags": [
"c#",
"strings"
],
"Title": "Calculating the seconds between 2 numbers in a specific place in a string"
} | 219487 |
<p>This is the latest version of my Blackjack game that uses a MySQL database to store user info. I did everything I was recommended in my previous post, added a ranking system and also fixed a bug where you could make infinite money.</p>
<pre><code>from random import shuffle
import os
import cymysql
from getpass import getpass
import sys
import re
from bcrypt import hashpw, gensalt
def shuffled_shoe():
shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
shuffle(shoe)
return shoe
def deal_card(shoe, person, number):
for _ in range(number):
person.append(shoe.pop())
def deal_hand(shoe, player, dealer):
for _ in range(2):
deal_card(shoe, player, 1)
deal_card(shoe, dealer, 1)
def score(person):
non_aces = (c for c in person if c != 'A')
aces = (c for c in person if c == 'A')
total = 0
for card in non_aces:
if card in 'JQK':
total += 10
else:
total += int(card)
for card in aces:
if total <= 10:
total += 11
else:
total += 1
return total
def set_money(money, money_bet, win, push):
if win:
money += money_bet * 2
elif push:
money += money_bet
return money
def clear_console():
os.system('cls' if os.name == 'nt' else 'clear')
def display_info(still_playing, player, dealer, money, money_bet, player_stands):
win = False
push = False
clear_console()
print(f'Money: ${money}')
print(f'Money bet: ${money_bet}')
print('Your cards: [{}] ({})'.format(']['.join(player), score(player)))
if player_stands:
print('Dealer cards: [{}] ({})'.format(']['.join(dealer), score(dealer)))
else:
print('Dealer cards: [{}][?]'.format(dealer[0]))
first_hand = len(dealer) == 2
if score(player) == 21:
print('Blackjack! You won')
still_playing = False
win = True
elif first_hand and score(dealer) == 21:
print('Dealer got a blackjack. You lost!')
still_playing = False
elif score(player) > 21:
print('Busted! You lost!')
still_playing = False
if player_stands:
if score(dealer) > 21:
print('Dealer busted! You won')
win = True
elif score(player) > score(dealer):
print('You beat the dealer! You won!')
win = True
elif score(player) < score(dealer):
print('Dealer has beaten you. You lost!')
else:
print('Push. Nobody wins or losses.')
push = True
still_playing = False
money = set_money(money, money_bet, win, push)
return still_playing, money
def hit_or_stand():
while True:
print('What do you choose?')
print('[1] - Hit')
print('[2] - Stand')
ans = input('> ')
if ans in '12':
return ans
def bet(money):
clear_console()
print(f'Money: ${money}')
print('How much money do you want to bet?')
while True:
money_bet = int(input('> '))
if money_bet <= money and not money_bet <= 0:
money -= money_bet
return money, money_bet
print('Please enter a valid bet.')
def player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands):
while not player_stands:
if hit_or_stand() == '2':
player_stands = True
player_plays = False
elif not player_stands:
deal_card(shoe, player, 1)
display_info(True, player, dealer, money, money_bet, player_stands)
if score(player) >= 21:
player_plays = False
break
return player_plays, player_stands
def dealer_play(shoe, dealer, dealer_minimum_score):
while score(dealer) <= dealer_minimum_score:
deal_card(shoe, dealer, 1)
return False
def check_money(money):
if money == 0:
print('\nUnfortunately you do not have any money.')
sys.exit()
def update_db_money(cur, money, email):
cur.execute('UPDATE `users` SET `money`=%s WHERE `email`=%s', (money, email))
def play_again(money):
check_money(money)
while True:
print('\nDo you want to play again? [Y]es/[N]o')
ans = input('> ').lower()
if ans == 'y':
return True
elif ans == 'n':
return False
def get_user_info():
while True:
email = input('Email address (max. 255 chars.): ')
password = getpass('Password (max. 255 chars.): ').encode('utf-8')
hashed_pw = hashpw(password, gensalt())
if len(email) < 255 and len(password) < 255:
if re.match(r'[^@]+@[^@]+\.[^@]+', email):
return email, password, hashed_pw
print('Please enter a valid email address.')
def register(cur, email, hashed_pw):
cur.execute('INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)', (email, hashed_pw))
def login(cur, email, password, hashed_pw):
cur.execute('SELECT * FROM `users` WHERE `Email`=%s LIMIT 1', (email,))
correct_credentials = cur.fetchone()
correct_hash = correct_credentials[2].encode('utf-8')
if hashpw(password, correct_hash) == correct_hash:
print('You have succesfully logged-in!')
else:
print('You failed logging-in!')
sys.exit()
def check_account(cur, email):
cur.execute('SELECT * FROM `users` WHERE `Email`=%s LIMIT 1', (email,))
return bool(cur.fetchone())
def display_top(cur):
cur.execute('SELECT * FROM `users` ORDER BY `money` DESC')
top = cur.fetchall()
places = range(1, len(top)+1)
for (a, b, c, d), i in zip(top, places):
print(f'{i}. {b} - ${d}')
def start():
print('\nWhat do you want to do?\n1 - Start playing\n2 - Display the top')
ans = input('> ')
if ans == '1':
return True
elif ans == '2':
return False
def db_conn():
conn = cymysql.connect(
host='127.0.0.1',
user='root',
passwd='',
db='database'
)
with conn:
cur = conn.cursor()
email, password, hashed_pw = get_user_info()
checked = check_account(cur, email)
if checked:
login(cur, email, password, hashed_pw)
else:
register(cur, email, hashed_pw)
print('You have succesfully registered and recieved $1000 as a gift!')
cur.execute('SELECT `money` FROM `users` WHERE `email`=%s', (email,))
money_tuple = cur.fetchone()
money = money_tuple[0]
check_money(money)
return cur, money, email
def main():
cur, money, email = db_conn()
keeps_playing = start()
if not keeps_playing:
display_top(cur)
while keeps_playing:
shoe = shuffled_shoe()
player = []
dealer = []
still_playing = True
player_plays = True
player_stands = False
money, money_bet = bet(money)
deal_hand(shoe, player, dealer)
still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
while still_playing:
while player_plays:
player_plays, player_stands = player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands)
still_playing = dealer_play(shoe, dealer, 17)
still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
update_db_money(cur, money, email)
keeps_playing = play_again(money)
cur.close()
if __name__ == '__main__':
main()
</code></pre>
<p>Database:</p>
<pre><code>SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) COLLATE utf8_bin NOT NULL,
`password` varchar(255) COLLATE utf8_bin NOT NULL,
`money` int(11) NOT NULL DEFAULT '1000',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T02:06:00.407",
"Id": "424167",
"Score": "0",
"body": "Can you link to the previous post?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T08:27:27.653",
"Id": "424195",
"Score": "0",
"body": "@l0b0 sure: https://codereview.stackexchange.com/questions/216409/blackjack-game-with-database-follow-up"
}
] | [
{
"body": "<p>This is a prime candidate for object orientation - you clearly have concepts like user, game, hand, shoe, dealer, etc. Each of these would keep track of their respective pieces of data — the <code>User</code> class would have a <code>money</code> field, for example.</p>\n\n<hr>\n\n<p>A method called <code>display_info</code> would not be <a href=\"https://en.wikipedia.org/wiki/Principle_of_least_astonishment\" rel=\"nofollow noreferrer\">expected</a> to return anything - it should simply receive some information and display it.</p>\n\n<hr>\n\n<p>I always suggest users to run their code through Black, flake8 and mypy with a setup.cfg something like this:</p>\n\n<pre><code>[flake8]\ndoctests = true\nexclude =\n .git,\n __pycache__\nmax-complexity = 4\nmax-line-length = 120\nignore = W503,E203\n\n[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre>\n\n<p>This will help making your code simple, readable and explicit (but will never guarantee it). Understanding and acting on all the information you'll get from these tools is super helpful to write idiomatic and clear Python code.</p>\n\n<hr>\n\n<p>This is an excellent example of code which could be <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">test driven</a>. TDD is probably the hardest thing I've ever learned, but it's an incredibly powerful way to achieve confidence in your code and to be sure that you can act on any future change requests without fear of breaking existing functionality (because if you do, your tests will catch it).</p>\n\n<hr>\n\n<p>Database interaction code should not be in the <code>main</code> method - typically that should only create the main object and set it going. Your connection parameters should be <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\">arguments</a> or configuration.</p>\n\n<hr>\n\n<p>You never call <code>deal_card</code> with any number other than 1. <a href=\"https://en.wikipedia.org/wiki/You_aren't_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> - just remove that parameter and deal one card.</p>\n\n<hr>\n\n<p>Single letter variables are terrible for readability. <code>c</code> is <code>score</code> should simply be <code>card</code>, for example.</p>\n\n<hr>\n\n<p>Rather than string matching on the various cards to get the score it looks like cards should be objects with a <code>score</code> field (or method if the score depends on external state). That way you could simply <code>return sum([card.score for card in cards])</code>.</p>\n\n<hr>\n\n<p>You should update the database <code>WHERE id = %s</code> rather than keying on the (non-unique!) email field. Also, you don't need to use backticks to quote fields unless they contain special characters such as spaces.</p>\n\n<hr>\n\n<p>You can use a <a href=\"https://docs.python.org/3/library/crypt.html#crypt.crypt\" rel=\"nofollow noreferrer\">built-in secure password hashing method</a> instead of an external package.</p>\n\n<hr>\n\n<p>A password hash will be <em>fixed size,</em> so you should store it in a column with the correct data type and length (some hashing functions return binary blobs rather than strings).</p>\n\n<p>For this reason you also shouldn't limit the password length to the size of the database field — it's unrelated to the length of the password. You may still want to limit the password length to something sane like 1,000 characters, though.</p>\n\n<hr>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/q/234657/13162\"><code>SELECT *</code> is discouraged in code</a> - it makes schema changes harder, wastes bandwidth, and is less explicit about what is needed.</p>\n\n<hr>\n\n<p>In general, input, output and persistence should be separate. If you rebuild this using TDD, making sure to <a href=\"https://stackoverflow.com/a/130862/96588\">dependency inject</a> the database and user input handler, this should follow naturally.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T11:15:23.790",
"Id": "424213",
"Score": "0",
"body": "Hello and thank you for your answer! I don't really know how to work with classes but I'll do my best in understanding them. I have a big problem in splitting display_info(), can you please tell me how can I simplify that function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T22:08:34.143",
"Id": "424298",
"Score": "0",
"body": "It is kinda hard to refactor without rebuilding from scratch. For example, `len(dealer)` makes no sense semantically - clearly `dealer` is not a dealer as such, but a list of something. Also, `score(player)` is weird - you calculate someone's score based on their *cards,* not on the *person.* I've added a paragraph at the end about handling this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T02:17:19.843",
"Id": "219616",
"ParentId": "219489",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219616",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T11:39:55.877",
"Id": "219489",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"sql",
"mysql",
"playing-cards"
],
"Title": "Lastest version of my Blackjack game"
} | 219489 |
<p>I am in my first high school programming course; the assignment is:</p>
<blockquote>
<p>Write a program that asks the user to input three integers and outputs
a message indicating their sum and whether it is positive, negative,
or zero. You should create 2 classes to run this program. One class
contains all of the procedures for your program and the other has all
of the procedure calls for your program.</p>
</blockquote>
<p>I have done exactly what the assignment has asked for me to do; I was wondering if there was anything that I should change to make my code more simple and or more elegant or point out anything that might lead up to errors, since I'm in my first programming course. I really want to start programming with simple elegant code and not messy code, because I feel like it starts good habits for me later on.</p>
<pre class="lang-java prettyprint-override"><code>
import java.util.Scanner;
class ConorsList {
int total;
public void add(int number) {
this.total = this.total + number ;
}
public void status(){
if(this.total<0) {
System.out.println("The sum is negative.");
} else if (this.total>0) {
System.out.println("The sum is positive");
} else {
System.out.println("The sum is equal to zero");
}
}
public void status(int total){
if(total<0) {
System.out.println("The number is negative.");
} else if (total>0) {
System.out.println("The number is positive.");
} else {
System.out.println("The number is equal to zero.");
}
}
}
public class Class1_2 {
public static void main(String args[]) {
ConorsList list = new ConorsList();
Scanner fromKeyboard = new Scanner(System.in);
int amount = 3;
for (int n=0; n<amount; n++) {
int x =fromKeyboard.nextInt();
list.add(x);
list.status();
list.status(x);
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:57:45.807",
"Id": "423983",
"Score": "2",
"body": "This is actually a rather challenging exercise if you need to take into account the possibility of integer overflow during addition. You're probably not expected to do so, though, if this is a first assignment in a high school course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:12:09.773",
"Id": "423985",
"Score": "0",
"body": "can you explain a little more indepth?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:22:25.273",
"Id": "423987",
"Score": "0",
"body": "An `int` can only go as large as 2147683487. If you add 2147383487 to 2147683487, the sum should be positive mathematically, but will be reported as -2 in Java because [the result would be too large to be represented as an `int`](https://en.wikipedia.org/wiki/Integer_overflow)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:23:45.320",
"Id": "423988",
"Score": "0",
"body": "okay cool, yeah like you said \"you're probably not expected to do so\" i think the assignment is just to do basic classes"
}
] | [
{
"body": "<p>Use shorthand for addition, multiplication, division etc.</p>\n\n<p>E.G instead of <code>this.total = this.total + number;</code></p>\n\n<p>do: <code>this.total += number;</code></p>\n\n<p>You have a lot of code repetition with these two methods. Anytime you copy & paste, you should be asking yourself if you can make the code shorter.</p>\n\n<p>With your overloaded method, it's easy. Just change your no-arg constructor to call the other:</p>\n\n<pre><code>public void status(){\n status(this.total);\n} \n</code></pre>\n\n<p>You may also want to change the name to <code>printStatus</code>. You can further reduce the code, since all of the if statements print a lot of the same characters </p>\n\n<p>E.G:</p>\n\n<pre><code>public void status(total){\n String status = \"The sum is \";\n\n if(total<0) {\n status += \"negative.\";\n } else if (total>0) {\n status += \"positive\";\n } else {\n status += \"equal to zero.\";\n }\n\n System.out.println(status);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:07:19.373",
"Id": "219494",
"ParentId": "219492",
"Score": "1"
}
},
{
"body": "<p><strong>Binary operators have spaces before and after them</strong></p>\n\n<p>In your <code>main</code>s <code>for</code> loop, you have:</p>\n\n<pre><code>int n=0;\n</code></pre>\n\n<p>It is more customary to write <code>int n = 0;</code></p>\n\n<p><strong>Superfluous new lines</strong></p>\n\n<p>Given</p>\n\n<p>public class ... { </p>\n\n<pre><code> public static void main(String args[]) {\n ConorsList list = new ConorsList();\n Scanner fromKeyboard = new Scanner(System.in);\n\n int amount = 3;\n\n for (int n=0; n<amount; n++) {\n int x =fromKeyboard.nextInt();\n list.add(x);\n list.status();\n list.status(x);\n }\n // Why new line here?\n }\n // And here?\n}\n</code></pre>\n\n<p><strong>Superfluous space in the <code>for</code> loop</strong></p>\n\n<p>In the <code>main</code>'s <code>for</code> loop, you have</p>\n\n<pre><code> for (int n=0; n<amount; n++) {\n int x =fromKeyboard.nextInt();\n list.add(x);\n list.status();\n list.status(x);\n }\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code> for (int n = 0; n < amount; n++) {\n int x = fromKeyboard.nextInt();\n list.add(x);\n list.status();\n list.status(x);\n }\n</code></pre>\n\n<p><strong>Bad name</strong></p>\n\n<p>I suggest you rename <code>fromKeyboard</code> to <code>scanner</code> here:</p>\n\n<pre><code>Scanner scanner = new Scanner(System.in);\n</code></pre>\n\n<p><strong>Superfluous variable</strong></p>\n\n<pre><code>int amount = 3;\n</code></pre>\n\n<p>Having this definition does not buy you much maintainability. I see two options here: </p>\n\n<ol>\n<li>Remove it and have <code>n < 3</code> in the <code>for</code> loop,</li>\n<li>Declare it <code>final</code>.</li>\n</ol>\n\n<p><strong>Bad class name</strong></p>\n\n<p><code>Class1_2</code> is a bad name for a class. Since it does nothing but runs you main logic, I suggest you rename it to <code>Main</code>, <code>Demo</code>, or similar.</p>\n\n<p><strong>Advice 1</strong></p>\n\n<p>When you reach a particular level of proficiency in Java, it is advisory to start using <strong><a href=\"https://www.w3schools.com/java/java_packages.asp\" rel=\"nofollow noreferrer\">packages.</a></strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:18:14.100",
"Id": "423978",
"Score": "0",
"body": "So i have a lot of unnecessary spaces between lines, and i can make my code less lines by getting rid of those.\n\nif i dont put spaces for the binary ops will that ever lead to an error or is it just it looks better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:23:21.893",
"Id": "423980",
"Score": "0",
"body": "No, it does not lead to errors, but it *may* lead to errors while reading the code. For example: `for(int i=0,j=-1;i>j&&ji+10;i+=2,j-=3)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:24:35.547",
"Id": "423981",
"Score": "0",
"body": "i see now, without the spaces its really hard to read without the spaces,\n\nthanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:26:34.050",
"Id": "423982",
"Score": "0",
"body": "@ConorOepkes No problem. Just remember that readability/maintainability is no less important than correctness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:53:36.063",
"Id": "424062",
"Score": "1",
"body": "Java is a strongly typed language, so there is no need to repeat the type of the variable in it's name. Especially if the type is the only thing in the name. The name \"fromKeyboard\" was in that sense more descriptive than \"scanner\". However, as System.in doesn't always come from keyboard, your name can be a bit deceptive. Names should describe what the variables do. E.g. \"amount\" should be \"numOfEntriesToRead\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:06:29.687",
"Id": "424064",
"Score": "0",
"body": "Amount should not be replaced with 3 in the for loop. Doing so would trigger a warning for magic numbers in a static code analyzer. The number 3 should be extracted into a constant with a name that describes what it stands for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:09:09.310",
"Id": "424065",
"Score": "0",
"body": "\"Class1_2\", while it doesn't follow Java naming conventionas, is a lot more descriptuive than \"Main\" or \"Demo\". It identifies the class and assignment for which it was written and thus describes it's exact purpose. When the naming convention is followed throughout the class, finding specific code is simple. \"Class1Assignment2\" would have been better, though, as undserscores do not belong to Java class names. The ConorsList was the actual bad class name as it is neither Conor nor a List. It is an Accumulator."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T13:13:29.677",
"Id": "219496",
"ParentId": "219492",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219496",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T12:41:42.800",
"Id": "219492",
"Score": "3",
"Tags": [
"java",
"beginner",
"object-oriented",
"homework"
],
"Title": "Add three integers and report the sign of the sum"
} | 219492 |
<blockquote>
<p>Given an array nums of n integers where n > 1, return an array output
such that output[i] is equal to the product of all the elements of
nums except nums[i].</p>
</blockquote>
<p><strong>Example:</strong></p>
<pre><code>Input: [1,2,3,4]
Output: [24,12,8,6]
Note: Please solve it without division and in O(n).
</code></pre>
<blockquote>
<p>Follow up: Could you solve it with constant space complexity? (The
output array does not count as extra space for the purpose of space
complexity analysis.)</p>
</blockquote>
<p>My solution</p>
<pre><code>public class ProductExceptSelf {
/**
* Approach 1:- Find the left[i] at i containing all the left multiplication. Do same with right[i]
*/
public int[] productExceptSelf(int[] nums) {
int size = nums.length;
int[] output = new int[size];
int[] left = new int[size];
int[] right = new int[size];
int temp = 1;
// Start filling up left array
for (int i = 0; i < size; i++) {
left[i] = temp;
temp = temp * nums[i];
}
// Again set the temp to 1
temp = 1;
// Start filling up right array
for (int i = size - 1; i >= 0; i--) {
right[i] = temp;
temp = temp * nums[i];
}
// Final traversal and return sum array.
for (int i = 0; i < size; i++) {
output[i] = left[i] * right[i];
}
return output;
}
}
</code></pre>
<p>Please help me to improve Auxilary space, code readibility and any best practice if I am missing.</p>
| [] | [
{
"body": "<p>Every time you feel obliged to put a comment like</p>\n\n<pre><code> // Start filling up left array\n</code></pre>\n\n<p>you really deal with a potentially important algorithm, which deserves a name, and a method of its own. In this case the algorithm is known as <em>partial product</em>. Consider factoring it out, and see the comments disappear.</p>\n\n<p>Ditto for the second loop.</p>\n\n<p>Regarding space complexity,</p>\n\n<ul>\n<li><p>You don't need <code>left</code>: accumulate the partial products directly into <code>output</code>.</p></li>\n<li><p>You don't need <code>right</code> as well: instead of accumulating the partial products, use it immediately:</p>\n\n<pre><code> temp = 1;\n\n for (int i = size - 1; i >= 0; i--) {\n output[i] *= temp;\n temp = temp * nums[i];\n }\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:40:22.043",
"Id": "219510",
"ParentId": "219499",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:05:54.610",
"Id": "219499",
"Score": "2",
"Tags": [
"java",
"array",
"interview-questions"
],
"Title": "Leetcode - product of array except self"
} | 219499 |
<p>I made the login flow without any reference to a tutorial. So I want some feedback.</p>
<p>Basically it sends username and password in a POST request to /token. The app stores the tokens on device, then uses the auth token to request customer profile data.</p>
<p><strong>LoginPageViewModel</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class LoginPageViewModel
{
public LoginPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator, IRepository repository, IProperties properties, ITokenService tokenService, ICustomerService customerService, ISubscriptionService subscriptionService, ITicketService ticketService, ITranslationService translation, IUserDialogs dialogs, IConfiguration configuration, IConnectivity connectivity)
{
_navigation = navigationService;
_eventAggregator = eventAggregator;
_repository = repository;
_properties = properties;
_tokenService = tokenService;
_customerService = customerService;
_translation = translation;
_dialogs = dialogs;
eventAggregator.GetEvent<LoggedInEvent>().Subscribe(async () => await LoggedInEventHandler());
}
private readonly INavigationService _navigation;
private readonly IEventAggregator _eventAggregator;
private readonly IRepository _repository;
private readonly IProperties _properties;
private readonly ITokenService _tokenService;
private readonly ICustomerService _customerService;
private readonly ITranslationService _translation;
private readonly IUserDialogs _dialogs;
public string Username { get; set; }
public string Password { get; set; }
public ICommand LoginCommand => new Command(async () => await Login());
private async Task LoggedInEventHandler()
{
if (_navigation.GetCurrentPageName() == "LoginPage")
{
await _navigation.NavigateAsync("/MainMasterDetailPage/NavigationPage/ContentPage");
}
}
private async Task Login()
{
if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
{
return;
}
_eventAggregator.GetEvent<LoggingInEvent>().Publish();
TokenData getTokenResponse;
try
{
getTokenResponse = await _tokenService.GetTokens(Username, Password);
}
catch (BadRequestException)
{
_dialogs.Alert(_translation.GetString("ProfilePageInvalidUsernameOrPassword"));
_eventAggregator.GetEvent<LoginFailedEvent>().Publish();
return;
}
catch (Exception ex)
{
_dialogs.Alert(_translation.GetString("ProfilePageOtherFault"));
Crashes.TrackError(ex, new Dictionary<string, string>
{
{ "Event", "LoginAndGetTokens" },
{ "Subject", Username },
{ "Message", ex.Message },
});
_eventAggregator.GetEvent<LoginFailedEvent>().Publish();
return;
}
_properties.AccessToken = getTokenResponse.AccessToken;
_properties.AccessTokenExpires = DateTime.UtcNow.AddSeconds(getTokenResponse.ExpiresIn);
_properties.RefreshToken = getTokenResponse.RefreshToken;
try
{
var getCustomerResponse = await _customerService.GetCustomer(_properties.AccessToken);
_repository.Customer = getCustomerResponse.Customer;
_eventAggregator.GetEvent<CustomerRetrievedEvent>().Publish(getCustomerResponse.Customer);
_eventAggregator.GetEvent<LoggedInEvent>().Publish();
}
catch (Exception ex)
{
_dialogs.Alert(_translation.GetString("ProfilePageOtherFault"));
Crashes.TrackError(ex, new Dictionary<string, string>
{
{ "Event", "GetCustomerAfterLogin" },
{ "Subject", Username },
{ "Message", ex.Message }
});
_eventAggregator.GetEvent<LoginFailedEvent>().Publish();
}
}
}
</code></pre>
<p><strong>TokenService</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class TokenService : ITokenService
{
public TokenService(IRequestService requestService)
{
_requestService = requestService;
}
private readonly IRequestService _requestService;
public Task<TokenData> GetTokens(string loginName, string password)
{
var getTokenRequest = new RestRequest("token", Method.POST);
getTokenRequest.AddParameter("client_id", "XamarinApp", ParameterType.GetOrPost);
getTokenRequest.AddParameter("grant_type", "password", ParameterType.GetOrPost);
getTokenRequest.AddParameter("username", loginName, ParameterType.GetOrPost);
getTokenRequest.AddParameter("password", password, ParameterType.GetOrPost);
return _requestService.DoRequest<TokenData>(getTokenRequest);
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>public class TokenData
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public long ExpiresIn { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("as:client_id")]
public string ClientId { get; set; }
[JsonProperty("userName")]
public string UserName { get; set; }
}
</code></pre>
<p><strong>RequestService</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class RequestService : IRequestService
{
private readonly IConnectivity _connectivity;
private readonly IRestClient _restClient;
public RequestService(IConnectivity connectivity, IRestClient restClient)
{
_connectivity = connectivity;
_restClient = restClient;
}
public async Task<TResult> DoRequest<TResult>(IRestRequest request)
{
if (!_connectivity.IsConnected)
{
throw new NoConnectionException();
}
var response = await _restClient.ExecuteTaskAsync<TResult>(request);
if (response.StatusCode != HttpStatusCode.OK)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
throw new UnauthorizedException(response.Content);
}
else if (response.StatusCode == HttpStatusCode.BadRequest)
{
throw new BadRequestException(response.Content);
}
else if (response.StatusCode == HttpStatusCode.NotFound)
{
throw new NotFoundException(response.Content);
}
else
{
throw new HttpRequestException(response.Content);
}
}
return response.Data;
}
}
</code></pre>
<p>Example response when POST to /token</p>
<pre><code>{
"access_token": "-UHguElQMme12_aIQ305C5pFBwV1X-qAyT1rO2quJcqXIjOCwd73kAwAVCiyfIsThoWa8LPgVmTOyBWG0rBa_5GsaAt8w-O2njL8SNBEJQma47IlGsL53jGJzAVfy2xk37GJLdmkvYOQRZF3u_ejOEx0XhYUNxg-Ph2IjV5EMgTWXrUjoUbiw8V7feonH1QpDFjgN7sZrDcKsLqzG0900yUVaqliCwPmSe6pcfa7ybEHyBG8KC7rihWqNcwMOx9yfwbDVAVY0ZzOJaNT0k0G1sRu0t4KHKr28I7EW_R-zCQVHVCq5uimYcL1VDJRzbNRz83GUddXT6OmQfW5PjTmUYqAPMl3JcyBkv5ko4R0kHB9v0Yp_Sb-4oJasOraF6c3wdqpXJAUTxIHGZy6WIeXJRwr1ZuFmngx_eiUafPsKxEcTTyvPmgPkV36FHam9FBl",
"token_type": "bearer",
"expires_in": 86399,
"refresh_token": "210a2106fd564aee9a75daeb73458fa2",
"as:client_id": "XamarinApp",
"userName": "someone@example.com",
".issued": "Wed, 01 May 2019 10:10:06 GMT",
".expires": "Thu, 02 May 2019 10:10:06 GMT"
}
</code></pre>
<p>The Web API was setup according to <em><a href="http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/" rel="nofollow noreferrer">Token Based Authentication using ASP.NET Web API 2, Owin, and Identity</a></em>.</p>
| [] | [
{
"body": "<p>Simplify your RequestService by inverting the if-statement in DoRequest():</p>\n\n<pre><code>public async Task<TResult> DoRequest<TResult>(IRestRequest request)\n{\n if (!_connectivity.IsConnected)\n {\n throw new NoConnectionException();\n }\n\n var response = await _restClient.ExecuteTaskAsync<TResult>(request);\n\n // If Ok, return ...\n if (response.StatusCode == HttpStatusCode.OK)\n {\n return response.Data;\n }\n\n // ... so this block is not nested\n if (response.StatusCode == HttpStatusCode.Unauthorized)\n {\n throw new UnauthorizedException(response.Content);\n }\n else if (response.StatusCode == HttpStatusCode.BadRequest)\n {\n throw new BadRequestException(response.Content);\n }\n else if (response.StatusCode == HttpStatusCode.NotFound)\n {\n throw new NotFoundException(response.Content);\n }\n else\n {\n throw new HttpRequestException(response.Content);\n }\n}\n</code></pre>\n\n<p>Since you always compare the status code, make sure to use a switch statement. This results in much shorter and more readable code.</p>\n\n<pre><code>public async Task<TResult> DoRequest<TResult>(IRestRequest request)\n{\n if (!_connectivity.IsConnected)\n {\n throw new NoConnectionException();\n }\n\n var response = await _restClient.ExecuteTaskAsync<TResult>(request);\n\n switch (response.StatusCode)\n {\n case HttpStatusCode.OK:\n return response.Data;\n case HttpStatusCode.Unauthorized:\n throw new UnauthorizedException(response.Content);\n case HttpStatusCode.BadRequest:\n throw new BadRequestException(response.Content);\n case HttpStatusCode.NotFound:\n throw new NotFoundException(response.Content);\n default:\n throw new HttpRequestException(response.Content);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T11:45:08.657",
"Id": "219580",
"ParentId": "219500",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219580",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:28:01.880",
"Id": "219500",
"Score": "1",
"Tags": [
"c#",
"authentication",
"asp.net-web-api",
"xamarin"
],
"Title": "Login flow in app"
} | 219500 |
<p>I got a long string, let's call it <code>Story</code>.
I fetch this story from a database so I don't know how long it is.</p>
<p>I want to display this story in a view, but what if the story is too long so it doesn't fit in one view?</p>
<p>I don't want to adjust the font size because it may be a very long story and making the font size smaller is not a good solution.</p>
<p>Therefore I want to split the Story into more than one view.
By passing the story and getting a separated story as an <code>array of String</code> every item in the array can fit in one view.</p>
<p>This is the code, it hopefully gives you a hint what I'm trying to achieve exactly:</p>
<pre><code>extension String {
/// - returns: The height that will fit Self
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.height)
}
#warning("it's so slow that i can't handle it in main thread , ( 21 second for 15 items in array )")
/// complition contains the separated string as array of string
func splitToFitSize(_ size : CGSize = UIScreen.main.bounds.size ,font : UIFont = UIFont.systemFont(ofSize: 17) , complition : @escaping (([String]) -> Void) ) {
DispatchQueue.global(qos: .background).async {
// contents contains all the words as Array of String
var contents = self.components(separatedBy: .whitespaces)
var values : [String] = []
for content in contents {
// if one word can't fit the size -> remove it , which it's not good, but i don't know what to do with it
guard content.isContentFit(size: size , font : font) else {contents.removeFirst(); continue;}
if values.count > 0 {
for (i , value) in values.enumerated() {
var newValue = value
newValue += " \(content)"
if newValue.isContentFit(size: size, font: font) {
values[i] = newValue
contents.removeFirst()
break;
}else if i == values.count - 1 {
values.append(content)
contents.removeFirst()
break;
}
}
}else {
values.append(content)
contents.removeFirst()
}
}
complition(values)
}
}
/// - returns: if Self can fit the passing size
private func isContentFit(size : CGSize, font : UIFont) -> Bool{
return self.height(withConstrainedWidth: size.width, font: font) < size.height
}
}
</code></pre>
<p>This code is working, but it takes very long.
If I want to split a story to 15 views it takes 20 seconds or even longer.</p>
<p>How can I optimize this so it runs faster?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:36:19.670",
"Id": "424009",
"Score": "0",
"body": "Just curious, but why can't you get the size of Story by using self.count and then dividing that by the maximum size of the view, then divide the story into the result of the number of views."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:48:16.483",
"Id": "424010",
"Score": "0",
"body": "@pacmaninbw great idea but i want to fill every view with the content , Explanation: if the story can fit in two views first view , will fill it and the second view just one line that will not work out because if i want to divide that , all views will have the same amount of content , and the first view will not be filled , i hope i explain that well , thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T05:21:28.267",
"Id": "424314",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T17:14:09.760",
"Id": "424360",
"Score": "0",
"body": "@MartinR sorry , but how can i share my improvement? , maybe my improvement can help someone"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T17:16:09.027",
"Id": "424362",
"Score": "0",
"body": "@mazen: The possible options are listed in the above-linked answer (e.g. posting a self-answer)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T17:26:24.527",
"Id": "424366",
"Score": "0",
"body": "okay thank you @MartinR , i will answer my own question when i feel that my code is good enough to be a good answer"
}
] | [
{
"body": "<h1>General remarks</h1>\n\n<p>Here are some general remarks that could make your code look a little cleaner :</p>\n\n<ul>\n<li>Avoid using <code>;</code> at the end of an instruction unless you have to put multiple instructions in the same line.</li>\n<li>Document the functions properly: The description of the <code>complition</code> parameter of <code>splitToFitSize</code> isn't well formatted.</li>\n<li>The correct spelling of <code>complition</code> is <code>completion</code>.</li>\n<li>This is subjective and probably nitpicky: Put a space only where needed, one after the closing curly brace of a scope: <code>} else</code>, and none before a punctuation sign: <code>(size: size, font: font)</code>.</li>\n</ul>\n\n<h1>Catching the culprits</h1>\n\n<p><a href=\"https://i.stack.imgur.com/BlSMr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BlSMr.jpg\" alt=\"Dalton Cousins\"></a></p>\n\n<p>Sources of slow code:</p>\n\n<ul>\n<li><code>\" \\(content)\"</code>: String interpolation is slow as previously stated <a href=\"https://codereview.stackexchange.com/a/213879/49921\">here</a>.</li>\n<li><code>self.components(separatedBy: .whitespaces)</code>: This has both a time and space <a href=\"https://developer.apple.com/documentation/foundation/nsstring/1413214-components\" rel=\"nofollow noreferrer\">complexity</a> of O(<em>n</em>). Better iterate over the <em>story</em> with a <code>String.Index</code>.</li>\n<li><code>DispatchQueue.global(qos: .background)</code> : This is the <a href=\"https://developer.apple.com/documentation/dispatch/dispatchqos/qosclass/background\" rel=\"nofollow noreferrer\">lowest priority</a> you could give to code and it wastes time by switching from the main thread to a background one, and back.</li>\n<li><p><code>contents.removeFirst()</code>: This is called in multiple places and repeatedly. Each call is O(<em>n</em>) since all the elements of the <code>contents</code> array shifted (Have a look <a href=\"https://developer.apple.com/documentation/swift/array/2886730-removefirst\" rel=\"nofollow noreferrer\">here</a>). This means that this algotithm shifts the elements of the <code>contents</code> array n + (n-1) + (n-2) + ... + 1 times. Knowing that :\n<span class=\"math-container\">$$n + (n-1) + (n-2) + ... + 1 = \\frac{n(n+1)}{2}$$</span></p>\n\n<p>it makes this algorithm O(<em>n<sup>2</sup></em>), with <em>n</em> being the number of elements in <code>contents</code>. To circumvent this use an index that traverses the array.</p></li>\n</ul>\n\n<hr>\n\n<h2>Alternative implementation</h2>\n\n<p>Here is an alternative solution to split a string into a given size using a certain font :</p>\n\n<pre><code>extension String {\n\n static let blanks: [Character] = [\" \", \"\\n\", \"\\t\"]\n\n func splitToFit (size: CGSize, using font: UIFont) -> [String] {\n var output: [String] = []\n var (fitted, remaining) = fit(self, in: size, using: font)\n var lastCount = fitted.count\n output.append(fitted)\n\n while remaining != \"\" {\n (fitted, remaining) = fit(remaining,\n in: size,\n using: font,\n lastCount: lastCount)\n lastCount = fitted.count\n output.append(fitted)\n }\n\n //Trim white spaces if needed\n //return output.map { $0.trimmingCharacters(in: .whitespacesAndNewlines)}\n return output\n }\n\n private func fit(\n _ str: String,\n in size: CGSize,\n using font: UIFont,\n lastCount: Int = 0) -> (String, String) {\n\n if !str.isTruncated(in: size, using: font) {\n return (str, \"\")\n }\n\n var low = 0\n var high = str.count - 1\n let lastValidIndex = high\n var substr = \"\"\n let step = lastCount/10 //Could be adjusted\n\n\n if lastCount != 0 {\n high = min(lastCount, lastValidIndex)\n while !str[0..<high].isTruncated(in: size, using: font) {\n low = high\n high = min(high + step, lastValidIndex)\n }\n }\n\n while low < high - 1 {\n let mid = low + (high - low)/2 \n //Or more efficiently \n //let mid = Int((UInt(low) + UInt(high)) >> 1)\n //Have a look here https://ai.googleblog.com/2006/06/extra-extra-read-all-about-it-nearly.html\n\n substr = str[0..<mid]\n\n let substrTruncated = substr.isTruncated(in: size, using: font)\n\n if substrTruncated {\n high = mid\n } else {\n low = mid\n }\n }\n\n substr = str[0..<low]\n\n while !String.blanks.contains(substr.last!) {\n substr.removeLast()\n low -= 1\n }\n\n let remains = str[low..<str.count]\n return (substr, remains)\n }\n}\n</code></pre>\n\n<p>It calls these other extensions :</p>\n\n<pre><code>extension String {\n func isTruncated(in size: CGSize, using font: UIFont) -> Bool {\n let textSize = (self as NSString)\n .boundingRect(with: CGSize(width: size.width,\n height: .greatestFiniteMagnitude),\n options: .usesLineFragmentOrigin,\n attributes: [.font: font],\n context: nil).size\n\n return ceil(textSize.height) > size.height\n }\n\n subscript (range: Range<Int>) -> String {\n let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)\n let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)\n let range = startIndex..<endIndex\n\n return String(self[range])\n }\n}\n</code></pre>\n\n<p>This code is inspired by this <a href=\"https://github.com/nishanthooda/FitMyLabel/blob/master/FitMyLabel/FitMyLabel.swift\" rel=\"nofollow noreferrer\">library</a> but <strong>twice</strong> as fast . Further improvements are possible.</p>\n\n<p>It was tested using the following code:</p>\n\n<pre><code>class ViewController: UIViewController, UIScrollViewDelegate {\n\n var scrollView: UIScrollView! {\n didSet{\n scrollView.delegate = self\n }\n }\n\n private let font = UIFont.systemFont(ofSize: 17)\n\n override func viewDidLoad() {\n super.viewDidLoad()\n\n let width = view.frame.width\n let height = view.frame.height\n let labelSize = CGSize(width: width - 40.0, height: height - 60.0)\n //Split the story here\n //let start = Date()\n let strings = story.splitToFit(size: labelSize, using: font)\n //let end = Date()\n //print(\"time =\", end.timeIntervalSince(start))\n\n let scrollViewFrame = CGRect(x: 0,\n y: 0,\n width: width,\n height: height)\n\n scrollView = UIScrollView(frame: scrollViewFrame)\n scrollView.contentSize = CGSize(width: width * CGFloat(strings.count), height: height)\n scrollView.isPagingEnabled = true\n\n let colors: [UIColor] = [.red, .green, .blue]\n\n for i in 0 ..< strings.count {\n let label = UILabel()\n label.numberOfLines = 0\n label.frame = CGRect(origin: CGPoint(x: width * CGFloat(i) + 20.0,\n y: 40.0),\n size: labelSize)\n label.backgroundColor = colors[i % 3]\n label.font = font\n label.text = strings[i]\n label.translatesAutoresizingMaskIntoConstraints = false\n scrollView.addSubview(label)\n }\n\n view.addSubview(scrollView)\n }\n}\n</code></pre>\n\n<p>with <code>story</code> being a 10-paragraph string, 1104 total words, 7402 total characters, generated on <a href=\"http://lorem-ipsum.perbang.dk/\" rel=\"nofollow noreferrer\">this website</a>, it takes <strong>54ms</strong> on my local machine to split the story.</p>\n\n<p>If the story is too long, and to avoid blocking the main thread I would recommend adding subviews asynchronously to the <code>UIScrollView</code> as the <code>fitted</code> strings are calculated one by one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T17:23:16.203",
"Id": "424254",
"Score": "0",
"body": "thank you so much , i'm really bad at this , but i use `DispatchQueue.global(qos: .background)` because if i don't the main thread will freeze as long as the algorithm execute, and yeah i'm bad in English to , Sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T17:36:53.137",
"Id": "424263",
"Score": "0",
"body": "@mazen Don't put yourself down, we're all here to learn from each other. Did [this](https://github.com/nishanthooda/FitMyLabel) work for you? It could be improved even further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T00:49:43.903",
"Id": "424306",
"Score": "0",
"body": "first thanks for your support , And no https://github.com/nishanthooda/FitMyLabel force you to use label and have a lot of issues and bugs , But he give me an idea for doing it , i update my question with my last improvements and maybe i will add binary search somehow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-05T09:36:38.720",
"Id": "424413",
"Score": "0",
"body": "@mazen I've added an alternative implementation"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T16:47:17.147",
"Id": "219655",
"ParentId": "219501",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "219655",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T14:35:23.327",
"Id": "219501",
"Score": "3",
"Tags": [
"performance",
"strings",
"swift",
"ios",
"layout"
],
"Title": "Splitting a long string based on its graphical presentation"
} | 219501 |
<p>I've created the following module to allow me to generate a SHA256 signature for a file. (In real life this is used to verify an image file hasn't been amended). The cut down code looks like this:</p>
<pre><code>open System.IO
open System.Text
open System.Security.Cryptography;
// Get the SHA256 hash of a file
let SHA256 (file:FileInfo) =
let FileSHA256Wrap (hashFile : FileStream) (sha256Hash : SHA256) : byte[] =
sha256Hash.ComputeHash(hashFile)
let FileWrap (hashFile : FileStream) : byte[] =
using (SHA256Managed.Create()) (FileSHA256Wrap hashFile)
using (file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) FileWrap
// Convert the byte[] version of the hash to a printable encoded HEX string
let HexEncoded (hash:byte[]) :string =
let sb = new StringBuilder(hash.Length * 2)
hash |> Array.map (fun c -> sb.AppendFormat("{0:X2}",c)) |> ignore
sb.ToString()
// Get the file hash and convert it to a HEX string
let HexEncodedSHA256 (file:FileInfo) =
file |> SHA256 |> HexEncoded
let fi = new FileInfo("somefile.tif")
HexEncodedSHA256 fi
</code></pre>
<p>I've two questions here, with the double <code>using</code> statements I find the wrap functions help me work out what is going on - but is there a neater and more succinct way to write this without making it hard to work out what is happening?</p>
<p>The implementation of HexEncoded uses a string builder, is there a more <em>functional</em> way to do this.</p>
| [] | [
{
"body": "<p>The <code>use</code> binding is usually better than the <code>using</code> function. The object is disposed when leaving the scope of the <code>use</code> binding (when leaving the <code>SHA256</code> function).</p>\n\n<pre><code>let SHA256 (file:FileInfo) =\n use hashFile = file.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n use sha256Hash = SHA256Managed.Create()\n sha256Hash.ComputeHash(hashFile)\n</code></pre>\n\n<p>You can avoid the use of a string builder by using <code>String.concat</code>. You can also use the F# <code>sprintf</code> function, which has slightly different format specifier syntax.</p>\n\n<pre><code>let HexEncoded (hash:byte[]) :string =\n hash\n |> Array.map (sprintf \"%02X\")\n |> String.concat \"\"\n</code></pre>\n\n<p>This might be slightly slower than your string builder because it requires an intermediate array. (Note that your implementation could remove the intermediate array by using <code>Array.iter</code> instead of <code>Array.map</code> and moving the <code>ignore</code> to inside the lambda.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:59:36.713",
"Id": "424108",
"Score": "0",
"body": "The use binding is clearer, I was sort of trying to re-invent it with my wrap functions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:05:38.403",
"Id": "219508",
"ParentId": "219505",
"Score": "4"
}
},
{
"body": "<p>I can only agree with TheQuickBrownFox.</p>\n\n<p>You can make even more dedicated functions and then compose them like:</p>\n\n<pre><code>let computeHash (dataStream: Stream) (hasher: HashAlgorithm) = hasher.ComputeHash(dataStream)\nlet openFile (fileInfo: FileInfo) = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n\nlet getHash algorithmFactory fileInfo = \n use hasher = algorithmFactory()\n use stream = openFile fileInfo\n computeHash stream hasher\n\nlet hexEncode hash = String.Join (\"\", hash |> Array.map (sprintf \"%02X\"))\n\nlet fromAlgorithm algorithmFactory fileInfo = fileInfo |> getHash algorithmFactory |> hexEncode\n\nlet fromSHA256 = fromAlgorithm SHA256Managed.Create\nlet fromSHA512 = fromAlgorithm SHA512Managed.Create\nlet fromMD5 = fromAlgorithm MD5.Create\n</code></pre>\n\n<p>As shown, in this way it's easy to change the hash algorithm.</p>\n\n<pre><code>let test () =\n let fi = new FileInfo(fileName)\n printfn \"%A\" (fromSHA256 fi)\n printfn \"%A\" (fromSHA512 fi)\n printfn \"%A\" (fromMD5 fi)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T13:57:13.100",
"Id": "424113",
"Score": "1",
"body": "Note that F#'s `String.concat` calls .NET's `String.Join`, so you can use `String.concat` and maintain the pipeline style like in my answer, without changing behaviour or performance "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T14:23:24.790",
"Id": "424116",
"Score": "0",
"body": "@TheQuickBrownFox: OK, thanks. I just thought I had to do something different than you :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:57:28.010",
"Id": "219525",
"ParentId": "219505",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219508",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T15:01:51.293",
"Id": "219505",
"Score": "4",
"Tags": [
"file",
"cryptography",
"f#",
"wrapper",
"hashcode"
],
"Title": "F# wrapper to generate SHA256 signature for a file"
} | 219505 |
<p>I have employed an AES algorithm in order to encrypt files within a GUI. I was wondering if my algorithm is secure. Could I change anything to improve it? Is my IV secure and is it producing different random numbers each time? Am I transferring the salt successfully? </p>
<p>I know that I could improve this by making separate classes for the different methods however I am just doing this within the main for now. I'm quite new to cryptography so any feedback would be greatly appreciated!
// author @Alex Matheakis
public class AESFileEncryption {</p>
<pre><code>// password to encrypt the file - how long should password be?
private static final String password = "UxIpOqSdNmSTuxZaShPu";
public static void main(String args[]) throws Exception {
// file to be encrypted
FileInputStream inF = new FileInputStream(GUI.AESinFile); // 'AESinFile' is a JFileChooser method from my GUI class
// encrypted file
FileOutputStream outF = new FileOutputStream("encrypted_file.des");
// generate and write the salt
SecureRandom sr = new SecureRandom();
byte[] salt = new byte[16];
sr.nextBytes(salt);
outF.write(salt);
// generate key
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); // salt, iteration count, key strength
SecretKey tmp = skf.generateSecret(keySpec);
SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); // returns key
// initialise the cipher with secure padding
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
AlgorithmParameters p = cipher.getParameters();
// iv used when initializing the cipher to make text more random
byte[] iv = p.getParameterSpec(IvParameterSpec.class).getIV();
outF.write(iv);
// file encryption
byte[] input = new byte[64];
int bytesRead;
while ((bytesRead = inF.read(input)) != -1) {
byte[] output = cipher.update(input, 0, bytesRead);
if (output != null)
outF.write(output);
}
byte[] output = cipher.doFinal();
if (output != null)
outF.write(output);
System.out.println("file encrypted");
inF.close();
outF.flush();
outF.close();
// inputScanner.close();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-06T23:38:37.420",
"Id": "424669",
"Score": "0",
"body": "@adot710 I rolled back that edit since it looked like a mistake, maybe try again if it was formatting related."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T15:23:42.270",
"Id": "426321",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>Line 105 is a typo. The indentation suggests its only executed if output is not null. </p>\n\n<p>But it's actually unrelated to the if statement. </p>\n\n<p>You should always use curly braces even if execution is only 1 line long. This goes for all statements: while, if, do, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T11:39:51.293",
"Id": "424100",
"Score": "0",
"body": "Good spot didn't see that thanks, does the rest of my code seem okay?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T18:37:47.533",
"Id": "219518",
"ParentId": "219511",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T16:41:10.170",
"Id": "219511",
"Score": "0",
"Tags": [
"java",
"algorithm",
"security",
"cryptography",
"aes"
],
"Title": "employing AES algorithm in Java"
} | 219511 |
<p>I implemented my own spin on the Atbash cipher in Ruby:</p>
<hr>
<pre class="lang-rb prettyprint-override"><code># frozen_string_literal: true
module Cryptorb
# The Atbash cipher
module Atbash
module_function
# Encrypts a string
#
# @param plaintext [String] the message that will be encrypted
#
# @return [String] the encrypted message
def encrypt(plaintext:)
atbash(plaintext)
end
# Decrypts an encrypted string
#
# @param ciphertext [String] the encrypted message that will be decrypted
#
# @return [String] the decrypted message
def decrypt(ciphertext:)
atbash(ciphertext)
end
# The algorithm
def atbash(string)
cap_a, cap_z = 65, 90
a, z = 97, 122
ciphertext = string.chars.map do |char|
limits = [cap_a, cap_z] if char.ord.between?(cap_a, cap_z)
limits = [a, z] if char.ord.between?(a, z)
limits ? (limits.last - (char.ord - limits.first)).chr : char
end
ciphertext.join
end
private_class_method :atbash
end
end
</code></pre>
<hr>
<p>White-space and numbers should not be modified. Character case should remain the same.</p>
<p><strong>For example:</strong> </p>
<ul>
<li><code>"1"</code> should map to <code>"1"</code></li>
<li><code>"."</code> should map to <code>"."</code></li>
<li><code>"B"</code> should map to <code>"Y"</code></li>
<li><code>"b"</code> should map to <code>"y"</code></li>
</ul>
<p><strong>Note:</strong> This implementation does not follow the "official" mathematical function of the Atbash cipher (<code>E(x) = (-x mod m) + 1</code>). Do you think it would be better if it did?</p>
<p><a href="https://repl.it/repls/RecentMonstrousOffice" rel="nofollow noreferrer">Here's</a> a REPL if you want to test it online.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:01:56.167",
"Id": "219513",
"Score": "3",
"Tags": [
"algorithm",
"ruby",
"cryptography"
],
"Title": "Atbash cipher in Ruby"
} | 219513 |
<p>I've been able to reduce my solution to constant time. Is it possible to reduce this by any constant factor further? (Besides trivialities i.e. inserting constants, not lazy importing). Specifically, I'd like to speed up <code>fastMinPayout</code> if there is a way to do it without using log.</p>
<blockquote>
<p>Lovely Lucky LAMBs</p>
<p>Being a henchman isn't all drudgery. Occasionally, when Commander Lambda is feeling generous, she'll hand out Lucky LAMBs
(Lambda's All-purpose Money Bucks). Henchmen can use Lucky LAMBs to
buy things like a second pair of socks, a pillow for their bunks, or
even a third daily meal! However, actually passing out LAMBs isn't
easy. Each henchman squad has a strict seniority ranking which must be
respected - or else the henchmen will revolt and you'll all get
demoted back to minions again! </p>
<p>There are 4 key rules which you must follow in order to avoid a
revolt:</p>
<ol>
<li>The most junior henchman (with the least seniority) gets exactly 1 LAMB. (There will always be at least 1 henchman on a team.)</li>
<li>A henchman will revolt if the person who ranks immediately above them gets more than double the number of LAMBs they do.</li>
<li>A henchman will revolt if the amount of LAMBs given to their next two subordinates combined is more than the number of LAMBs they get.
(Note that the two most junior henchmen won't have two subordinates,
so this rule doesn't apply to them. The 2nd most junior henchman
would require at least as many LAMBs as the most junior henchman.)</li>
<li>You can always find more henchmen to pay - the Commander has plenty of employees. If there are enough LAMBs left over such that
another henchman could be added as the most senior while obeying the
other rules, you must always add and pay that henchman.</li>
</ol>
<p>Note that you may not be able to hand out all the LAMBs. A single LAMB
cannot be subdivided. That is, all henchmen must get a positive
integer number of LAMBs.</p>
<p>Write a function called answer(total_lambs), where total_lambs is the
integer number of LAMBs in the handout you are trying to divide. It
should return an integer which represents the difference between the
minimum and maximum number of henchmen who can share the LAMBs (that
is, being as generous as possible to those you pay and as stingy as
possible, respectively) while still obeying all of the above rules to
avoid a revolt.</p>
<p>For instance, if you had 10 LAMBs and were as generous as possible,
you could only pay 3 henchmen (1, 2, and 4 LAMBs, in order of
ascending seniority), whereas if you were as stingy as possible, you
could pay 4 henchmen (1, 1, 2, and 3 LAMBs). Therefore, answer(10)
should return 4-3 = 1</p>
<p>To keep things interesting, Commander Lambda varies the sizes of the
Lucky LAMB payouts: you can expect total_lambs to always be between 10
and 1 billion (10 ^ 9).</p>
</blockquote>
<pre class="lang-py prettyprint-override"><code>
''' Recursive form
Rules:
1) A0 = 1
2) An+1 !> 2*An
3) An-1 + An-2 !> An
4) n -> inf
Rewritten:
1) A0 = 1
2) An <= 2*An-1
3) An >= An-1 + An-2
4) n -> inf
Therefore:
A0 = 1, A-1 = 0, A-2 = 0
An-1 + An-2 <= An <= 2*An-1
'''
def maxPayout(LAMBs):
'''
Given An-1 + An-2 <= An <= 2*An-1
An is maximized when An = 2*An-1
'''
# payouts[0] and payouts[1] exist as 'dummy' payouts
payouts = [0, 0, 1]
LAMBs -= payouts[-1]
while (LAMBs >= 0):
payouts.append(2*payouts[-1])
LAMBs -= payouts[-1]
# -2 for first two 'dummy' payouts and -1 for extra payout
return len(payouts) - 2 - 1
def minPayout(LAMBs):
'''
Given An-1 + An-2 <= An <= 2*An-1
An is minimized when An = An-1 + An-2
'''
# payouts[0] and payouts[1] exist as 'dummy' payouts
payouts = [0, 0, 1]
LAMBs -= payouts[-1]
while (LAMBs >= 0):
payouts.append(payouts[-1] + payouts[-2])
LAMBs -= payouts[-1]
# -2 for first two 'dummy' payouts and -1 for extra payout
return len(payouts) - 2 - 1
def solution(total_lambs):
return minPayout(total_lambs) - maxPayout(total_lambs)
def fastMaxPayout(LAMBs):
'''
Since maxPayout follows An = 2*An-1, maxPayout follows
geometric sequence that can be reduced to exponential.
An = 2^n
Then we solve for sum(An = 2^n) <= LAMBs and the geometric
series' sum formula follows:
Sn = A0 * 1-r^n / (1-r)
Sn = 1 * 1-2^n / (1-2)
Sn = 2^n - 1
Now we finally solve (Sn = 2^n - 1) <= LAMBs
2^n <= LAMBs + 1
n <= log2(LAMBs + 1)
n = floor(log2(LAMBs + 1)) = (LAMBs + 1).bit_length() - 1
'''
return (LAMBs + 1).bit_length() - 1
def fastMinPayout(LAMBs):
'''
Since minPayout follows An = An-1 + An-2, minPayout follows
a shifted Fibonnacci sequence. Apply Binet's formula to
derive the nth Fibonnacci sequence.
An-1 = Fn = ((1+sqrt(5) / 2)^n - (1-sqrt(5) / 2)^n) / sqrt(5)
Substitute constants for variables to simplify
let a = 1+sqrt(5) / 2
let b = 1-sqrt(5) / 2
let x = An-1 * sqrt(5)
x = a^n - b^n
a^n = x + b^n
n = loga(x + b^n)ls
And since lim n->inf b^n = 0, Binet's formula approximates:
n = loga(x)
Now we finally solve (Sn = An+2 - 1) >= LAMBs
n+3 = loga(An+2 * sqrt(5)) = loga((An+2 - 1 + 1) * sqrt(5))
n = loga((LAMBs + 1) * sqrt(5)) - 3
'''
from math import log, ceil, sqrt
return int(ceil(log((LAMBs + 1 + 0.5)*sqrt(5), (1+sqrt(5)) / 2)) - 3)
def fastSolution(total_lambs):
return fastMinPayout(total_lambs) - fastMaxPayout(total_lambs)
print(solution(143), fastSolution(143))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:22:20.373",
"Id": "424019",
"Score": "2",
"body": "It's really nice that you provided the description of the problem, but would it be possible for you to move it out of the code section?"
}
] | [
{
"body": "<h1>FP arithmetic</h1>\n<blockquote>\n<p>Besides trivialities i.e. inserting constants</p>\n</blockquote>\n<p>This is <em>kind</em> of a constant, but perhaps you'll view it as non-trivial.\nFor one thing it allows turning a division into a (cheaper) multiplication.</p>\n<p>Rather than supplying two args to <code>math.log()</code>, use this faster technique:</p>\n<pre><code> # one-time init\n rad_five = sqrt(5)\n phi = (1 + sqrt(5)) / 2\n recip_phi = 1 / phi\n\n # compute log base b, that is, base phi\n log((LAMBs + 1 + 0.5) * rad_five) * recip_phi\n</code></pre>\n<p>Invoking with 1 arg and then multiplying definitely runs faster.</p>\n<h1>lookup table</h1>\n<p>We accept a number that is at most a billion,\nthen compute lots of detailed mantissa bits,\nonly to have <code>ceil()</code> discard most of them.\nWhich is to say that the only input values you <em>really</em> care about\nare the ones that bump the log result past the next integer lattice point.\nStore such values in an ordered lookup table.\nRepeated multiplication by <code>phi</code> will help you find them.</p>\n<p>At runtime, compute the relevant log result using <a href=\"https://docs.python.org/3/library/bisect.html\" rel=\"noreferrer\">binary search</a>\non the lookup table.</p>\n<p>And yeah, you're right, you want to promote the <code>import</code>s to top-of-file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T19:39:13.897",
"Id": "424137",
"Score": "1",
"body": "I like both your suggestions. The first one isn't a 'constant' insertion per say for me because it changes how the logarithm operates. Secondly you make a good point about the look up table. I am thinking the arguments are rounded and delegated to a memoized function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T21:53:33.493",
"Id": "424144",
"Score": "0",
"body": "Hmm after actual testing, it seems that the functions do not return the same results. I am not sure what trick you are using but it may not apply here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T01:53:13.147",
"Id": "219543",
"ParentId": "219515",
"Score": "5"
}
},
{
"body": "<h1>PEP-8</h1>\n\n<ul>\n<li>Python convention uses <code>snake_case</code> for variable and function names</li>\n<li>Your spacing around numerical operators is not consistent</li>\n</ul>\n\n<h1>comments</h1>\n\n<p>Your comments are clear and they explain why something is done</p>\n\n<h1><code>payouts</code> list</h1>\n\n<p>This list is unnecessary. You only use its last element and its length. Better would be to use just variables, just like a standard fibonacci generators, and <code>itertools.count</code> to keep track of the number of payouts</p>\n\n<pre><code>def max_payouts(lambs):\n payout = 1\n for i in count():\n if lambs <= 0:\n return i\n payout *= 2\n lambs -= payout\n\n\ndef min_payouts(lambs):\n a, b = 0, 1\n for i in count():\n if lambs <= 0:\n return i\n a, b = b, a + b\n lambs -= b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T17:43:09.837",
"Id": "424125",
"Score": "1",
"body": "Hmm, ok that makes sense. Do you mind explaining `min_payouts` line `a, b = b, a + b`? I haven't seen that syntax before and I'm not quite sure what its doing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:16:58.617",
"Id": "219564",
"ParentId": "219515",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T17:48:11.783",
"Id": "219515",
"Score": "4",
"Tags": [
"python",
"programming-challenge",
"fibonacci-sequence"
],
"Title": "Foobar Challenge: Lovely Lucky Lambs"
} | 219515 |
<p>The problem is </p>
<blockquote>
<p>Given a non-negative integer <code>n</code>, return all valid parentheses strings
with <code>n</code> open parens and <code>n</code> close parens.</p>
</blockquote>
<p>My algorithm (represented by the <code>MySolution</code> class below) keeps a count of the open parentheses on the stack, and does a recursive depth-first search of possible strings.</p>
<p>Another algorithm (represented by the <code>TheirSolution</code> class) uses a similar strategy, but their solution reliably runs about twice as fast, when optimization is turned off. The outputs are identical.</p>
<p>The major difference is that their solution copies the current string on every recursive call to <code>Dfs</code>, so they never have to delete any characters from the end of strings; they just throw away the whole copy when the current stack frame ends. Another difference is that they keep track of the number of open parens left to use (<code>pos</code>) and close parens left to use (<code>neg</code>) explicitly, while my code does so implicitly.</p>
<p>Their code involves roughly the same number of recursions that mine does. </p>
<pre class="lang-cpp prettyprint-override"><code>int main()
{
constexpr int n_parens = 11;
MySolution sol1;
TheirSolution sol2;
sol1.generateParenthesis(n_parens);
sol2.generateParenthesis(n_parens);
}
</code></pre>
<p>Produces (with debug config)</p>
<pre><code>There were 290511 recursions.
Timer took 0.0245487 seconds.
There were 290510 recursions.
Timer took 0.0118699 seconds.
Program ended with exit code: 0
int main()
{
constexpr int n_parens = 11;
MySolution sol1;
TheirSolution sol2;
std::vector<std::string> v = sol1.generateParenthesis(n_parens);
std::vector<std::string> w = sol2.generateParenthesis(n_parens);
std::cout << (int)(v == w) << std::endl;
}
</code></pre>
<p>Produces (with release config)</p>
<pre><code>There were 290511 recursions.
Timer took 0.00570454 seconds.
There were 290510 recursions.
Timer took 0.00704376 seconds.
1
Program ended with exit code: 0
</code></pre>
<p>Here's the code!</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <chrono>
#include <vector>
#include <string>
#include <iomanip>
#include <algorithm>
struct Timer
{
std::chrono::time_point<std::chrono::steady_clock> start, end;
std::chrono::duration<float> duration;
Timer()
{
start = std::chrono::high_resolution_clock::now();
}
~Timer()
{
end = std::chrono::high_resolution_clock::now();
duration = end - start;
std::cout << "Timer took " << duration.count() << " seconds." << std::endl;
}
};
class TheirSolution {
public:
void Dfs(int deep, int border, int cnt, char c, std::vector<std::string>& v, int pos, int neg, std::string s)
{
n_recursions++;
s.append(1, c);
if (deep == border && pos == 0 && neg == 0)
{
v.push_back(s);
return;
}
if (pos > 0)
{
Dfs(deep + 1, border, cnt + 1, '(', v, pos - 1, neg, s);
}
if (cnt > 0 && neg > 0)
{
Dfs(deep + 1, border, cnt - 1, ')', v, pos, neg - 1, s);
}
}
std::vector<std::string> generateParenthesis(int n) {
n_recursions = 0;
Timer timer;
int positive, negative;
positive = negative = n;
std::vector<std::string> answer;
std::string s = "";
Dfs(1, 2 * n, 1, '(', answer, positive - 1, negative, s);
std::cout << "There were " << n_recursions << " recursions." << std::endl;
return answer;
}
private:
long long n_recursions;
};
class MySolution {
public:
std::vector<std::string> generateParenthesis(int _n)
{
Timer timer;
n_recursions = 0;
n = _n;
dfs(0);
std::cout << "There were " << n_recursions << " recursions." << std::endl;
return ret;
}
private:
void dfs(int stack_count)
{
n_recursions++;
if (stack_count == -1)
return;
else if (current_string.size() == 2*n)
{
if (stack_count == 0)
ret.push_back(current_string);
return;
}
if (stack_count < 2*n - current_string.size())
{
current_string.push_back('(');
dfs(stack_count + 1);
current_string.pop_back();
}
if (stack_count > 0)
{
current_string.push_back(')');
dfs(stack_count - 1);
current_string.pop_back();
}
}
long long n_recursions;
int n;
std::string current_string;
std::vector<std::string> ret;
};
int main()
{
constexpr int n_parens = 11;
MySolution sol1;
TheirSolution sol2;
sol1.generateParenthesis(n_parens);
sol2.generateParenthesis(n_parens);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T20:58:48.090",
"Id": "424032",
"Score": "0",
"body": "Do the two algorithms return the same string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T22:14:31.527",
"Id": "424042",
"Score": "0",
"body": "@pacmaninbw Yes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T00:58:53.457",
"Id": "424048",
"Score": "0",
"body": "You're including output (`std::cout` calls) in your execution times. These should be outside the timed code block, as they can be relatively slow and introduce great variability in timings."
}
] | [
{
"body": "<p>I <em>think</em> your implicit question was \"how may I improve runtime?\",\nin terms of CPU cycles, and in terms of memory read stalls.\nThe only relevant timings to pay attention to seem to be the optimized runs,\nand in that contest you're already pretty close.\nRuntimes less than 10 msec suggest that you might want to\ndo a hundred iterations of the whole test,\nor bump up <code>n_parens</code>.\nDo verify that switching the order of running sol{1,2} doesn't change the timings,\ne.g. due to cache warming effects.</p>\n\n<p>This code appears to be vestigial; it may have mattered in an earlier code version:</p>\n\n<pre><code> if (stack_count == -1)\n return;\n</code></pre>\n\n<p>The <code>return</code> appears to be dead code.\nI say that because there is a \"positive\" guard <code>if (stack_count > 0)</code>\non the decrement of <code>stack_count</code>.</p>\n\n<p>Overall your code seems pretty cache friendly.\nI don't see any obvious gotchas.\nThis copy:</p>\n\n<pre><code> ret.push_back(current_string);\n</code></pre>\n\n<p>could maybe be dispensed with,\nby building up the result string in the desired spot within <code>ret</code>.\nOf course, they do <code>v.push_back(s)</code> which is similar copying cost.</p>\n\n<p>I choose to read <code>deep</code> as \"depth\",\nand I prefer that concise name over the clunky <code>stack_count</code>.</p>\n\n<p>I find their profusion of redundant args somewhat ugly.\nHowever, it's a sure thing that each one is register allocated.\nI wonder if your repeated <code>current_string.size()</code> access explains\nthe few missing milliseconds that separate the two implementations?</p>\n\n<p>Your depth first search has three clauses,\nand three brief comments seem warranted.</p>\n\n<p>The biggest change to make to this recursive approach\nwould be to <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoize</a> the result of a given <code>stack_count</code> input,\nto avoid repeatedly computing (and recursing) for that given value.\nYour single-arg API is clearly simpler to memoize\nthan TheirSolution would be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T13:37:52.753",
"Id": "424112",
"Score": "2",
"body": "Naturally, for best results [change the algorithm](https://sahandsaba.com/interview-question-generating-all-balanced-parentheses.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T15:45:01.510",
"Id": "424232",
"Score": "0",
"body": "@Deduplicator Great link! Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T01:08:37.573",
"Id": "219542",
"ParentId": "219517",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "219542",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T18:35:56.220",
"Id": "219517",
"Score": "4",
"Tags": [
"c++",
"recursion",
"comparative-review",
"depth-first-search",
"balanced-delimiters"
],
"Title": "Return all valid paren strings with a given length"
} | 219517 |
<p>I have an interactor/usecase class in my application. My application follows MVVM architecture with interactor/usecases responsible for logic (e.g. get data from api-service, store in local-database etc).</p>
<p>Now I am trying to write unit tests for my interactor classes.</p>
<p>Here is one on those classes:</p>
<pre><code>public class ChangeUserPasswordInteractor {
private final FirebaseAuthRepositoryType firebaseAuthRepositoryType;
public ChangeUserPasswordInteractor(FirebaseAuthRepositoryType firebaseAuthRepositoryType) {
this.firebaseAuthRepositoryType = firebaseAuthRepositoryType;
}
public Completable changeUserPassword(String newPassword){
return firebaseAuthRepositoryType.getCurrentUser()
.flatMapCompletable(firebaseUser -> {
firebaseAuthRepositoryType.changeUserPassword(firebaseUser, newPassword);
return Completable.complete();
})
.observeOn(AndroidSchedulers.mainThread());
}
}
</code></pre>
<p>This class changes the password for a Firebase user.</p>
<p>Now here is a test class I wrote:</p>
<pre><code>@RunWith(JUnit4.class)
public class ChangeUserPasswordInteractorTest {
@Mock
FirebaseAuthRepositoryType firebaseAuthRepositoryType;
@Mock
FirebaseUser firebaseUser;
@InjectMocks
ChangeUserPasswordInteractor changeUserPasswordInteractor;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
RxAndroidPlugins.reset();
RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerCallable -> Schedulers.trampoline());
}
@Test
public void changeUserPassword() {
Mockito.when(firebaseAuthRepositoryType.getCurrentUser()).thenReturn(Observable.just(firebaseUser));
Mockito.when(firebaseAuthRepositoryType.changeUserPassword(firebaseUser, "test123")).thenReturn(Completable.complete());
changeUserPasswordInteractor.changeUserPassword("test123")
.observeOn(Schedulers.trampoline())
.test()
.assertSubscribed()
.assertNoErrors()
.assertComplete();
}
}
</code></pre>
<p>I would like some criticism and suggestions on these tests. Is this a good way to test my interactor method?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T18:53:19.410",
"Id": "219520",
"Score": "3",
"Tags": [
"java",
"android",
"junit",
"mocks",
"rx-java"
],
"Title": "Android+Firebase testing using Mockito"
} | 219520 |
<blockquote>
<p>Given a string, find the first non-repeating character in it and
return it's index. If it doesn't exist, return -1.</p>
</blockquote>
<p><strong>Examples:</strong></p>
<pre><code>s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
</code></pre>
<blockquote>
<p>Note: You may assume the string contain only lowercase letters.</p>
</blockquote>
<p>My solution</p>
<pre><code>public class FirstUniqueCharacter {
public int firstUniqChar(String s) {
LinkedHashMap<Character, Integer> map = new LinkedHashMap<>();
for (char c : s.toCharArray()) {
if (Objects.isNull(map.get(c))) {
map.put(c, 1);
} else {
int count = (Integer) map.get(c);
map.put(c, ++count);
}
}
for (Map.Entry e : map.entrySet()) {
int value = (int) e.getValue();
Character c = (Character) e.getKey();
if (value == 1) {
return s.indexOf(c);
}
}
return -1;
}
}
</code></pre>
<p>The statistics shows it’s still slower than 60% of the solutions submitted in terms of speed and space. How can I improve it? Any comments regarding code readibility are most welcome.</p>
| [] | [
{
"body": "<p>You don’t need <code>Objects.isNull(...)</code>. Simply using <code>!= null</code> would suffice, and avoids an extra function call so should be faster (unless the compiler can optimize the call out).</p>\n\n<hr>\n\n<p>Your loop at the end is using raw types. You should use</p>\n\n<pre><code>for(Map.Entry<Character, Integer> e : map.entrySey()) {\n</code></pre>\n\n<p>instead, for type safety. Your castings then are unnecessary.</p>\n\n<hr>\n\n<p>There is no need to fetch the character <code>c = e.getKey()</code> unless <code>value == 1</code> is true; you can more that inside the <code>if</code> for a minor performance gain.</p>\n\n<hr>\n\n<p>Counting the character occurrences is slightly dangerous: you could overflow an <code>Integer</code>, or even a <code>Long</code> with a long enough string. Simply flagging the character as “seen once” or “more than once” avoids the counting overflow bug.</p>\n\n<hr>\n\n<p>The <code>map.put(c, 1)</code> call returns the previous value stored in the map, or <code>null</code> if no value was stored. Instead of fetching the value, testing whether it was present or not, and then storing another value, why not store & fetch in one operation? Then, if a value was already present, you can flag it as occurring twice (or more).</p>\n\n<pre><code>if( map.put(c, 1) != null )\n map.put(c, 2);\n</code></pre>\n\n<hr>\n\n<p>Since you are no longer counting, you don’t need a <code>LinkedHashMap<Character, Integer></code>. You just have 3 states: not seen, seen once, and seen more than once. A <code>Boolean</code> can cover this. <code>Boolean.TRUE</code> is seen once (unique), <code>Boolean.FALSE</code> is seen more than once, and not present (<code>null</code>) is never seen.</p>\n\n<pre><code>LinkedHashMap<Character, Boolean> unique = new LinkedHashMap<>();\n\nfor(char c: ...) {\n if (unique.put(c, Boolean.TRUE) != null)\n unique.put(c, Boolean.FALSE);\n}\n</code></pre>\n\n<p>We’ve saved a tiny bit of space, since we only have two <code>Boolean</code> objects, instead of several (possibly interned) <code>Integer</code> objects. Much more importantly, we’ve avoided auto boxing, so this should be much faster.</p>\n\n<hr>\n\n<p>We are still wasting time storing both <code>Boolean.TRUE</code> and <code>Boolean.FALSE</code> successively on the third and subsequent occurrences of any character.</p>\n\n<p>If we always store <code>Boolean.FALSE</code>, then on the first occurrence <code>null</code> will be returned. We can detect that and overwrite it with <code>Boolean.TRUE</code> instead, so the exceptional first occurrence has 2 map <code>put</code> operations, but subsequent occurrences only use 1 map <code>put</code> operation, for better performance.</p>\n\n<pre><code> if (unique.put(c, Boolean.FALSE) == null)\n unique.put(c, Boolean.TRUE);\n</code></pre>\n\n<hr>\n\n<p>To truly gain speed and reduce memory usage, avoid clunky <code>HashSet<></code> memory structures, and store the data yourself. You are told you can assume only lowercase letters are used, so you can use a <code>new byte[26]</code> array for “not seen”, “seen once”, and “seen multiple times” storage. And use a <code>new char[26]</code> array to maintain encounter order of “first seen” characters.</p>\n\n<p>You can use a bit more memory and store the index of the first seen characters in a <code>new int[26]</code>, so you can avoid the linear <code>s.indexOf(c)</code> search at the end. You could even use <code>0</code> for not seen, <code>index+1</code> for seen once, and <code>-1</code> for seen multiple times, and avoid the <code>new byte[26]</code> flag storage.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:38:16.900",
"Id": "424054",
"Score": "0",
"body": "Never assume that a \"letter\" means something between a-z. https://www.compart.com/en/unicode/category/Ll Regards, Your Scandinavian fellow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T11:21:40.183",
"Id": "424096",
"Score": "0",
"body": "@TorbenPutkonen The task description explicitly says you can assume that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T14:31:53.920",
"Id": "424118",
"Score": "0",
"body": "@RoToRa Actually it says “_You may assume the string contains only lowercase letters._”. It doesn’t say anything about ‘a-z’. On the other hand , it doesn’t mention the vulgarities of [Unicode combining characters](https://en.m.wikipedia.org/wiki/Combining_character). The “C” version of the problem uses `char *` for its strings, but that doesn’t preclude multibyte character encodings either. Even with ‘a-z’ restrictions, using EBCDIC encoding would complicate the storage into just 26 array entries. Using `byte[256]` storage would be better, but still wrong for some encodings."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:19:21.250",
"Id": "219549",
"ParentId": "219521",
"Score": "2"
}
},
{
"body": "<p>Having LinkedHashMap A and HashSet B.</p>\n\n<p>For each character C in string S</p>\n\n<ul>\n<li>Map C to it's position in S to A.</li>\n<li>If adding C to B returns false</li>\n<li>Remove C from A.</li>\n</ul>\n\n<p>Return value mapped to first element in A or -1 if A is empty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:39:56.027",
"Id": "219553",
"ParentId": "219521",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:10:46.087",
"Id": "219521",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"array",
"interview-questions"
],
"Title": "Leetcode - First Unique Character in a String"
} | 219521 |
<p>I have a function that returns a string that indicates if an element is the same as another element(s). The logic is:</p>
<pre><code>function duplicates(duplicatesArray, id = 1) {
var duplicates = '';
var count = 1;
var length = duplicatesArray.length;
var _id = null;
for (var i = 0; i < length; i++) {
_id = duplicatesArray[i];
if (_id !== id) {
count++;
if (length == 2) {
duplicates = duplicates + ' ' + _id;
return duplicates;
} else if (count < length) {
duplicates = duplicates + ' ' + _id;
if (count + 1 < length) {
duplicates = duplicates + ',';
}
} else {
duplicates = duplicates + ' and ' + _id;
}
}
}
return duplicates;
}
</code></pre>
<p>The above outputs:</p>
<pre><code>console.log(
'This item is the same as item ' + duplicates(
[1, 2]
)
); // This item is the same as item 2
console.log(
'This item is the same as item ' + duplicates(
[1, 2, 3]
)
); // This item is the same as item 2 and 3
console.log(
'This item is the same as item ' + duplicates(
[1, 2, 3, 4]
)
); // This item is the same as item 2, 3 and 4
</code></pre>
<p>This function takes in an <code>id</code> (here, I am defaulting it to <code>id = 1</code> for the purpose of brevity) and it compares that <code>id</code> to elements in the first argument, which is an array of other IDs. The comments after the <code>console.log</code>s above is the expected output, I'm just wondering if there is a more succinct way of approaching this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:42:55.417",
"Id": "424021",
"Score": "0",
"body": "I don't understand what task this code accomplishes, nor do I understand what this question has to do with [tag:functional-programming]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:50:27.523",
"Id": "424022",
"Score": "0",
"body": "Which part specifically are you having trouble with?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:51:24.407",
"Id": "424023",
"Score": "1",
"body": "All of it. You never explained what a \"duplicate\" is. As far as I'm concerned, `[1, 2, 3, 4]` is an array with four distinct elements, and no duplicates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:56:31.727",
"Id": "424026",
"Score": "0",
"body": "Oh, that's fair -- I've updated the question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:18:00.423",
"Id": "424085",
"Score": "0",
"body": "As far as I'm concerned it confuses me that you are talking about a string-builder in the title and then about checking whether there are duplicate elements. Which one is it or what is string-builder-ish about it? Oh, and if you are doing both things at the same time, which I suppose, then it's a huge design no-go."
}
] | [
{
"body": "<p>I really have difficulty understanding your explanation or your code, but the wanted output is clear. So going only by that I propose this function:</p>\n\n<pre><code>function duplicates(testArray, id = 1)\n{\n return testArray.filter(testId => testId !== id);\n}\n</code></pre>\n\n<p>the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">filter()</a> method creates a new array with all elements that pass the test implemented by the provided function. In this case I test that the array items are unequal to the given id. The output of your tests is:</p>\n\n<blockquote>\n <p>This item is the same as item 2<br>\n This item is the same as item 2,3<br>\n This item is the same as item 2,3,4</p>\n</blockquote>\n\n<p>So, there's not the fancy 'and' in there yet, but that can be added. Is it really needed? Anyway, adding a bit of extra code like this:</p>\n\n<pre><code>function formatArray(idArray)\n{\n var ending = (idArray.length > 1) ? ' and ' + idArray.pop() : '';\n return idArray.join(', ') + ending;\n}\n\nfunction duplicates(testArray, id = 1)\n{\n return formatArray(testArray.filter(test => test !== id));\n}\n</code></pre>\n\n<p>where we join the array to a string separated by commas, except for the ending if there are multiple items, when we insert an 'and'. The thing that might not be obvious is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">conditional (ternary) operator</a>. If you don't like it you can replace it with a normal <code>if (...) {...} else {...}</code> statement. This returns:</p>\n\n<blockquote>\n <p>This item is the same as item 2<br>\n This item is the same as item 2 and 3<br>\n This item is the same as item 2, 3 and 4</p>\n</blockquote>\n\n<p>Now this is \"Code Review\" so I should review your code. That is difficult. I can almost see what you were trying to do, but it is such a mess (sorry). It seems you started with the <code>for</code> loop and then just created this Frankenstein monster by adding bits. Inside the loop you have four <em>ifs</em>, two <em>elses</em> and even a <em>return</em>. Some of the actions are the same, like adding a space. I don't believe even you know exactly what's going on there. It might work, but that's it. This is not how you should be programming.</p>\n\n<p>Some advice:</p>\n\n<p>Try to analyse the problem before you start writing any code. There are two clear distinct jobs to do: </p>\n\n<ol>\n<li>Get rid of the duplicates.</li>\n<li>Generate the output.</li>\n</ol>\n\n<p>Keep these two jobs apart. That makes each problem easier to solve and leads to easier to understand code, because the jobs themselves are easier. Ideally these two jobs should be done in two seperate functions. A function should only do one thing, and not two.</p>\n\n<p>Now I have to agree that, what I did, simply requires a lot of experience. You need to know the language you're using. That will come with time and practice.</p>\n\n<p>Another thing you need to pay attention to is the names you use. One of the major reason I cannot understand your code is that it is unclear what it all means. What is in <code>duplicatesArray</code>? And why is the function called <code>duplicates</code>? That just doesn't make much sense. Something like <code>removeDuplicates</code> would be better as a function name, because it implies a clear action.</p>\n\n<p>In my personal opinion each function should always, and only, have one <code>return</code> in it. I'll admit that I don't always stick to this rule, but as a general idea it is sound. Having multiple returns makes a function harder to understand, and having no return just seems lazy. There's always something to return.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:14:51.267",
"Id": "219559",
"ParentId": "219522",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:15:41.223",
"Id": "219522",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Is there a better way to implement this string builder?"
} | 219522 |
<p>I'm trying to create a shell prompt that displays the <code>$PWD</code> in a "smart" way. I want to display the top two directories rather than the full path. If <code>$HOME</code> is the parent (or parent of the parent) directory, I want to show it like <code>~</code>.</p>
<p>Assuming my <code>$HOME</code> is <code>"/home/user"</code>, here are a few test cases with expected output according to several <code>$PWD</code> values:</p>
<pre><code>/ -> /
/home -> /home
/home/user -> ~
/home/user/foo -> ~/foo
/home/user/foo/bar -> foo/bar
/usr/local -> /usr/local
/usr/local/games -> local/games
/home/userr -> /home/userr
</code></pre>
<p>Currently, my solution is as follow:</p>
<pre class="lang-bsh prettyprint-override"><code>path=$PWD
# $n is the number of "/" in the path indicating that there is more than 2 dirs
# In such case, the path should be truncated
# If the path contains root / (like "/home/usr"), 3 "/" implies 3 dirs
# If the path is "~/foo" then only 2 "/" are required
# If ${PWD} starts with ${HOME}, we can replace this part with "~"
# A slash need to be appended to "${HOME}" to avoid false positive
n=3
if [[ ${path}/ == ${HOME}/* ]]; then
path=~${path:${#HOME}}
n=2
fi
# Count the number of "/" in the path
# If there is more than $n "/", this means the path contains more than 2 dirs
# In this situation, we need to extract the two last dirs only from the path
slashes=${path//[^\/]}
if [[ ${#slashes} -ge $n ]]; then
dir=${path##*/}
parentpath=${path%/*}
parentdir=${parentpath##*/}
path=$parentdir/$dir
fi
echo $path
</code></pre>
<p>This function is intended to be used in my bash shell prompt. As this will be issued each time I type a command in my terminal, and as I will keep this in my <code>.bashrc</code> for probably several years to come, I'm looking to "<strong>optimize</strong>" this function. </p>
<p>Could the solution have been implemented otherwise, or could this function be improved in some way in order to minimize it's overall "footprint"?</p>
| [] | [
{
"body": "<p>Returning values by variable is 3-10 times faster than capturing an <code>echo</code> with <code>$( )</code>. Your temp variable is already global. Just name it something similar to what the surrounding function is named. </p>\n\n<p>Whitespace and comments affect bash performance negatively. It's not a big penalty, just something to be aware of.</p>\n\n<p>A regular expression can do the \"last two path components\" extraction very compactly. </p>\n\n<pre><code>cwd() {\n cwd=$PWD\n [[ $cwd/ == $HOME/* ]] && cwd=~${cwd#$HOME}\n [[ $cwd =~ ./([^/]+/[^/]+)$ ]] && cwd=${BASH_REMATCH[1]}\n}\n\nPROMPT_COMMAND=cwd\n\nPS1=\"<span class=\"math-container\">\\$cwd \\$</span>\"\n</code></pre>\n\n<p>I'd say not to count the tilde as a path component: it's only one extra character that carries a lot of information, well worth the single column. The regex is then:</p>\n\n<pre><code> [[ $cwd =~ (..|[^~])/([^/]+/[^/]+)$ ]] && cwd=${BASH_REMATCH[2]}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T23:18:02.983",
"Id": "424159",
"Score": "0",
"body": "Thanks for the tips. I have figured out that best performances are reached by avoiding use of regex engine (and replacing `${HOME}/*` with index-based substring extraction)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T04:31:00.293",
"Id": "219548",
"ParentId": "219524",
"Score": "3"
}
},
{
"body": "<p>Based on @OhMyGoodness suggestions, here is an improved function:</p>\n\n<pre><code>cwd() {\n cwd=$PWD\n [[ $cwd/ == $HOME/* ]] && cwd=~${cwd:${#HOME}}\n begin=${cwd%?/*/*} && [[ \"$begin\" != \"$cwd\" ]] && path=${cwd:${#begin}+2}\n}\n</code></pre>\n\n<p>It's slightly faster as it reduces string manipulations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T18:52:39.880",
"Id": "219720",
"ParentId": "219524",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T19:41:04.640",
"Id": "219524",
"Score": "5",
"Tags": [
"performance",
"bash"
],
"Title": "Smart way to shorten the current working directory in pure Bash"
} | 219524 |
<p><strong>The task</strong>
is taken from <a href="https://leetcode.com/problems/flipping-an-image/" rel="nofollow noreferrer">leetcode</a></p>
<blockquote>
<p>Given a binary matrix <code>A</code>, we want to flip the image horizontally, then
invert it, and return the resulting image.</p>
<p>To flip an image horizontally means that each row of the image is
reversed. For example, flipping <code>[1, 1, 0]</code> horizontally results in <code>[0, 1, 1]</code>.</p>
<p>To invert an image means that each 0 is replaced by 1, and each 1 is
replaced by 0. For example, inverting <code>[0, 1, 1]</code> results in <code>[1, 0, 0]</code>.</p>
<h3>Example 1:</h3>
<p><strong>Input</strong>: <code>[[1,1,0],[1,0,1],[0,0,0]]</code><br>
<strong>Output</strong>: <code>[[1,0,0],[0,1,0],[1,1,1]]</code><br>
<strong>Explanation</strong>: First reverse each row: <code>[[0,1,1],[1,0,1],[0,0,0]]</code>. Then,
invert the image: <code>[[1,0,0],[0,1,0],[1,1,1]]</code></p>
<h3>Example 2:</h3>
<p><strong>Input</strong>: <code>[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]</code><br>
<strong>Output</strong>:
<code>[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]</code><br>
<strong>Explanation</strong>: First reverse
each row: <code>[[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]]</code>. Then invert the
image: <code>[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]</code> </p>
<h3>Notes:</h3>
<ul>
<li><code>1 <= A.length = A[0].length <= 20</code></li>
<li><code>0 <= A[i][j] <= 1</code> </li>
</ul>
</blockquote>
<p><strong>My functional solution:</strong></p>
<pre><code>const arr = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]];
const flipAndInvertImage = A => A
.map(x => x.reverse())
.map(x => x.map(i => i ? 0 : 1));
console.log(flipAndInvertImage(arr));
</code></pre>
| [] | [
{
"body": "<p>Flipping binary numbers (i.e. bits) from 0 to 1 or vise-versa can be achieved with bitwise operations, like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#(Bitwise_XOR)\" rel=\"nofollow noreferrer\">XOR</a>. This may give a slight performance increase in some browsers - refer to <a href=\"https://jsperf.com/bitwise-xor-vs-ternary\" rel=\"nofollow noreferrer\">this jsPerf</a>.</p>\n\n<p>Instead of the ternary:</p>\n\n<blockquote>\n<pre><code> .map(x => x.map(i => i ? 0 : 1));\n</code></pre>\n</blockquote>\n\n<p>Use XOR:</p>\n\n<pre><code> .map(x => x.map(i => i ^ 1));\n</code></pre>\n\n<hr>\n\n<p>Unless I am mistaken, you should be able to combine the two <code>.map()</code> callbacks into one - </p>\n\n<pre><code>.map(x => x.reverse().map(i => i ^ 1));\n</code></pre>\n\n<p>This will lead to fewer function calls, resulting in less resources required to complete.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arr = [[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]];\nconst flipAndInvertImage = A => A\n .map(x => x.reverse().map(i => i ^ 1));\n\n\nconsole.log(flipAndInvertImage(arr));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:17:51.770",
"Id": "424036",
"Score": "0",
"body": "Thanks for the hint with the bitwise operation. But your last code is incorrect I think. This should give me the correct result: `const flipAndInvertImage2 = A => A.map(x => x.map(i => i ^ 1));`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:28:00.617",
"Id": "424038",
"Score": "0",
"body": "but that could wouldn't have the `reverse()` calls, and thus each row would not be _flipped_..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:08:57.790",
"Id": "219531",
"ParentId": "219528",
"Score": "3"
}
},
{
"body": "<p>If this was computer graphics each operation would be called a transform. You would never do two or more transforms in sequence you would combine the transforms into a single transform and apply that to the image.</p>\n<p>As in this case the transforms are abstracted and thus hard coded you can avoid the need to combine transforms and just hard code the combined transform. IE reverse and flip in one expression.</p>\n<p>Invert is often called "image negative". The transform is done by subtracting the pixel value from the maximum possible pixel value</p>\n<h2>Two versions</h2>\n<p>The first inverts using <code>1 - pixel</code> and second using bitwise operation <code>pixel ^ 1</code></p>\n<pre><code>const flipInvertImg = img => img.map(row => row.map((p,i) => 1 - row[row.length - 1 - i]))\n</code></pre>\n<p>or</p>\n<pre><code>const flipInvertImg = img => img.map(row => row.map((p,i) => row[row.length - 1 - i] ^ 1))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T00:58:15.523",
"Id": "219541",
"ParentId": "219528",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219541",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T20:33:48.133",
"Id": "219528",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Flipping an Image"
} | 219528 |
<pre><code>def validate_time_zone
if time_zone.present? && org.present? && !org.country.states.map(&:time_zone).uniq.include?(time_zone)
errors.add(:time_zone, :invalid)
end
end
</code></pre>
<p>I have a user model with the following relations:</p>
<ul>
<li>User can optionally belong to Org</li>
<li>Org belongs to a Country</li>
<li>A Country has some timezones (not unique as two states may have the same timezone). </li>
</ul>
<p>So I validate that if the user is associated with an organization then it must have a valid timezone. Valid timezone means any time zone that comes under organization country. Ex Organization is ABC, Country is USA and Timezones are CET, Pacific, and Other US Time Zone. Then the user must use a timezone within the above three only. </p>
<p>I have filtered the condition but I am not sure breaking down will improve quality or further performance.</p>
<p>Can we used scope here too in country or organization or user module as it help in DRY not just validation. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T04:41:55.600",
"Id": "424051",
"Score": "0",
"body": "(Welcome to Code Review.) You use `Country` at least two times, just to be followed by *organization **county***: is the latter a typing error?"
}
] | [
{
"body": "<p>In case if you wanna improve only the <code>validate_time_zone</code> method:</p>\n\n<p>Performance wise I don't see anything sinister in your implementation.</p>\n\n<p>I assume the <code>states</code> table has a direct <code>time_zone</code> field. If so, then we can use the <code>pluck</code> method to avoid instantiation ActiveRecord objects.</p>\n\n<p><code>Array.uniq</code> returns a new array by removing duplicate values. The idea is nobel but it means it will use more memory and will loop over the time zones array which will happen anyway in case of <code>include?</code> </p>\n\n<p>On the other hand nowadays in software development the real cost is more in maintenance rather than in CPU cycles.</p>\n\n<p>With this in mind, how about the following refactor?</p>\n\n<pre><code>class User\n validates_presence_of :time_zone\n\n validate :validate_time_zone\n\n def validate_time_zone\n # using guard clause and let the built in validation do the presence validation\n return unless org.present? && time_zone.present?\n\n # A temp variable is a code smell, but here we have an underlying concept\n # that is better to be named\n allowed_time_zones = org.country.states.pluck(:time_zone)\n\n # tip: you can use the .exclude? API if you don't want to a use guard clause\n return if allowed_time_zones.include?(time_zone)\n\n errors.add(:time_zone, :invalid)\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T03:11:08.390",
"Id": "424050",
"Score": "0",
"body": "What if organization may it might not be present."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T09:35:33.850",
"Id": "424070",
"Score": "0",
"body": "You mean, the organisation is optional for users?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:07:58.840",
"Id": "424101",
"Score": "0",
"body": "Yes its optional in osme scenario"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T13:04:39.333",
"Id": "424109",
"Score": "0",
"body": "Well, you forget to mention it in the original description, I edited it. You might wanna disclose the business logic for such a case when you wanna validate the time_zone of a user who doesn't belong to any organisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T18:31:46.497",
"Id": "424128",
"Score": "0",
"body": "Agree. But is not there any way we can set some scope in country or user or organization. That could be rich data model."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T19:01:10.407",
"Id": "424134",
"Score": "0",
"body": "Also this code break if a user created without organization"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T14:01:23.550",
"Id": "424223",
"Score": "0",
"body": "Why not to link the users to a country/state as well? That would specify their timezone by default. It would help when an organization has some contractor remote employees from different country than the organization itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T14:02:51.173",
"Id": "424224",
"Score": "0",
"body": "As per businesses rule we don't need any other timezone. We intentionally block them to use other."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T23:14:26.533",
"Id": "219537",
"ParentId": "219529",
"Score": "3"
}
},
{
"body": "<p>I would do <code>org.country.states.where(time_zone: time_zone).empty?</code> instead of not + map/pluck + include?, there's no need to get an array of time zones.</p>\n\n<p>And I'd move the condition to a helper private method for readabilty.</p>\n\n<pre><code>def validate_time_zone\n errors.add(:time_zone, :invalid) if time_zone_not_in_country?\nend\n\nprivate\ndef time_zone_not_in_country?\n time_zone.present? and org.present? and org.country.states.where(time_zone: time_zone).empty?\nend\n</code></pre>\n\n<p>You could even move that ugly <code>org.country.states....</code> chain to a method on the Org model like <code>incluedes_time_zone?(time_zone)</code> (read about the Law of Demeter)</p>\n\n<pre><code>def time_zone_not_in_country?\n time_zone.present? and !org.try(:includes_time_zone?, time_zone) #using `try` to skip that `org.present?` call too\nend\n</code></pre>\n\n<p>and on Org.rb</p>\n\n<pre><code>def includes_time_zone?(tz)\n country.states.where(time_zone: tz).any?\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T13:00:22.657",
"Id": "219986",
"ParentId": "219529",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T20:34:06.917",
"Id": "219529",
"Score": "1",
"Tags": [
"performance",
"ruby",
"validation",
"ruby-on-rails"
],
"Title": "Validate if the user is associated with the organization then it must have any valid timezone"
} | 219529 |
<p>I wrote a function that iterates over 3 parameters to spot out-of-stock items. To illustrate this I'll draw an example: suppose that the product 10 in store 2 for an offer named "super5" is following this trend</p>
<pre><code>day | qty
1 50
2 70
3 55
4 67
5 13
6 0
</code></pre>
<p>Offer finished at day 6, the product was potentially out of stock at day 5. In order to spot this and verify it I find the index of 0 qty and look 2 back i took the mean of that two day (67 + 13) / 2 = 40 if the mean is > first decile then tag "out-of-stock" else "ko"</p>
<p>I tried: </p>
<pre><code>def flag_out_of_stock(dataframe, sku, store, offer) :
ffl = []
sku_store_offer = dataframe[["id_sku", "id_store", "id_offer"]].drop_duplicates(["id_sku", "id_store", "id_offer"])
for sku, store, offer in tqdm(zip(sku_store_offer["id_sku"], sku_store_offer["id_store"], sku_store_offer["id_offer"])):
cond1 = dataframe["id_sku"] == sku
cond2 = dataframe["id_store"] == store
cond3 = dataframe["id_offer"] == offer
timeseries = dataframe[np.logical_and.reduce((cond1, cond2, cond3))][["f_qty_recalc", "id_day"]]\
.set_index("id_day")\
.sort_index()
mu = timeseries.mean()[0]
if mu >= 6 :
sigma = timeseries.std()[0]
q1 = timeseries.quantile(0.1)[0]
# index where qty == 0
likely_out_of_stock_index = np.where(timeseries ==0)[0]
# if there more that one value where qty == 0
if len(likely_out_of_stock_index) > 1 :
# for each index where qty == 0
for i in likely_out_of_stock_index :
# if the day before or day after are superior to the first decile
#then flag out of stock
day_before_2 = timeseries.iloc[i-2:i].mean()[0]
if day_before_2 >= q1 :
ffl.append("out_of_stock")
elif day_before_2 >= mu - sigma :
ffl.append("likely_out_of_stock")
else :
ffl.append("KO")
else :
try :
day_before_2 = timeseries.iloc[likely_out_of_stock_index-2:likely_out_of_stock_index].mean()[0]
if day_before_2 >= q1 :
ffl.append("out_of_stock")
elif day_before_2 >= mu - sigma :
ffl.append("out_of_stock")
else :
ffl.append("KO")
except TypeError :
ffl.append("KO")
else :
ffl.append("KO")
return pd.Series(ffl)
</code></pre>
<p>The issue there that this code running on ~600k row of parameters and took ~1.3seconds per iteration. Of that, 0.9sec is that operations…</p>
<blockquote>
<pre><code>timeseries = dataframe[np.logical_and.reduce((cond1, cond2, cond3))][["f_qty_recalc", "id_day"]]\
.set_index("id_day")\
.sort_index()
</code></pre>
</blockquote>
<p>so I would like to find a faster way.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:49:19.063",
"Id": "424057",
"Score": "1",
"body": "Hey, welcome to Code Review! Can you add some small example input data? It is a bit hard to follow what is happening otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:23:59.270",
"Id": "424087",
"Score": "2",
"body": "This question has been flagged for moving to SO but I think it belongs here. It's not looking off-topic but as @Graipher said, some additional example data would be very helpful."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:24:38.810",
"Id": "219532",
"Score": "1",
"Tags": [
"python",
"performance",
"statistics",
"pandas"
],
"Title": "Flagging out-of-stock items"
} | 219532 |
<p>This code is tested and works, but I am needing some guidance on simplifying these loops with non-contiguous ranges. I was thinking an <code>array</code> might be better, but I haven't had enough experience with <code>Arrays</code> to know where to start with one. Any guidance would be greatly appreciated.</p>
<pre class="lang-vb prettyprint-override"><code>Dim r As Range
Dim v
For Each r In JHACheck.Range("M7:M32")
v = r.Value
If v <> "" Then
If Not r.HasFormula Then
r.Value = Trim(v)
End If
End If
Next r
For Each r In JHACheck.Range("M35:M41")
v = r.Value
If v <> "" Then
If Not r.HasFormula Then
r.Value = Trim(v)
End If
End If
Next r
For Each r In JHACheck.Range("R35:R41")
v = r.Value
If v <> "" Then
If Not r.HasFormula Then
r.Value = Trim(v)
End If
End If
Next r
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T22:23:00.013",
"Id": "424043",
"Score": "1",
"body": "Are the ranges the same every time you run the macro? if they are you could try `For Each r In JHACheck[\"M7:M32,M35:M41R35:R41\"]` It wouldn't decrease the speed but it would reduce the duplication of code. Otherwise you would need to create an array of ranges to reduce the duplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T22:33:50.057",
"Id": "424044",
"Score": "0",
"body": "Thanks. I'll give it a try when I'm back in the office tomorrow."
}
] | [
{
"body": "<p>The small amount of data doesn't merit the use of arrays. I agree with R. Roe comment on combining the Ranges.</p>\n\n<p>But first:</p>\n\n<ul>\n<li>V is a very unhelpful helper variable, I would get rid of it. </li>\n<li>Personally, I use <code>r</code> to iterate rows row, <code>c</code> to iterate columns and <code>cell</code> to iterate cells in a Range</li>\n<li>Techiniquelly, the two if statements are more efficient than combining a single If statement. Realistically, it will not make a noticeable difference with your code. I would combine the Ifs and save the clutter. </li>\n</ul>\n\n<hr>\n\n<blockquote>\n<pre><code>Dim cell As Range\nFor Each cell In JHACheck.Range(\"M7:M32,M35:M41,R35:R41\")\n If Not r.HasFormula And cell.Value <> \"\" Then cell.Value = Trim(cell.Value)\nNext\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:55:42.283",
"Id": "424107",
"Score": "0",
"body": "Thanks! For some strange reason I was under the wrong assumption that I couldnt loop through non-contiguous cells like this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T05:01:05.507",
"Id": "424171",
"Score": "0",
"body": "@ZackE I think that they changed it in recent years. I'm pretty sure that in Excel 2007, we had to iterate over each cell of each area of a range,"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T11:32:35.283",
"Id": "219578",
"ParentId": "219533",
"Score": "1"
}
},
{
"body": "<p>It's clear you're performing the same operation over different ranges of cells. So I'd separate that logic in a <code>Function</code> which you can call with any range you like. Using arrays achieve a speed up if the ranges are large, but for now wait until you think you need it. (Needing to check the cell for <code>.HasFormula</code> will slow down using an array in any case.)</p>\n\n<p>The code below shows the trimming logic isolated to a single function. The logic is no different from yours with the exception of more clear variable names.</p>\n\n<pre><code>Option Explicit\n\nSub test()\n TrimTheseCells JHACheck.Range(\"M7:M32\")\n TrimTheseCells JHACheck.Range(\"M35:M41\")\n TrimTheseCells JHACheck.Range(\"R35:R41\")\nEnd Sub\n\nPrivate Sub TrimTheseCells(ByRef thisRange As Range)\n Dim cell As Range\n For Each cell In thisRange\n If Not IsEmpty(cell) Then\n If Not cell.HasFormula Then\n cell.Value = Trim(cell.Value)\n End If\n End If\n Next cell\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T13:49:04.713",
"Id": "219587",
"ParentId": "219533",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "219578",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T21:55:23.790",
"Id": "219533",
"Score": "1",
"Tags": [
"strings",
"vba",
"excel",
"formatting"
],
"Title": "Trimming strings in non-contiguous spreadsheet ranges"
} | 219533 |
<p>Bukkit/CraftBukkit/Spigot are Minecraft server extenders that allow for creating and using plugins. A particular type of plugin is a generator, which creates the game world. Generators operate chunk-by-chunk, where a chunk is a 16x16x256 area of blocks. First, the generator creates the terrain of the chunk. Then, the generator populates the chunk with extra "stuff." A generator can have any number of populators.</p>
<p>The "problem" with populators is that they may attempt to populate outside of the bounds of the current chunk, so in another chunk. If the other chunk does not yet exist, the generator will then attempt to generate and populate that chunk, and so on until the server crashes from locked threads waiting for all of the neighboring chunks.</p>
<p>My solution is to create a "SafeBlockPopulator" that doesn't attempt population until it is certain that all neighboring chunks exist. It uses a SQLite database to keep track of all of the chunks it has seen, and only actually attempts to populate a given chunk until all neighboring chunks within a given radius exist in the database.</p>
<pre><code>package com.michaelbmorris.generator;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Random;
import org.bukkit.Chunk;
import org.bukkit.World;
import org.bukkit.generator.BlockPopulator;
/**
* Populates a chunk once all surrounding chunks within a radius are generated.
*/
public abstract class SafeBlockPopulator extends BlockPopulator {
private static final HashSet<String> DatabaseUrls = new HashSet<String>();
private static final int DEFAULT_RADIUS = 1;
/*
* Statuses
*/
private static final int STATUS_GENERATED = 0;
private static final int STATUS_POPULATED = 1;
/*
* SQL
*/
private static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS chunkCoordinate (x INTEGER NOT NULL, z INTEGER NOT NULL, status INTEGER NOT NULL, PRIMARY KEY (x, z));";
private static final String DELETE_GENERATED_CHUNKS = "DELETE FROM chunkCoordinate WHERE status = " + STATUS_GENERATED + ";";
private static final String GET_CHUNK = "SELECT * FROM chunkCoordinate WHERE x = ? AND z = ?;";
private static final String GET_GENERATED_CHUNKS = "SELECT * FROM chunkCoordinate WHERE status = " + STATUS_GENERATED + ";";
private static final String INSERT_CHUNK = "INSERT INTO chunkCoordinate (x, z, status) VALUES (?, ?, 0);";
private static final String RESET_CHUNK = "UPDATE chunkCoordinate SET status = " + STATUS_GENERATED + " WHERE x = ? AND z = ?;";
private static final String SET_CHUNK_POPULATED = "UPDATE chunkCoordinate SET status = " + STATUS_POPULATED + " WHERE x = ? AND z = ?;";
private static ResultSet getGeneratedChunks(Connection connection) throws SQLException {
PreparedStatement getGeneratedChunks = connection.prepareStatement(GET_GENERATED_CHUNKS);
return getGeneratedChunks.executeQuery();
}
private static void insertOrResetChunk(int x, int z, Connection connection) throws SQLException {
PreparedStatement getChunk = connection.prepareStatement(GET_CHUNK);
getChunk.setInt(1, x);
getChunk.setInt(2, z);
ResultSet chunk = getChunk.executeQuery();
if (!chunk.next()) {
PreparedStatement insertChunk = connection.prepareStatement(INSERT_CHUNK);
insertChunk.setInt(1, x);
insertChunk.setInt(2, z);
insertChunk.executeUpdate();
} else {
PreparedStatement resetChunk = connection.prepareStatement(RESET_CHUNK);
resetChunk.setInt(1, x);
resetChunk.setInt(2, z);
resetChunk.executeUpdate();
}
}
private final HashMap<String, Chunk> chunks;
private final int radius;
private final String databaseUrl;
/**
* Creates a SafeBlockPopulator with the default radius of 1.
*/
protected SafeBlockPopulator(String databaseUrl, boolean isNew) {
this(databaseUrl, isNew, DEFAULT_RADIUS);
}
/**
* Creates a SafeBlockPopulator with a specified radius.
*/
protected SafeBlockPopulator(String databaseUrl, boolean isNew, int radius) {
if (databaseUrl == null || databaseUrl.isEmpty()) {
throw new IllegalArgumentException("Inheriting block populator must supply a URL for the SQLite database.");
}
if (DatabaseUrls.contains(databaseUrl)) {
throw new IllegalArgumentException("Each populator must have a unique database URL.");
}
if (radius < 1) {
throw new IllegalArgumentException("The radius must be at least 1.");
}
DatabaseUrls.add(databaseUrl);
this.radius = radius;
this.databaseUrl = "jdbc:sqlite:" + databaseUrl;
if (isNew) {
File database = new File(databaseUrl);
database.delete();
}
try (Connection connection = DriverManager.getConnection(this.databaseUrl)) {
Statement statement = connection.createStatement();
statement.execute(CREATE_TABLE);
statement.executeUpdate(DELETE_GENERATED_CHUNKS);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
chunks = new HashMap<String, Chunk>();
}
@Override
public final void populate(World world, Random random, Chunk chunk) {
int x = chunk.getX();
int z = chunk.getZ();
chunks.put(x + " " + z, chunk);
try (Connection connection = DriverManager.getConnection(databaseUrl)) {
insertOrResetChunk(x, z, connection);
attemptPopulate(world, random, connection);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
private void attemptPopulate(World world, Random random, Connection connection) throws SQLException {
ResultSet unpopulatedChunks = getGeneratedChunks(connection);
PreparedStatement setChunkPopulated = connection.prepareStatement(SET_CHUNK_POPULATED);
while (unpopulatedChunks.next()) {
if (unpopulatedChunks.getInt("status") == STATUS_GENERATED) {
int chunkX = unpopulatedChunks.getInt("x");
int chunkZ = unpopulatedChunks.getInt("z");
if (hasSurrounding(connection, chunkX, chunkZ)) {
Chunk chunk;
String key = chunkX + " " + chunkZ;
if (chunks.containsKey(key)) {
chunk = chunks.get(key);
chunks.remove(key);
} else {
chunk = world.getChunkAt(chunkX, chunkZ);
}
actuallyPopulate(world, random, chunk);
setChunkPopulated.setInt(1, unpopulatedChunks.getInt("x"));
setChunkPopulated.setInt(2, unpopulatedChunks.getInt("z"));
setChunkPopulated.executeUpdate();
}
}
}
}
private boolean hasSurrounding(Connection connection, int x, int z) throws SQLException {
PreparedStatement getChunk = connection.prepareStatement(GET_CHUNK);
ResultSet resultSet;
for (int i = 0 - radius; i <= radius; i++) {
for (int j = 0 - radius; j <= radius; j++) {
getChunk.setInt(1, x + i);
getChunk.setInt(2, z + j);
resultSet = getChunk.executeQuery();
if (!resultSet.next()) {
return false;
}
}
}
return true;
}
/**
* Actually populates this chunk once all surrounding chunks within the radius
* are generated.
*/
protected abstract void actuallyPopulate(World world, Random random, Chunk chunk);
}
</code></pre>
<p>This obviously causes somewhat reduced performance. The database interactions are costly compared to keeping track of the data in memory, but persistence is required for when the server restarts. Theoretically, it would be nice to load all the data from the database on startup and save it all back on shutdown, but there's no guarantee that the server will be shutdown correctly. I do have to keep the chunks themselves in memory because there's another bug in the server that causes chunks to be "forgotten" if they are generated but not populated for a while. That's why I delete all generated but not populated chunks from the database on startup; the server consistently sends all of them through again.</p>
<p>Larger radii decrease performance as well, but it's up to the author of the inheriting class to determine how much room their populator implementation needs.</p>
<p>Is there any way to optimize/reduce my database calls while still ensuring that all data is persisted immediately? In particular, I'm looking at the <code>hasSurrounding()</code> method that makes <code>(2 * radius + 1)^2</code> amount of database calls. Are there any other improvements I could make?</p>
| [] | [
{
"body": "<p>Your algorithm by example: In your method hasSurrounding(), you are executing a query for each point. If for example you have current x=100 and current z=1000 and surrounding=10, you are examining every point between x=90 to 109 and z=990 to 1009. That makes 10*10 = 100 queries. If one of these points do not exists, you immediately return false.</p>\n\n<p>You can do that in one query, given example values above: </p>\n\n<pre><code>SELECT * FROM chunkCoordinate WHERE x >= 90 AND x < 110 AND z >= 990 and z < 1009\n</code></pre>\n\n<p>But because you do not need to know which point(s) does not exist, you can just count the number of points. If one is missing, you would receive 99 instead of 100 results.\nThat leads to high performance since the database does not need to fetch the data for the point, but just needs to check if it exists, by using its buffered index tables (primary keys).</p>\n\n<p>Changed code:</p>\n\n<pre><code>private boolean hasSurrounding(Connection connection, int x, int z) throws SQLException {\n String CHECK_SURROUNDING = \"SELECT COUNT(*) FROM chunkCoordinate WHERE x >= ? AND x < ? AND z >= ? and z < ?;\";\n PreparedStatement getChunkCount = connection.prepareStatement(CHECK_SURROUNDING);\n getChunkCount.setInt(1, x - radius);\n getChunkCount.setInt(2, x + radius);\n getChunkCount.setInt(3, z - radius);\n getChunkCount.setInt(4, z + radius);\n\n ResultSet resultSet = getChunkCount.executeQuery(); \n if (! resultSet.next()) {\n throw new IllegalStateException(\"Could not get the record count to check surrounding. Check if table 'chunkCoordinate' exists.\");\n }\n\n int numberOfRows = rs.getInt(1);\n return (numberOfRows == radius * radius);\n}\n</code></pre>\n\n<p>Another method is to use a cache: read the whole table into an arraylist and only operate on that. You will need a flag (or version number) to know when the table is modified and needs to be read again. There are java libraries out there that already do that for you.</p>\n\n<p>Remarks:</p>\n\n<ul>\n<li>Some databases have a BETWEEN operator. Try if it is faster.</li>\n<li>regarding real-time checks: If you execute 100 queries for checking the surrounding one after the other, it will take some time. It may happen that one point got deleted during this time that was there some milliseconds before you checked or vice versa, leading to wrong results. With a single query like above this cannot happen. But if in your code you have no choice than executing many queries, you should accumulate the results in an intermediate table and return that. In other words: using subqueries withing your single query.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T14:11:41.263",
"Id": "219640",
"ParentId": "219535",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-01T22:46:54.570",
"Id": "219535",
"Score": "2",
"Tags": [
"java",
"sql",
"sqlite",
"plugin",
"minecraft"
],
"Title": "SafeBlockPopulator to ensure neighboring chunks are generated before population"
} | 219535 |
<p>Asked this on StackOverflow, not knowing that this would be a better place for the question... </p>
<p>I've managed to figure out a script in js to hide and show various elements. But, I imagine there must be a cleaner/simpler way to do this that what I've created? (without using jquery). </p>
<p>Essentially, I'm just using an eventlistener to catch clicks and individual 'getElementbyID' - to my beginner understanding, it seemed like using queryselectorAll would have actually created more lines (at least by the examples I saw. I might've misunderstood)</p>
<p>Here's what I did: </p>
<p>Side note: I also noticed I was getting an error at the end.. I need to add an if exists statement, but didn't yet, just in case someone knows a cleaner way to do this.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// show/hide questions & divs on click of 'NEXT' button
var nextquestion = document.getElementsByClassName('btnnext');
for (let i = 0; i < nextquestion.length; i++) {
nextquestion[i].addEventListener("click", function() {
str = nextquestion[i].id;
var closefield = str.replace("btnnext", "questionbox");
var closebtn = nextquestion[i].id;
var closebtnprev = str.replace("btnnext", "btnprev");
document.getElementById(closefield).style.display = 'none';
document.getElementById(closebtn).style.display = 'none';
var isthere = document.getElementById(closebtnprev);
if (isthere !== null) {
document.getElementById(closebtnprev).style.display = 'none';
};
var openfield = "questionbox-" + (parseFloat(str.substring(str.indexOf("-") + 1)) + 1).toString();
var openbtn = "btnnext-" + (parseFloat(str.substring(str.indexOf("-") + 1)) + 1).toString();
var openbtnprev = "btnprev-" + (parseFloat(str.substring(str.indexOf("-") + 1)) + 1).toString();
document.getElementById(openfield).style.display = 'block';
document.getElementById(openbtn).style.display = 'table';
document.getElementById(openbtnprev).style.display = 'table';
});
};
// show/hide questions & divs on click of 'PREVIOUS' button
var prevquestion = document.getElementsByClassName('btnprev');
for (let i = 0; i < prevquestion.length; i++) {
prevquestion[i].addEventListener("click", function() {
strprev = prevquestion[i].id;
var closefield2 = strprev.replace("btnprev", "questionbox");
var closebtn2 = strprev.replace("btnprev", "btnnext");
var closeprevbtn2 = "btnprev-" + parseFloat(strprev.substring(str.indexOf("-") + 1)).toString();
document.getElementById(closefield2).style.display = 'none';
document.getElementById(closebtn2).style.display = 'none';
var isthere = document.getElementById(closeprevbtn2);
if (isthere !== null) {
document.getElementById(closeprevbtn2).style.display='none';
};
var openfield2 = "questionbox-" + (parseFloat(strprev.substring(strprev.indexOf("-") + 1)) - 1).toString();
var openbtn2 = "btnnext-" + (parseFloat(strprev.substring(strprev.indexOf("-") + 1)) - 1).toString();
var openprevbtn2 = "btnprev-" + (parseFloat(strprev.substring(str.indexOf("-") + 1)) - 1).toString();
document.getElementById(openfield2).style.display = 'block';
document.getElementById(openbtn2).style.display = 'table';
// document.getElementById(openprevbtn2).style.display = 'table';
var isthere2 = document.getElementById(openprevbtn2);
if (isthere2 !== null) {
document.getElementById(openprevbtn2).style.display='table';
};
});
};</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.quizholder form {
display:flex;
flex-wrap: wrap;
}
.selectables{
border:1px solid #ccc;
background:#faf1d3;
border-radius: 1px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
min-width:90%;
padding: 8px 16px !important;
}
.selectables:hover {
background-color: #ffffff;
cursor: pointer;
}
.questionbox {
flex:3;
}
.btnnext {
flex:1;
background:#d15d21;
padding:.5em;
color:#ffffff;
font-weight:900;
text-align:center;
font-family: 'Helvetica', arial, sans-serif;
font-size:.9em;
}
.btnnext:hover {
background:#f36921;
-webkit-transition: all .5s;
/* Safari */
transition: all .5s;
}
#btnnext-0 {
display:table;
}
#questionbox-1, #questionbox-2, #questionbox-3, #btnnext-1, #btnnext-2, #btnnext-3, #btnprev-1, #btnprev-2 {
display:none;
}
.btnprev {
border: 1px solid #ccc;
padding: .25em;
flex:1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="quizholder">
<form action="" method="post">
<div class="questionbox" id="questionbox-0"><label for="dropdown0">Dropdown ONE</label>
<br />
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select...</option>
<option value="10">Choice 1 (plus 10)</option>
<option value="-5">Choice 2 (minus 5)</option>
<option value="60">Choice 3 (plus 60)</option>
</select>
</div>
<div class="btnnext" id="btnnext-0">Next question
</div>
&nbsp;
<div class="btnprev" id="btnprev-1">go back to 1
</div>
<div class="questionbox" id="questionbox-1"><label for="dropdown1">Dropdown TWO</label>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select...</option>
<option value="8">Choice A (plus 8)</option>
<option value="-10">Choice B (minus 10)</option>
<option value="15">Choice C (plus 15)</option>
</select>
</div>
<div class="btnnext" id="btnnext-1">Next question
</div>
&nbsp;
<div class="btnprev" id="btnprev-2">go back to 2
</div>
<div class="questionbox" id="questionbox-2"><label for="dropdown2">Dropdown THREE</label>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select...</option>
<option value="-20">Choice ii (- 20)</option>
<option value="15">Choice ii (plus 15)</option>
<option value="12">Choice iii (plus 12)</option>
</select>
</div>
<div class="btnnext" id="btnnext-2">Next question
</div>
<div class="questionbox" id="questionbox-3">
<input type="submit" value="Submit" />
</div>
</form>
</div></code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T00:33:42.653",
"Id": "219539",
"Score": "1",
"Tags": [
"javascript",
"html"
],
"Title": "Show & hide multiple elements - vanilla js"
} | 219539 |
<p>I have the following code to filter some items by the keys. </p>
<pre><code>const keys = Object.keys(cars.plans)
let filteredPlans = [];
for (const key of keys) {
if (key !== "1" && key !== "2") {
filteredPlans.push (cars.plans[key])
}
}
</code></pre>
<p>I am trying to find a more React / efficient way of doing this.</p>
<p>Note that I can't change the data structure as it's provided by an external API. I need a better way of filtering the data by keys.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T00:53:54.927",
"Id": "424047",
"Score": "1",
"body": "What would you consider \"better\"? Can you clarify that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:19:51.930",
"Id": "424053",
"Score": "1",
"body": "Apart from avoiding the need for the `keys` reference (`for (const key of Object.keys(phone.plans)){` ) you are not going to get any more efficient. You could do `filtered = Object.keys(phone.plans).reduce((arr,key)=>(key != 6 && key != 7 ? arr.push(phonePlans[key] : 0, arr), [])` though you will find it a tiny little bit slower than how you do it already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:07:47.277",
"Id": "424056",
"Score": "0",
"body": "@1201ProgramAlert : Either more maintainable or more efficient, ie by using built-in functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-26T07:54:27.253",
"Id": "451166",
"Score": "0",
"body": "Use Filter and map on the array of keys provided by `Object.keys()` on `cars.plans` const filteredPlans = Object.keys(cars.plans) .filter(key => key !== \"1\" && key !== \"2\") .map(key => cars.plans[key]);"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T00:47:56.450",
"Id": "219540",
"Score": "0",
"Tags": [
"javascript",
"react-native"
],
"Title": "React filtering by key strings"
} | 219540 |
<p>The weekly coding challenge in Eric Normand's newsletter this week involves implementing <a href="https://en.wikipedia.org/wiki/Langton%27s_ant" rel="nofollow noreferrer">Langton's ant</a>.</p>
<p>I wanted something on my screen so I put together a simple re-frame app. The core functions relating to the ant:</p>
<p><code>world.cljs</code></p>
<pre class="lang-clj prettyprint-override"><code>(ns ant.world)
(defn init-world [width height]
{:width width
:height height
:grid (into [] (repeat height (into [] (repeat width 0))))
:ant-pos [(quot width 2) (quot height 2)]
:ant-dir :up
:stopped? false})
(defn within-bounds? [[row col] width height]
(and (>= row 0) (>= col 0)
(< row width) (< col height)))
(defn turn-right [dir]
(case dir
:up :right
:right :down
:down :left
:left :up))
(defn turn-left [dir]
(case dir
:up :left
:left :down
:down :right
:right :up))
(defn move [[x y] dir]
(case dir
:up [x (dec y)]
:right [(inc x) y]
:down [x (inc y)]
:left [(dec x) y]))
(defn iter-world [{:keys [width height grid
ant-pos
ant-dir
stopped?]
:as world}]
(if (and (not stopped?) (within-bounds? ant-pos width height))
(let [cell-color (get-in grid ant-pos)
is-white? (= cell-color 0)
next-dir (if is-white? (turn-right ant-dir) (turn-left ant-dir))
next-pos (move ant-pos next-dir)
next-grid (assoc-in grid ant-pos (if is-white? 1 0))]
{:width width
:height height
:grid next-grid
:ant-pos next-pos
:ant-dir next-dir
:stopped? false})
(assoc world :stopped? true)))
</code></pre>
<p>And the view:</p>
<p><code>views.cljs</code></p>
<pre class="lang-clj prettyprint-override"><code>(ns ant.views
(:require
[re-frame.core :as re-frame]
[ant.subs :as subs]
[ant.events :as ev]
[cljs.pprint :refer [pprint]]
))
(defn main-panel []
(let [grid (re-frame/subscribe [::subs/grid])]
(into [:table {:style {:border "1px solid red"}}]
(for [row @grid]
(into [:tr]
(for [cell row]
[:td {:width "5px" :height "5px"
:style {:backgroundColor (if (= cell 1) "black" "white")}}]))))))
(defn dispatch-timer-event
[]
(let [now (js/Date.)]
(re-frame/dispatch [::ev/timer now]))) ;; <-- dispatch used
;; Call the dispatching function every second.
;; `defonce` is like `def` but it ensures only one instance is ever
;; created in the face of figwheel hot-reloading of this file.
(defonce do-timer (js/setInterval dispatch-timer-event 50))
</code></pre>
<p>subscriptions:</p>
<p><code>subs.cljs</code></p>
<pre class="lang-clj prettyprint-override"><code>(ns ant.subs
(:require
[re-frame.core :as re-frame]))
(re-frame/reg-sub
::grid
(fn [db]
(:grid db)))
</code></pre>
<p>Events:</p>
<p><code>events.cljs</code></p>
<pre class="lang-clj prettyprint-override"><code>(ns ant.events
(:require
[re-frame.core :as re-frame]
[ant.db :as db]
[ant.world :as aw]
))
(re-frame/reg-event-db
::initialize-db
(fn [_ _]
db/default-db))
(re-frame/reg-event-db
::timer
(fn [db _]
(aw/iter-world db)))
</code></pre>
<p>DB:</p>
<p><code>db.cljs</code></p>
<pre class="lang-clj prettyprint-override"><code>
(ns ant.db
(:require [ant.world :as aw]))
(def default-db
(aw/init-world 100 100))
</code></pre>
<p>This works. But is quite slow. Though the timer is supposed to trigger an event every 50ms, the drawing rate is not so high.</p>
<p>What can I do to improve the performance here? Is it possible without resorting to mutable data structures?</p>
<p>(Any general code improvement suggestions are also most welcome)</p>
<p>Full code is here:
<a href="https://github.com/nakiya/langton-ant/tree/b9b2f3d8a52ac183744a8110b05a69321932a065" rel="nofollow noreferrer">https://github.com/nakiya/langton-ant</a></p>
| [] | [
{
"body": "<p>I don't have any performance related suggestions unfortunately. I do have a couple cleanup suggestions though.</p>\n\n<p>The bounds checking function can be cleaned up a bit by making use of \"comparison chaining\" similar to what you'd use in Pytbon:</p>\n\n<pre><code>(defn within-bounds? [[row col] width height]\n (and (< -1 row width)\n (< -1 col height)))\n</code></pre>\n\n<hr>\n\n<p>In the iteration function, you have</p>\n\n<pre><code>{:width width\n :height height\n :grid next-grid\n :ant-pos next-pos\n :ant-dir next-dir\n :stopped? false}\n</code></pre>\n\n<p>This is less than ideal for a few reasons</p>\n\n<ul>\n<li><p>You're reassociating entries that already exist in the map. This is unlikely to effect performance, but causes unneeded code bloat. It also creates a potential source of bugs if you add a new entry into the game state. Will you remember to update the map retuned by the function? I'd use <code>assoc</code> here instead.</p></li>\n<li><p>You're associating <code>false</code> with the <code>:stopped?</code> key. Following the logic of the function though, it must already be falsey there.</p></li>\n</ul>\n\n<p>I'd just write</p>\n\n<pre><code>(assoc world :grid next-grid\n :ant-pos next-pos\n :ant-dir next-dir}\n</code></pre>\n\n<hr>\n\n<p>In <code>init-world</code>, you're using <code>(into [])</code> to convert to vectors. This can be written slightly neater using <code>vec</code>.</p>\n\n<pre><code>:grid (vec (repeat height\n (vec (repeat width 0))))\n</code></pre>\n\n<p>I also typically space this code out like I have above (I actually write this exact code fairly often).</p>\n\n<hr>\n\n<p>This is entirely subjective, but instead of maintaining a <code>:stopped?</code> flag, I prefer to use a <code>:running?</code> one instead (the logic is flipped). I find it tends to lead to easier to read code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T15:45:58.743",
"Id": "219591",
"ParentId": "219545",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T03:00:15.327",
"Id": "219545",
"Score": "4",
"Tags": [
"performance",
"animation",
"clojure",
"cellular-automata",
"clojurescript"
],
"Title": "Langton's ant in Clojurescript"
} | 219545 |
<p>I had the following interview question: Given an array of integers, for each member of the array find the product of all the other members of the array. So for instance, if you have this array:</p>
<pre><code>{3, 1, 2, 0, 4}
</code></pre>
<p>you should end up with this:</p>
<pre><code>{0 0 0 24 0}
</code></pre>
<p>I wrote this code which uses two loops, but I couldn't come up with a solution with just one loop. Can anyone help me?</p>
<pre><code>public int[] findProducts(int[] arr) {
int[] products = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
int product = 1;
for (int j = 0; j < arr.length; j++) {
if (i != j) {
product *= arr[j];
}
}
products[i] = product;
}
return products;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:04:57.667",
"Id": "424055",
"Score": "0",
"body": "Was your solution rejected because you used two nested loops?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T17:35:57.317",
"Id": "424123",
"Score": "0",
"body": "Well, the interviewer acknowledged that this situation would work, but he also asked if there was a more efficient way to do it, and I was at a loss, hence my bringing the problem here."
}
] | [
{
"body": "<p>This could be done with two consecutive loops (instead of nested loops), making it O(N) instead of O(N^2).</p>\n\n<p>In the first loop you calculate the total product of all non-zero elements (and the number of zeros).</p>\n\n<p>If there are more than one zero, return result as is, since all elements already default to zero.</p>\n\n<p>In the second you either set the result element to zero or to total product divided by the current element depending on the number of zeros in the data and the value of the current element.</p>\n\n<p>BTW, There are a lot of blog posts and even some research written about the pointlessness of this kind of interview questions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T17:34:34.953",
"Id": "424122",
"Score": "0",
"body": "Thanks for the help. I would agree that this question does seem pretty pointless. How often does this kind of situation occur in a real-world application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T07:46:32.343",
"Id": "424187",
"Score": "0",
"body": "@Frank Situations like these do occur, but the difference is that in real life nobody ever has to solve them in such a short and stressful scenario as job interview is. And in real life you're usually given more limitations (e.g. told that there will be a million entries instead of five so you're already prepared for writing the code with efficiency in mind)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:12:54.530",
"Id": "219555",
"ParentId": "219546",
"Score": "2"
}
},
{
"body": "<p>This could also be done using a single for loop in a recursive method that can calculate for each member of the array the product of all the other members of the array .</p>\n\n<p>this can be done like this .</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class ArrayElementsProduct {\n private int[] originalArray = {3, 1, 2, 0, 4};\n private int[] productsArray = {1, 1, 1, 1, 1};\n private int j = 0; // j is used to recursion the method product() only uptill the last element in productArray\n\n\n public static void main(String[] args) {\n new ArrayElementsProduct().product();//created an anonymous object of ArrayElementsProduct and calling method product() through it.\n }\n\n private void product() {\n for (int i = 0; i < originalArray.length; i++) {\n if (j != i) {\n productsArray[j] *= originalArray[i];//multiplying the originalArray elements and storing them in productArray\n }\n }\n j++;\n if (j < productsArray.length) {\n product(); //recursing the method product\n } else {\n System.out.println(Arrays.toString(productsArray));\n }\n }\n}\n</code></pre>\n\n<p>Recursion basically works like a loop itself , this is just an idea that came in my mind for the question , i am just a beginner in Java .</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T09:43:51.730",
"Id": "219630",
"ParentId": "219546",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "219555",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T03:31:52.373",
"Id": "219546",
"Score": "3",
"Tags": [
"java",
"algorithm",
"array"
],
"Title": "Finding products of all other members of an array"
} | 219546 |
<p>I am new to <code>TeX</code> and here is my attempt to (ab)use <code>mfirstuc</code> to define an environment that counts the words. I am looking for suggestions on how to improve the implementation.</p>
<pre class="lang-latex prettyprint-override"><code>\documentclass{article}
\usepackage{mfirstuc}
\newcounter{wordcount}
%Make sure we don't accidentally overwrite things with \def and \let
\newcommand\cwaux\relax
\newcommand\oldgmfu\relax
\newcommand\temppar\relax
%
\newtoks\temppar
\def\cwaux#1\par{\capitalisewords{#1}\par}
\newcommand*\myglsmakefirstuc[1]{\stepcounter{wordcount}#1}
\newenvironment{countwords}{%
\setcounter{wordcount}{0}\let\oldgmfu\glsmakefirstuc\let\glsmakefirstuc\myglsmakefirstuc\temppar\everypar\everypar{\cwaux}%
}{%
\everypar\temppar\let\glsmakefirstuc\oldgmfu Word count:\arabic{wordcount}%
}
\begin{document}
\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}
\begin{countwords}
One paragraph.
Another paragraph which is longer.
\end{countwords}
\begin{countwords}
The third paragraph.
I am glad to see this works.
\end{countwords}
\capitalisewords{Outside the environment, \texttt{\textbackslash capitalisewords} works normally.}
\end{document}
</code></pre>
<p><a href="https://i.stack.imgur.com/vHvaG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vHvaG.png" alt="Pdf file rendered"></a></p>
| [] | [
{
"body": "<p>You can do it in a more robust way, using <code>expl3</code>.</p>\n\n<pre class=\"lang-latex prettyprint-override\"><code>\\documentclass{article}\n\\usepackage{xparse}\n\\usepackage{mfirstuc}\n\n\\ExplSyntaxOn\n\\NewDocumentEnvironment{countwords}{+b}\n {\n % typeset the contents and add \\par at the end\n #1 \\par\n\n % save the contents of the environment in a token list variable\n \\tl_set:Nn \\l_tmpa_tl { #1 }\n % blank lines generate a \\par, change it into a space\n \\tl_replace_all:Nnn \\l_tmpa_tl { \\par } { ~ }\n % split the token list at spaces\n \\seq_set_split:NnV \\l_tmpa_seq { ~ } \\l_tmpa_tl\n % remove blank items\n \\seq_remove_all:Nn \\l_tmpa_seq { }\n % print the word count\n Word~count:~\\int_to_arabic:n { \\seq_count:N \\l_tmpa_seq }\n }{}\n\\ExplSyntaxOff\n\n\\begin{document}\n\n\\capitalisewords{Outside the environment, \\texttt{\\textbackslash capitalisewords} works normally.}\n\n\\begin{countwords}\nOne paragraph.\n\nAnother paragraph which is longer.\n\n\\end{countwords}\n\n\\begin{countwords}\nThe third paragraph.\n\nI am glad to see this works.\n\\end{countwords}\n\n\\capitalisewords{Outside the environment, \\texttt{\\textbackslash capitalisewords} works normally.}\n\n\\end{document}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/y3IH7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y3IH7.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-25T23:01:21.887",
"Id": "221023",
"ParentId": "219554",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221023",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T05:58:24.050",
"Id": "219554",
"Score": "8",
"Tags": [
"tex"
],
"Title": "A LaTeX environment that counts words"
} | 219554 |
<p>When creating data-driven tests with <code>xUnit</code> we can use the <a href="http://ikeptwalking.com/writing-data-driven-tests-using-xunit/" rel="nofollow noreferrer"><code>MemberDataAttribute</code></a> to get the data from a member of this or other class. This is very nice but it has one disadvantage, you have to specify parameters in the same order as the test method so you need to be very careful. I prefer to use names for that purpose because my data-items already have them so I'd like to reuse them with the test signature.</p>
<hr>
<h3><code>SmartMemberDataAttribute</code></h3>
<p>In order to make it work this way I created my own <code>SmartMemberDataAttribute</code>. I think it's <em>smart</em> because it can not only match data-item and parameters by name but at the same time it's case-insensitive and also validates whether data-item values can be assigned to the parameters or are optional.</p>
<p><em><strong>Warning</strong>: <a href="https://codereview.stackexchange.com/questions/177172/compiling-and-throwing-simple-dynamic-excepitons-at-runtime"><code>DynamicException</code></a>s at work here! Please ignore this question if you don't like them ;-]</em></p>
<p>Yes, this code throws three <code>DynamicException</code>s to make debugging easier in case I made a mistake and gave properties or parameters non-matching names or used incompatible types.</p>
<pre><code>[DataDiscoverer("Xunit.Sdk.MemberDataDiscoverer", "xunit.core")]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class SmartMemberDataAttribute : MemberDataAttributeBase
{
public SmartMemberDataAttribute(string memberName, params object[] parameters) : base(memberName, parameters) { }
protected override object[] ConvertDataItem(MethodInfo testMethod, object item)
{
try
{
return CreateDataItem(testMethod, item);
}
catch (Exception inner)
{
throw DynamicException.Create
(
$"DataItemConversion",
$"Could not convert '{item.GetType().ToPrettyString()}' for '{GetTestMethodInfo()}'. See the inner exception for details.",
inner
);
}
// Creates text: MyTest.TestMethod
string GetTestMethodInfo() => $"{testMethod.DeclaringType.ToPrettyString()}.{testMethod.Name}";
}
private static object[] CreateDataItem(MethodInfo testMethod, object item)
{
var itemProperties = item.GetType().GetProperties().ToDictionary(p => p.Name, p => p, SoftString.Comparer);
var testMethodParameters = testMethod.GetParameters();
var dataItem = new object[testMethodParameters.Length];
// We need the index to set the correct item in the result array.
foreach (var (testMethodParameter, i) in testMethodParameters.Select((x, i) => (x, i)))
{
if (itemProperties.TryGetValue(testMethodParameter.Name, out var itemProperty))
{
if (testMethodParameter.ParameterType.IsAssignableFrom(itemProperty.PropertyType))
{
dataItem[i] = itemProperty.GetValue(item);
}
else
{
throw DynamicException.Create
(
$"ParameterTypeMismatch",
$"Cannot assign value of type '{itemProperty.PropertyType.ToPrettyString()}' " +
$"to the parameter '{testMethodParameter.Name}' of type '{testMethodParameter.ParameterType.ToPrettyString()}'."
);
}
}
else
{
if (testMethodParameter.IsOptional)
{
dataItem[i] = testMethodParameter.DefaultValue;
}
else
{
throw DynamicException.Create
(
$"ParameterNotOptional",
$"Data item does not specify the required parameter '{testMethodParameter.Name}'."
);
}
}
}
return dataItem;
}
}
</code></pre>
<hr>
<h3>Example</h3>
<p>I use it the same way as the original attribute:</p>
<blockquote>
<pre><code>[Theory]
[SmartMemberData(nameof(GetData))]
public void Can_evaluate_supported_expressions(string useCaseName, object expected, bool throws)
{
var useCase = _helper.GetExpressions().Single(e => e.Name == useCaseName);
ExpressionAssert.Equal(expected, useCase, ctx => ctx.WithReferences(_helper.GetReferences()), _output, throws);
}
</code></pre>
</blockquote>
<p>It gets the data from anonymous-objects like this one that I create from tuples:</p>
<blockquote>
<pre><code>public static IEnumerable<object> GetData() => new (string UseCaseName, object Expected, bool Throws)[]
{
("Any", true, false),
("Sum", 3.0, false),
("ToDouble", 1.0, false),
("True.Not", false, false),
("Double.ToDouble", 1.0, true),
// ... more use cases
}.Select(uc => new { uc.UseCaseName, uc.Expected, uc.Throws });
</code></pre>
</blockquote>
<hr>
<p>What do you say? Is this solution robust enough and debug-friendly? Can it be even <em>smarter</em>?</p>
| [] | [
{
"body": "<p>I would use a relaxation on type matching. Since an entire type conversion API is available in the .NET Framework, why not take advantage of it?</p>\n\n<blockquote>\n<pre><code>if (testMethodParameter.ParameterType.IsAssignableFrom(itemProperty.PropertyType))\n{\n dataItem[i] = itemProperty.GetValue(item);\n}\nelse\n{\n throw DynamicException.Create\n (\n $\"ParameterTypeMismatch\", \n $\"Cannot assign value of type '{itemProperty.PropertyType.ToPrettyString()}' \" +\n $\"to the parameter '{testMethodParameter.Name}' of type '{testMethodParameter.ParameterType.ToPrettyString()}'.\"\n );\n}\n</code></pre>\n</blockquote>\n\n<p>You can still decide to wrap it with an exception handler and do some trickery with Nullable and Null-assignable type checks <a href=\"https://codereview.stackexchange.com/questions/221012/extending-identityuser-with-nullable-foreign-key-to-another-identityuser/221013#221013\">like here</a>.</p>\n\n<pre><code>dataItem[i] = Convert.ChangeType(itemProperty.GetValue(item), testMethodParameter.ParameterType);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-01T05:03:26.640",
"Id": "432586",
"Score": "0",
"body": "_Since an entire type conversion API is available in the .NET Framework, why not take advantage of it?_ - because it's only a utility with very limited capabilities. Frameworks are extendable and this one isn't :-( I find tests should be very strict about the data they use. _Invisible_ conversions may result in false positives suggesting that the code under test can work with a certain type of data where in fact it's the helper that converts it. The only resposibility of this attribute should be to assign values to matching parameters. Anything else would violate the SRP."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-30T20:26:45.653",
"Id": "223256",
"ParentId": "219556",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:13:36.893",
"Id": "219556",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"reflection",
"xunit",
"ddt"
],
"Title": "Assigning test-data parameters by name"
} | 219556 |
xUnit.net is a free, open source, community-focused unit testing tool for the .NET Framework | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T06:15:26.853",
"Id": "219558",
"Score": "0",
"Tags": null,
"Title": null
} | 219558 |
<p>I have a modelScan.php file, as you can see,</p>
<p>I have codes that repeated within the function/method. How can I make this code more readable?</p>
<pre><code><?php
/**
* Class for Scanning files
*/
class modelScan
{
/**
* Get the total size of file in the directory
* @param string $sPath and integer $iTotalCount
*/
public function getBytesTotal($sPath, $iTotalCount)
{
$sPath = realpath($sPath);
if($sPath!==false && $sPath!='' && file_exists($sPath)){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sPath, FilesystemIterator::SKIP_DOTS)) as $oObject){
$iTotalCount += $oObject->getSize();
}
}
return $iTotalCount;
}
/**
* Get the total files in the directory
* @param string $sPath and integer $iTotalCount
*/
public function getFilesTotal($sPath, $iTotalCount)
{
$ite = new RecursiveDirectoryIterator($sPath);
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
if(is_file($cur)){
$iTotalCount++;
}
}
return $iTotalCount;
}
/**
* Get the total Class in the directory
* @param string $sPath and integer $iTotalCount
*/
public function getClassTotal($sPath, $iTotalCount)
{
$ite = new RecursiveDirectoryIterator($sPath);
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
if(is_file($cur)){
$fileToString = file_get_contents($cur);
$token = token_get_all($fileToString);
$tokenCount = count($token);
//Class Count
$sPathInfo = pathinfo($cur);
if ($sPathInfo['extension'] === 'php') {
for ($i = 2; $i < $tokenCount; $i++) {
if ($token[$i-2][0] === T_CLASS && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING ) {
$iTotalCount++;
}
}
} else {
error_reporting(E_ALL & ~E_NOTICE);
}
}
}
return $iTotalCount;
}
/**
* Get the total Method in the directory
* @param string $sPath and integer $iTotalCount
*/
public function getMethodTotal($sPath, $iTotalCount)
{
$ite = new RecursiveDirectoryIterator($sPath);
foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
if(is_file($cur)){
$fileToString = file_get_contents($cur);
$token = token_get_all($fileToString);
$tokenCount = count($token);
//Method Count
$sPathInfo = pathinfo($cur);
if ($sPathInfo['extension'] === 'php') {
for ($i = 2; $i < $tokenCount; $i++) {
if ($token[$i-2][0] === T_FUNCTION) {
$iTotalCount++;
}
}
} else {
error_reporting(E_ALL & ~E_NOTICE);
}
}
}
return $iTotalCount;
}
}
</code></pre>
| [] | [
{
"body": "<p>Welcome to Code Review. Your code is understandable, so we can, more or less, figure out what it does, but it is always nice for reviewers to hear you say what you use a piece of code for, what its purpose is, what the code itself specifically does, and to have some usage examples. This also helps you to reflect on the choices you made.</p>\n\n<p>I couldn't get your <code>getClassTotal()</code> and <code>getMethodTotal()</code> to work. They assume that all the files are PHP files, and in my test directory they are not. You should have checked the PHP file extension before tokenizing the file content.</p>\n\n<p>From what I can see this looks like a class that wraps four independent function. That only doesn't justify the existence of this class. Is there nothing common to these functions? I think we can agree that the <code>RecursiveDirectoryIterator</code> and <code>RecursiveIteratorIterator</code> are present in all four, so I made that part of the class.</p>\n\n<p>There are also some simplifications I added in the file and bytes counter. </p>\n\n<p>Using the build-in PHP tokenizer was a good idea, but clearly the way that classes and methods are counted is very similar. So I created a new method which will count either. I don't see the point of checking for a class name, so I left that bit out.</p>\n\n<p>In your code a counter is the second argument to all four method. I fail to see why this is a good thing. I dropped it.</p>\n\n<p>This gives me the following code:</p>\n\n<pre><code><?php\n\nclass DirectoryScanner\n{\n private $files;\n\n public function __construct($path)\n {\n $dirIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);\n $this->files = new RecursiveIteratorIterator($dirIterator);\n }\n\n public function getFileCount()\n {\n return iterator_count($this->files);\n }\n\n public function getBytesUsed()\n {\n $bytes = 0;\n foreach ($this->files as $file) {\n $bytes += $file->getSize();\n }\n return $bytes;\n }\n\n private function getPhpTokenCount($token)\n {\n $counter = 0;\n foreach ($this->files as $file) {\n if ($file->getExtension() == 'php') {\n $contents = file_get_contents($file);\n $tokens = token_get_all($contents);\n $values = array_count_values(array_column($tokens, 0));\n $counter += isset($values[$token]) ? $values[$token] : 0;\n }\n }\n return $counter;\n }\n\n\n public function getPhpClassCount()\n {\n return $this->getPhpTokenCount(T_CLASS);\n }\n\n public function getPhpFunctionCount()\n {\n return $this->getPhpTokenCount(T_FUNCTION);\n }\n}\n\n?>\n</code></pre>\n\n<p>I left out all the comments to save some space. This code can be tested like this:</p>\n\n<pre><code>$path = $_SERVER['DOCUMENT_ROOT'];\n$test = new DirectoryScanner($path);\n\necho 'getFileCount: ' . $test->getFileCount() . '<br>';\necho 'getBytesUsed: ' . $test->getBytesUsed() . '<br>';\necho 'getPhpClassCount: ' . $test->getPhpClassCount() . '<br>';\necho 'getPhpFunctionCount: ' . $test->getPhpFunctionCount() . '<br>';\n</code></pre>\n\n<p>In my code I take advantage of what a class is: An piece of code in which you share fields and methods in a local scope. I made <code>$files</code> and <code>getPhpTokenCount()</code> private intentionally to stress this point.</p>\n\n<p>I think the first two methods have little in common with the last three. So I would split this up in two classes, like so:</p>\n\n<pre><code>class DirectoryScanner\n{\n protected $files;\n\n public function __construct($path)\n {\n $dirIterator = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);\n $this->files = new RecursiveIteratorIterator($dirIterator);\n }\n\n public function getFileCount()\n {\n return iterator_count($this->files);\n }\n\n public function getBytesUsed()\n {\n $bytes = 0;\n foreach ($this->files as $file) {\n $bytes += $file->getSize();\n }\n return $bytes;\n }\n}\n\n\nclass PhpFilesScanner extends DirectoryScanner\n{\n\n public function getPhpTokenCount($token)\n {\n $counter = 0;\n foreach ($this->files as $file) {\n if ($file->getExtension() == 'php') {\n $contents = file_get_contents($file);\n $tokens = token_get_all($contents);\n $values = array_count_values(array_column($tokens, 0));\n $counter += isset($values[$token]) ? $values[$token] : 0;\n }\n }\n return $counter;\n }\n\n\n public function getPhpClassCount()\n {\n return $this->getPhpTokenCount(T_CLASS);\n }\n\n public function getPhpFunctionCount()\n {\n return $this->getPhpTokenCount(T_FUNCTION);\n }\n}\n\n?>\n</code></pre>\n\n<p>It just makes more sense this way. Note that <code>PhpFilesScanner</code> does rely on <code>DirectoryScanner</code> for the iterator functionality.</p>\n\n<p>I think, depending on your usage, that result buffering would be a nice addition to these classes. For instance, by once buffering alle the token counts, the <code>PhpFilesScanner</code> class can return multiple requests for counts of certain tokens much quicker. Especially if you expand it to include more types of tokens. Buffering would make the class look something like this:</p>\n\n<pre><code>class PhpFileScanner extends DirectoryScanner\n{\n private $tokenCounts = [];\n\n public function __construct($path)\n {\n parent::__construct($path);\n foreach ($this->files as $file) {\n if ($file->getExtension() == 'php') {\n $contents = file_get_contents($file);\n $tokens = token_get_all($contents);\n $counts = array_count_values(array_column($tokens, 0));\n foreach ($counts as $token => $count) {\n if (!isset($this->tokenCounts[$token])) {\n $this->tokenCounts[$token] = 0;\n }\n $this->tokenCounts[$token] += $count;\n }\n }\n }\n }\n\n public function getPhpClassCount()\n {\n return $this->tokenCounts[T_CLASS] ?? 0;\n }\n\n public function getPhpFunctionCount()\n {\n return $this->tokenCounts[T_FUNCTION] ?? 0;\n }\n}\n</code></pre>\n\n<p>The <code>??</code> is the new <a href=\"https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op\" rel=\"nofollow noreferrer\">Null coalescing operator</a> of PHP 7.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T23:04:55.280",
"Id": "424158",
"Score": "0",
"body": "+1 simply for introducing me to the `??` operator! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T08:53:49.937",
"Id": "424203",
"Score": "0",
"body": "I will mark it as acceptable answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:38:23.477",
"Id": "219582",
"ParentId": "219560",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:19:12.760",
"Id": "219560",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"file-system"
],
"Title": "PHP class for scanning filesystem"
} | 219560 |
DDT stands for Data Driven Testing. It is a test design and execution strategy where tests receive their test data from data sources like file, database, etc.. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T07:29:27.490",
"Id": "219562",
"Score": "0",
"Tags": null,
"Title": null
} | 219562 |
<p>I'm trying to copy files to S3 after writing them locally:
I have 2 functions which I need to do this. What is the best way to refactor the code that exists in both.</p>
<pre><code> s3 = False
if data_fp.lower().startswith('s3://'):
s3_data_fp = data_fp
data_fp = os.path.join(_TMP, os.path.basename(data_fp))
s3 = True
</code></pre>
<pre><code>def save_json(data_fp, data, sort_keys=True, indent=4):
s3 = False
if data_fp.lower().startswith('s3://'):
s3_data_fp = data_fp
data_fp = os.path.join(_TMP, os.path.basename(data_fp))
s3 = True
with open(data_fp, 'w') as output_file:
json.dump(data, output_file, cls=NumpyEncoder, sort_keys=sort_keys,
indent=indent)
if s3:
save_in_s3(data_fp, s3_data_fp)
# def save_hdf5(data_fp: str, data: Dict[str, object]):
def save_hdf5(data_fp, data, metadata=None):
s3 = False
if data_fp.lower().startswith('s3://'):
s3_data_fp = data_fp
data_fp = os.path.join(_TMP, os.path.basename(data_fp))
s3 = True
if metadata is None:
metadata = {}
mode = 'w'
if os.path.isfile(data_fp):
mode = 'r+'
with h5py.File(data_fp, mode) as h5_file:
for key, value in data.items():
dataset = h5_file.create_dataset(key, data=value)
if s3:
save_in_s3(data_fp, s3_data_fp)
</code></pre>
| [] | [
{
"body": "<p>The S3-functionality wraps the specific code, which does not change the variables. So how about a decorator?</p>\n\n<pre><code>from functools import wraps\n\ndef handle_s3_upload(fcn):\n @wraps(fcn)\n def inner(data_fp, data, *args, **kwargs):\n # handle S3 path\n s3 = False\n if data_fp.lower().startswith('s3://'):\n s3_data_fp = data_fp\n data_fp = os.path.join(_TMP, os.path.basename(data_fp))\n s3 = True\n # call decorated function\n fcn(data_fp, data, *args, **kwargs)\n # S3 upload\n if s3:\n save_in_s3(data_fp, s3_data_fp)\n return inner\n\n@handle_s3_upload\ndef save_json(data_fp, data, sort_keys=True, indent=4):\n with open(data_fp, 'w') as output_file:\n json.dump(data, output_file, cls=NumpyEncoder, sort_keys=sort_keys,\n indent=indent)\n\n@handle_s3_upload\ndef save_hdf5(data_fp, data, metadata=None):\n if metadata is None:\n metadata = {}\n mode = 'w'\n if os.path.isfile(data_fp):\n mode = 'r+'\n with h5py.File(data_fp, mode) as h5_file:\n for key, value in data.items():\n dataset = h5_file.create_dataset(key, data=value)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T13:16:01.490",
"Id": "219586",
"ParentId": "219563",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219586",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:16:53.197",
"Id": "219563",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"json",
"file",
"amazon-web-services"
],
"Title": "Python functions to save JSON and H5 to local files and S3"
} | 219563 |
<p>I am confused if I can do like this:</p>
<pre><code>$param = "%{$id}%";
$stmt = $conn->prepare("SELECT name, comp, date FROM stats WHERE date = ? AND name LIKE ? ORDER BY date DESC LIMIT 20");
$stmt->bind_param("ss", $param, $_POST['date']);
$stmt->execute();
$result = $stmt->get_result();
$count_rows = $result->num_rows;
$stmt->close(); // CAN I CLOSE IT HERE
while($row = $result->fetch_assoc()){
echo '
<tr>
<td>'.$row['name'].'
<td>'.$row['comp'].'
<td>'.$row['date'].'
</tr>';
}
</code></pre>
<p>Question is can i close <code>$stmt->close();</code> where i do it now or should i close it after while loop?</p>
<p>I tested and it does work but is it wrong?</p>
| [] | [
{
"body": "<p>As soon as you are finished using your <code>$stmt</code> object, it is practical to close it.</p>\n\n<p>However, I find that I am never calling <code>$stmt->close();</code> in any of my projects because php is going to trash them as soon as my script is done anyhow.</p>\n\n<p>Technically, you could have called it one line earlier.</p>\n\n<p>Some leisure reading:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/q/19531195/2943403\">$stmt->close() vs $stmt->free_result()</a></li>\n<li><a href=\"https://stackoverflow.com/q/6631364/2943403\">When to close Prepared Statement</a></li>\n<li><a href=\"https://stackoverflow.com/q/35169146/2943403\">PHP - close prepared stmt</a></li>\n<li><a href=\"https://stackoverflow.com/q/49224638/2943403\">When is the right time to close a prepared statement?</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:49:04.267",
"Id": "424066",
"Score": "0",
"body": "So you say that i can use it before while loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:50:52.957",
"Id": "424067",
"Score": "0",
"body": "Also i did read that if you do not use `$stmt->close();` you could have memory leak?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:51:23.627",
"Id": "424068",
"Score": "0",
"body": "Before `$count_rows = $result->num_rows;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T10:58:51.257",
"Id": "424094",
"Score": "0",
"body": "@Ingus Did you read that online? In that case it is useful to add the link to your comment, otherwise we cannot verify your source. I cannot find any up-to-date source for it. Also, if memory leaks are what you fear, why then do you not use [$result->free()](https://www.php.net/manual/en/mysqli-result.free.php)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:41:01.490",
"Id": "424103",
"Score": "0",
"body": "@KIKOSoftware i did read that in one comment in one page that i cant find anymore. .. Maybe was misread info. I m new to prepared statements so i did not know `free()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T12:46:54.887",
"Id": "424105",
"Score": "0",
"body": "@Ingus Yeah, see that's exactly my point: \"I read somewhere\", probably means you're not sure about it. Programming relies on knowing the exact facts, not on rumor. I did find the term 'memory leak' at the bottom of [this page](https://www.php.net/manual/en/mysqli.close.php), but that's from 10 years ago."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:44:27.120",
"Id": "219570",
"ParentId": "219565",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "219570",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:19:16.200",
"Id": "219565",
"Score": "1",
"Tags": [
"php",
"mysqli"
],
"Title": "Fetching table using mysqli, closing statement before displaying results"
} | 219565 |
<p>There is an interactive program, namely <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/50002102D.pdf" rel="nofollow noreferrer">Microchip Debugger</a> (Later called MDB), which I want to communicate with from NodeJS program. You can think about it as any console-based debugger - they all do the same thing, just with slightly different output/input expectations. This question is about the lowest layer here - launching MDB process and creating an async API, that will be easy to use later, that will abstract away all text processing required on MDB's stdout/stdin.</p>
<p>My ultimate goal for this project is to create a debugger extension for VS Code that will support MDB to program and debug PIC MCUs from VS Code, however this is not what this question is about.</p>
<p>The whole code is available on <a href="https://pastebin.com/CAUAB7RM" rel="nofollow noreferrer">pastebin</a>.</p>
<p>The code is working - successfully debugging a test executable in simulator. However I don't feel very confident about the design which could be much improved - this is my first attempt at this kind of problem and first big Javascipt/Typescript project, hence I ask for review from more experienced programmers. I would like to get feedback primarily on:</p>
<p><strong>Error handling strategy</strong></p>
<pre class="lang-js prettyprint-override"><code>const ERRORS = {
get PROCESS_NOT_RUNNING() { return new Error("Process not running"); },
/* Omitted similar code */
get DEVICE_RUNNING() { return new Error("Device running"); },
};
</code></pre>
<p>I created <code>ERRORS</code> object that is a factory for all errors that might happen. Later I would extend <code>Error</code> class with my own that would also carry some kind of error code (which would live inside an exported object/enum) that would allow the user of the API to differentiate between errors.</p>
<p><strong>Design of the <code>MdbWrapper</code> class'es API</strong></p>
<p>Example function headers:</p>
<ul>
<li><code>public async start(timeoutMs: number = 60000) {</code></li>
<li><code>public async selectDevice(device: string, timeoutMs: number = 60000) {</code></li>
<li><code>public async breakpoint_address(address: number, passCount?: number, timeoutMs: number = 60000): Promise<BreakpointInfo> {</code></li>
</ul>
<p>All functions either reject with error created by <code>ERRORS</code> factory or resolve with whatever is most appropriate or <code>void</code> for simple commands like <code>start</code> or <code>selectDevice</code>. But for most of them the same can be achieved by firing the function and waiting for event. Maybe a better pattern to follow would be creating the API as <code>fire and forget</code> and providing a public convenience function <code>waitForEventsOrTimeout</code> and making all actions fire a unique event upon completion this allowing the user of the API to stall if required.</p>
<p>I don't feel very comfortable with passing this <code>timeoutMs</code> parameter for each function although at the same time and I don't really feel comfortable with all this <code>async</code> and <code>Promise</code> styles. I feel like it's because the API should be shaped differently, are there some patterns that I could follow?</p>
<p><strong>Design of the <code>onData</code> member function</strong></p>
<p>This function is called on <code>data</code> event on processes <code>stdout</code>.</p>
<pre class="lang-js prettyprint-override"><code> private onData = (data: any) => {
type Resolver<T> = {
eventName: string,
args?: (data: T) => any[],
} | ((data: T) => void);
interface ValueHandlerString {
key: string;
resolver: Resolver<string>;
}
interface ValueHandlerRegExp {
key: RegExp;
resolver: Resolver<RegExpExecArray>;
}
const valueHandlers: Array<ValueHandlerString | ValueHandlerRegExp> = [
{ key: '>', resolver: () => {
if (! this._initialized) {
this._initialized = true;
this.emit(MDB_EVENTS.MDB_INITIALIZED);
}
}},
{ key: 'Programming target...', resolver: { eventName: MDB_EVENTS.DEVICE_PRORGRAMING_START } },
{ key: 'Program succeeded.', resolver: () => this._imageLoaded = true },
{ key: 'Program succeeded.', resolver: {eventName: MDB_EVENTS.DEVICE_PRORGRAMING_SUCCESS } },
{ key: 'Running', resolver: { eventName: MDB_EVENTS.DEVICE_RUNNING }},
{ key: 'Running', resolver: () => this._running = true },
{ key: 'HALTED', resolver: {
eventName: MDB_EVENTS.DEVICE_HALT,
args: () => [{...this._haltInfo, breakpoint: this._haltInfo.address === this._lastBreakpoint}]
}},
{ key: 'HALTED', resolver: () => { this._running = false; this._lastBreakpoint = -1; } },
{ key: /^>?Working directory: (.*)$/, resolver: {eventName: MDB_EVENTS.MDB_CHANGE_DIRECTORY, args: (arr: RegExpExecArray) => [arr[1]]}},
{ key: /^>?(W[0-9]{4}-[A-Z]{3}): .*$/, resolver: {eventName: MDB_EVENTS.CONSOLE_WARNING, args: (arr: RegExpExecArray) => [arr[0], arr[1], arr[2]]} },
{ key: /^>?Single breakpoint: @0x([0-9A-F]+)$/, resolver: (arr: RegExpExecArray) => this._lastBreakpoint = parseInt(arr[1], 16) },
{ key: /^>?Breakpoint ([0-9]+) at 0x([0-9a-f]+).$/, resolver: {
eventName: MDB_EVENTS.DEVICE_BREAKPOINT_SET,
args: (arr: RegExpExecArray) => [{ id: parseInt(arr[1], 10), address: parseInt(arr[2], 16) }]
}},
{ key: /^>?Breakpoint ([0-9]+) at function (.+)\.$/, resolver: {
eventName: MDB_EVENTS.DEVICE_BREAKPOINT_SET,
args: (arr: RegExpExecArray) => [{ id: parseInt(arr[1], 10), function: arr[2] }]
}},
{ key: /^>?Breakpoint ([0-9]+) at file (.+), line ([0-9]+).$/, resolver: {
eventName: MDB_EVENTS.DEVICE_BREAKPOINT_SET,
args: (arr: RegExpExecArray) => [{ id: parseInt(arr[1], 10), file: { name: arr[2], line: parseInt(arr[3], 10) } }]
}},
{ key: 'Stop at', resolver: () => this._haltInfo = {} },
{ key: /^>?address:0x([0-9a-f]+)$/, resolver: (matches: RegExpExecArray) => this._haltInfo.address = parseInt(matches[1], 16) },
{ key: /^>?file:(.+)$/, resolver: (matches: RegExpExecArray) => this._haltInfo.file = matches[1] },
{ key: /^>?source line:([0-9]+)$/, resolver: (matches: RegExpExecArray) => this._haltInfo.line = parseInt(matches[1], 10) },
{ key: /^>?---debug/, resolver: () => null } /* Silence "---debug peripheral accessed" - provide interface for it later */,
{ key: 'Simulator halted', resolver: () => null } /* Silence "Simulator halted" it's the same as HALTED */,
{ key: 'Stepping', resolver: () => this._running = true } /* Silence "Stepping" - it's output after "stepi" command */,
];
const callResolver = <T>(resolver: Resolver<T>, arg: T) => {
if (typeof resolver === 'function') {
resolver(arg);
} else {
const args = resolver.args ? resolver.args(arg) : [];
this.emit(resolver.eventName, ...args);
}
};
const lines = String(data).split("\n").map(line => line.trim()).filter(line => line.length > 0);
lines.forEach(line => {
const altLine = (line[0] === '>') ? line.substring(1) : line;
let handled = false;
for (const handler of valueHandlers) {
if (typeof handler.key === 'string') {
if (line !== handler.key) {
if (altLine === handler.key) {
callResolver((handler as ValueHandlerString).resolver, altLine);
handled = true;
}
} else {
callResolver((handler as ValueHandlerString).resolver, line);
handled = true;
}
} else {
const match = handler.key.exec(line);
if (match) {
callResolver((handler as ValueHandlerRegExp).resolver, match);
handled = true;
}
}
}
if (! handled) {
console.warn("Unhandled line", line);
}
});
}
</code></pre>
<p>This function encapsulates a lot of logic that boils down to:</p>
<ul>
<li>For each line from stdout</li>
<li>Match it to each <code>valueHandler</code> either using regex or simple string compare. Note that <code>MDB</code> sometimes emits <code>></code> symbol just before whatever output I'm looking for. So that needs to be accounted for.</li>
<li>Execute appropriate action - that is either simply emitting an event or executing a lambda.</li>
</ul>
<p>Currently it's nearly 100 lines long function that contains many non-obvious inner functions and quite complex connections between it's internal data for my taste. I feel like it's too complicated to exist as a single unit, how could this be improved? Are there any patterns? My current choice would be to extract whole output parsing to a separate class, but at the same time I feel like it's not good approach in this case.</p>
<p>Or maybe it is okay to encapsulate all this logic inside a function in javascript and I'm just not used to this?</p>
<p>Also I hit a dead spot with the above as <code>getHwTools</code> member function would require a totally different parsing of MDB's output (a table) that just doesn't fit current design. I've already encountered it when parsing breakpoints witch resulted in creation of <code>_haltInfo</code> and <code>_lastBreakpoint</code> member variables, which form a separate state machine inside already overgrown object. It would be possible to implement (for example creating regexes that would match only this table or some global state determining current parsing mode), but I feel like it would just be going down the rabbit hole.</p>
<p><strong>How to approach testing such code in Typescript?</strong></p>
<p>I can't really use <code>MDB</code> for it as it is highly buggy and not deterministic (it has some concurrency on stdout issues, likes to spuriously hang and such). I though of mocking <code>child_process</code> and providing my own <code>stdin</code> and <code>stdout</code> stream that would simulate whatever it is that I want to test, but I don't know how to encapsulate it enough, so that test-cases would be short, easy to write and really obvious what they are testing. Are there some patterns.</p>
<p><strong>I have a lot of member functions that look like this:</strong></p>
<pre class="lang-js prettyprint-override"><code> public async stepIn(timeoutMs: number = 60000) {
if (! this._imageLoaded) {
throw ERRORS.IMAGE_NOT_LOADED;
}
if (this._running) {
throw ERRORS.DEVICE_RUNNING;
}
this._running = true;
this.writeLnAndWaitForEvent(MDB_COMMANDS.STEP(), MDB_EVENTS.DEVICE_HALT, timeoutMs);
}
</code></pre>
<p>They all do the following:</p>
<ul>
<li>Check some preconditions and throw appropriate error if not met</li>
<li>(sometimes) Set some internal state</li>
<li>Execute (write to <code>MDB</code>s stdin) a command and wait for some event that should be a result of it.</li>
</ul>
<p>This probably can be simplified I just don't know how.</p>
<p><strong>Remarks</strong></p>
<p>I feel like most of my problem with design here is lack of separation of concerns. I've created this one big class which has the API that I want, but does everything inside instead of delegating tasks to other units (like parsing of the <code>MDB</code>s output). I've done this because I can't really find any good pattern for merging multiple <code>EventEmmiter</code>s into one big class. So either I'm looking in wrong places or this should be solved differently - I would really appreciate input in this area.</p>
<p>As far as the review is concerned please disregard <code>test</code> function at the bottom - It's there to test the class during development and show example usage of the API.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T09:46:48.003",
"Id": "424073",
"Score": "0",
"body": "Welcome to Code Review. Please revisit [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and improve your question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T09:56:51.880",
"Id": "424210",
"Score": "0",
"body": "@greybeard is it better? What areas should I try to improve more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T07:16:04.487",
"Id": "424317",
"Score": "0",
"body": "For the outstanding reason of deciding whether your question gets read or not, the first actionable paragraph in the help page linked is about titling: In my eyes, your title is too long. I used to do *remote debugging* as well as *cross debugging* and (once) [ICE](https://en.m.wikipedia.org/wiki/In-circuit_emulation) - and think the terms even more detached than in the day. You seem to want to debug \"processes\" on an MCU using support code there, *VS Code* locally (I think you can and should mark up this in the title, **or** tag [tag:vscode] - can't seem to make up my mind)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T07:22:07.680",
"Id": "424318",
"Score": "0",
"body": "In the introduction, you could try and unambiguously describe which parts are executing where (interactive console program on MCU (console?!), wrapper locally/in *VS Code*?). Questions not containing the lion's share of what there is to review are [off topic](https://codereview.stackexchange.com/help/on-topic). I see your question at the very verge (and do not intend to delve into the pastebin code to try and decide if there was a more appropriate line to draw, and where)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-04T17:21:31.767",
"Id": "424363",
"Score": "0",
"body": "@greybeard I clarified the scope of this question. I think I focused too much on the end goal and not what the code actually does - which led to confusion. \n\nAlso - thank you for taking your time and helping me improve the question."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:36:56.117",
"Id": "219567",
"Score": "3",
"Tags": [
"node.js",
"async-await",
"typescript"
],
"Title": "Communication with interactive program using ChildProcess"
} | 219567 |
<p>This is my code written to check whether a given number is armstrong or not . but the logic differs from the conventional logic of using integer and separating its digits and calculating , instead i optimize the logic of separating the digits using Sting and char array . Please review my code ? </p>
<pre><code>import java.util.Scanner;
public class ArmstrongNumberChecker {
public static void main(String[] args) {
int number;
int sum = 0;
Scanner scanner = new Scanner(System.in);
try {
System.out.println("\nEnter the number to check if it is armstrong number\n");
number = scanner.nextInt();
String s = Integer.toString(number);
char[] c = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
sum = ( int ) (sum + Math.pow((c[i] - 48), c.length));
}
if (sum == number) {
System.out.println("Number " + number + " is Armstrong");
} else {
System.out.println("Number " + number + " is not Armstrong");
}
} catch (Exception e) {
System.out.println("Invalid data");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T01:42:17.380",
"Id": "424166",
"Score": "0",
"body": "Welcome to CodeReview! Can you provide a link or a definition of what Armstrong means?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T02:34:30.167",
"Id": "424168",
"Score": "0",
"body": "Ya sure Austin, https://en.m.wikipedia.org/wiki/Narcissistic_number"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T06:03:11.147",
"Id": "424176",
"Score": "1",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T06:09:30.490",
"Id": "424178",
"Score": "0",
"body": "Now what can I do, I am new to code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T06:25:51.897",
"Id": "424183",
"Score": "0",
"body": "Thanks to edit my question to previous, @Sᴀᴍ Onᴇᴌᴀ ."
}
] | [
{
"body": "<p>It's one big static main method that works only on data from System.in. Start by refactoring the algorithm into a reusable utility method that works with integers. You're working with numbers so requiring the input to be a string is not an improvement (it seems like a cop-out to make the coding easier for you).</p>\n\n<p>An armstrong number can not be larger than 4 * 9^3 so you should add range checks to avoid useless checking.</p>\n\n<p>You're not prepared for negative values.</p>\n\n<p>You catch generic Exception, ignore it and report a pretty useless error message. You know what the possible exceptions are (IOException and NumberFormatException), so catch them and tell the user exactly what went wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T09:50:20.433",
"Id": "424075",
"Score": "2",
"body": "If you didn't want feedback, why on earth did you post to code review? You should have said that up front and saved everyones time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T09:33:17.510",
"Id": "219574",
"ParentId": "219568",
"Score": "3"
}
},
{
"body": "<p>Thanks for your reviews everyone. Using the ideas in answer I rewrote my code. </p>\n\n<p>Here I changed my void main () and use it to only call my methods to run the program. </p>\n\n<pre><code>public static void main(String[] args) {\n new ArmstrongNumberChecker().mainMethod();\n }\n</code></pre>\n\n<p>I also separated the tasks by creating methods in my class and handled exceptions in the method .</p>\n\n<pre><code>private void mainMethod() {\n try {\n System.out.println(\"\\nEnter the number to check if it is armstrong number\\n\");\n number = scanner.nextInt();\n armstrongChecker();\n } catch (InputMismatchException e) {\n System.out.println(e + \"\\t : Only integers allowed\");\n }\n }\n\n private void armstrongChecker() {\n String s = Integer.toString(number);\n char[] c = s.toCharArray();\n for (int i = 0; i < s.length(); i++) {\n sum = ( int ) (sum + Math.pow((c[i] - 48), c.length));\n }\n if (sum == number) {\n System.out.println(\"Number \" + number + \" is Armstrong\");\n } else {\n System.out.println(\"Number \" + number + \" is not Armstrong\");\n }\n }\n</code></pre>\n\n<p>Putting it all together my code looks like this. </p>\n\n<pre><code>import java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class ArmstrongNumberChecker {\n private int number;\n private int sum = 0;\n private Scanner scanner = new Scanner(System.in);\n\n public static void main(String[] args) {\n new ArmstrongNumberChecker().mainMethod();\n }\n\n private void mainMethod() {\n try {\n System.out.println(\"\\nEnter the number to check if it is armstrong number\\n\");\n number = scanner.nextInt();\n armstrongChecker();\n } catch (InputMismatchException e) {\n System.out.println(e + \"\\t : Only integers allowed\");\n }\n }\n\n private void armstrongChecker() {\n String s = Integer.toString(number);\n char[] c = s.toCharArray();\n for (int i = 0; i < s.length(); i++) {\n sum = ( int ) (sum + Math.pow((c[i] - 48), c.length));\n }\n if (sum == number) {\n System.out.println(\"Number \" + number + \" is Armstrong\");\n } else {\n System.out.println(\"Number \" + number + \" is not Armstrong\");\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-03T06:37:48.277",
"Id": "219621",
"ParentId": "219568",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-02T08:37:22.730",
"Id": "219568",
"Score": "-2",
"Tags": [
"java",
"algorithm",
"strings",
"integer"
],
"Title": "ArmstrongNumber checker"
} | 219568 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.