问:
using .reduce() on an a list of objects
I have this sample data set:

```<code>let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]
</code>```

I am trying to end up with this:

```<code>[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]
</code>```

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

```<code>let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])
</code>```

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

```<code>let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])
</code>```

答:
In my approach, i'm using reduce to create a sparse array with the index as the list id. I then use Object.values to squash it down.

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4}
];

let result = list.reduce( (acc, item, index) => {
  if(acc[item.id]){
   acc[item.id][1].push(item.first);
  } else {
   acc[item.id] = [item.id, [item.first]];
  }
  return acc;
}, []);

console.log(Object.values(result));```

Title: using .reduce() on an a list of objects

Body:
I have this sample data set:

let list = [
  {'first': 'morgan', 'id': 1},
  {'first': 'eric', 'id': 1},
  {'first': 'brian', 'id': 2 },
  {'first': 'derek', 'id' : 2},
  {'first': 'courtney', 'id': 3},
  {'first': 'eric', 'id': 4},
  {'first': 'jon', 'id':4},
]

I am trying to end up with this:

[[1, [morgan, eric]], [2, [brian, derek]], [3, [courtney]], [4, [eric, jon]]

I am using the .reduce() function to map over the list. However, I'm somewhat stuck.

I got this working:

let b = list.reduce((final_list, new_item) => {
  x = final_list.concat([[new_item.id, [new_item.first]]])
  return x
}, [])

However, that flattens out the list into a list of lists of lists, but doesn't combine names that share a similar id.

I tried using .map() the code below does not work

I tried to map over the final_list (which is a list of [id, [names]] looking to see if the id of the new_item exists in the smaller_list and then add new_item.first to the smaller_list[1] (which should be the list of names).

Is this the right approach?

let b = list.reduce((final_list, new_item) => {
  final_list.map((smaller_list) => {
    if (smaller_list.indexOf((new_item.id)) >=0) {
      smaller_list[1].concat(new_item.first)
      // not sure what to do here...
    } else {
        // not sure what to do here either...
    }

  })
  x = final_list.concat([[item.id, [item.first]]])
  return x
}, [])


来源: stackexchange

问:
Why does my git bash always start at master branch?
I have a Windows PC with git installed. Whenever I start git bash, it always stand at /c/Users/_user with master branch as below:

```<code>NativeKiwi@nkiwi MINGW64 ~ (master)
</code>```

I think it should look like this:

```<code>NativeKiwi@nkiwi MINGW64 ~
</code>```

I had a look at people around, found out that they don't have (master) at their first start using git bash. I checked git repo at where I stand with git remote -v but there is nothing.

答:
The string shown in your prompt depends on your PS1 environment variable.
Please check your .bash_profile or .bashrc　for the configuration of PS1 environment variable.

ContentLicense: CC BY-SA 4.0

Body:
I have a Windows PC with git installed. Whenever I start git bash, it always stand at /c/Users/_user with master branch as below:

NativeKiwi@nkiwi MINGW64 ~ (master)

I think it should look like this:

NativeKiwi@nkiwi MINGW64 ~

I had a look at people around, found out that they don't have (master) at their first start using git bash. I checked git repo at where I stand with git remote -v but there is nothing.

ContentLicense: CC BY-SA 3.0


问:
Analysis of Linear congruential generator is wrong?
So in an attempt to better understand MSVC++'s implementation of rand, I re-implemented it and attempted to better understand it (and LCGs in general I guess).

My implementation (which matches MSVC++'s almost exactly) is as follows:

```<code>// vc++ impl. of random
// Xn+1 = (aXn + i) mod m
// a = 214013, i = 2531011, m = 32768
unsigned int seed = 0;
unsigned int random()
{
    seed = seed * 214013L + 2531011L;
    // return (seed/(1<<16)) % 32768; (equiv to below)
    return seed>>16 & 0x7FFF;
}
</code>```

To find the difference in the newly generated seeds from 2 seeds, I figured it would just be (214013*h) % 2^32 where h is the difference between the 2 initial seeds. Using this same logic I figured the difference between 2 randomly generated numbers given the initial seed as x and the next seed as x+h, I took this different in seed, divided it by 2^16 (or shifted it right 16 bits), and got rid of the most significant bit.

The values this yields seem to be correct except in some cases, for example when x = 100 and h = 5000.

Here's the entire code:

```<code>#include <iostream>
#include <cstdlib>

// vc++ impl. of random
// Xn+1 = (aXn + i) mod m
// a = 214013, i = 2531011, m = 32768
unsigned int seed = 0;
unsigned int random()
{
    seed = seed * 214013L + 2531011L;
    return seed>>16 & 0x7FFF;
}

int main()
{
    // f(x) = (214013x + 2531011) mod 2^32 [LCG]
    // g(x) = floor(f(x)/2^16) mod 2^15 [RND]
    // h(x) = f(x + h) - f(x) ?= 214013*h mod 2^32
    // j(x) = g(x + h) - g(x) ?= 214013*h/2^16 mod 2^15

    // x: initial seed
    // h: displaecment to next seed (next seed: x + h)
    // a, b: first and second randomly generated values using C rand
    // c, d: first and second randomly generated values using random
    // newSeedA, newSeedB: seed generated from LCG after x and x + h respectively
    // diffExp: experimental difference in random values
    // diffCalc: calculated/theoretical difference in random vlaues
    unsigned int x = 100, h = 50000;
    unsigned int a, b, c, d;
    unsigned int newSeedA, newSeedB;
    int diffExp, diffCalc;

    srand(x);
    seed = x;
    a = rand();
    c = random();
    newSeedA = seed;

    srand(x + h);
    seed = x + h;
    b = rand();
    d = random();
    newSeedB = seed;

    diffExp = (d - c) % 32768;
    diffCalc = (214013*h)>>16 & 0x7FFF;

    std::cout << "RANDOM VALUES\n";
    std::cout << "  VC++ rand: " << a << ", " << b << "\n";
    std::cout << "Custom rand: " << c << ", " << d << "\n";
    std::cout << "\n";

    std::cout << "DIFFERENCE IN SEED\n";
    std::cout << "Experimental Difference: " << (newSeedB - newSeedA) << "\n";
    std::cout << "  Calculated Difference: " << (static_cast<unsigned int>(214013)*h) << "\n";
    std::cout << "\n";

    std::cout << "DIFFERENCE IN VALUES\n";
    std::cout << "Experimental Difference: " << diffExp << "\n";
    std::cout << "  Calculated Difference: " << diffCalc << "\n";
    std::cout << "\n";
    return 0;
}
</code>```

However with these values, the estimated difference between the 2 randomly generated values is 1 less than the actual difference. Am I doing something obviously wrong?

答:
The difference between the new seeds is indeed 214013*h.

That gives the seeds s and s + 214013*h, the difference between the resulting random outputs would be (before simplification) diff = ((s + 214013*h >> 16) & 0x7fff) - ((s >> 16) & 0x7fff). The question is then essentially, is this expression independent of s.

It is not. For example, even taking h = 1, diff can be either 3 (eg s = 0) or 4 (eg s = 0x0000bc03).

Body:
So in an attempt to better understand MSVC++'s implementation of rand, I re-implemented it and attempted to better understand it (and LCGs in general I guess).

My implementation (which matches MSVC++'s almost exactly) is as follows:

// vc++ impl. of random
// Xn+1 = (aXn + i) mod m
// a = 214013, i = 2531011, m = 32768
unsigned int seed = 0;
unsigned int random()
{
    seed = seed * 214013L + 2531011L;
    // return (seed/(1<<16)) % 32768; (equiv to below)
    return seed>>16 & 0x7FFF;
}

To find the difference in the newly generated seeds from 2 seeds, I figured it would just be (214013*h) % 2^32 where h is the difference between the 2 initial seeds. Using this same logic I figured the difference between 2 randomly generated numbers given the initial seed as x and the next seed as x+h, I took this different in seed, divided it by 2^16 (or shifted it right 16 bits), and got rid of the most significant bit.

The values this yields seem to be correct except in some cases, for example when x = 100 and h = 5000.

Here's the entire code:

#include <iostream>
#include <cstdlib>

// vc++ impl. of random
// Xn+1 = (aXn + i) mod m
// a = 214013, i = 2531011, m = 32768
unsigned int seed = 0;
unsigned int random()
{
    seed = seed * 214013L + 2531011L;
    return seed>>16 & 0x7FFF;
}

int main()
{
    // f(x) = (214013x + 2531011) mod 2^32 [LCG]
    // g(x) = floor(f(x)/2^16) mod 2^15 [RND]
    // h(x) = f(x + h) - f(x) ?= 214013*h mod 2^32
    // j(x) = g(x + h) - g(x) ?= 214013*h/2^16 mod 2^15

    // x: initial seed
    // h: displaecment to next seed (next seed: x + h)
    // a, b: first and second randomly generated values using C rand
    // c, d: first and second randomly generated values using random
    // newSeedA, newSeedB: seed generated from LCG after x and x + h respectively
    // diffExp: experimental difference in random values
    // diffCalc: calculated/theoretical difference in random vlaues
    unsigned int x = 100, h = 50000;
    unsigned int a, b, c, d;
    unsigned int newSeedA, newSeedB;
    int diffExp, diffCalc;

    srand(x);
    seed = x;
    a = rand();
    c = random();
    newSeedA = seed;

    srand(x + h);
    seed = x + h;
    b = rand();
    d = random();
    newSeedB = seed;

    diffExp = (d - c) % 32768;
    diffCalc = (214013*h)>>16 & 0x7FFF;

    std::cout << "RANDOM VALUES\n";
    std::cout << "  VC++ rand: " << a << ", " << b << "\n";
    std::cout << "Custom rand: " << c << ", " << d << "\n";
    std::cout << "\n";

    std::cout << "DIFFERENCE IN SEED\n";
    std::cout << "Experimental Difference: " << (newSeedB - newSeedA) << "\n";
    std::cout << "  Calculated Difference: " << (static_cast<unsigned int>(214013)*h) << "\n";
    std::cout << "\n";

    std::cout << "DIFFERENCE IN VALUES\n";
    std::cout << "Experimental Difference: " << diffExp << "\n";
    std::cout << "  Calculated Difference: " << diffCalc << "\n";
    std::cout << "\n";
    return 0;
}

However with these values, the estimated difference between the 2 randomly generated values is 1 less than the actual difference. Am I doing something obviously wrong?


问:
Storing passwords in Jupyter notebooks
Is there a way to store secrets/access secrets/passwords in notebooks? I have an api endpoint where I pull data from, and I dont want to expose the apiKey to everyone who can view the notebook. </p>

答:
You can use the keyring package to store sensitive information in a system-specific protected store.

It can be installed via pip from pypi.

Title: Storing passwords in Jupyter notebooks


问:
Replacing text inside textarea without focus
I want to replace selected text(or insert new text after cursor position if nothing is selected).
The new text is entered from another textbox.

 I want to be able to insert new text without clicking first (focusing) in  the textarea.

meaning: first select text to replace inside textarea, then enter new text into the textbox and click the button.

```<code><textarea id='text' cols="40" rows="20">
</textarea>

<div id="opt">
    <input id="input" type="text" size="35">
    <input type="button" onclick='pasteIntoInput(document.getElementById("input").value)' value="button"/>
</div>

function pasteIntoInput(text) {
  el=document.getElementById("text");
  el.focus();
  if (typeof el.selectionStart == "number"&& typeof el.selectionEnd == "number") {
    var val = el.value;
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
    el.selectionEnd = el.selectionStart = selStart + text.length;
  }
  else if (typeof document.selection != "undefined") {
    var textRange = document.selection.createRange();
    textRange.text = text;
    textRange.collapse(false);
    textRange.select();
  }
}
</code>```

Online example:
link text

答:
Alright, correct me where I am wrong.

1) When text in the textarea is selected, then the button is clicked, the selected text is replaced by the text in the input.

2) When no text is selected, no matter the cursor position, text is automatically added at the very end of the textarea.

If those are the only stipulations, then this javascript would suffice, otherwise I need more information on what you want it to do.

```<code>function pasteIntoInput(text) {
  el=document.getElementById("text");
  el.focus();
  if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number" && el.selectionStart != el.selectionEnd) {
    var val = el.value;
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
    el.selectionEnd = el.selectionStart = selStart + text.length;
  }
  else
    el.value += text;
}
</code>```

Sorry that I cannot be of more assistance, it would be beneficial to understand the use of the function, so I could give the desired action.

ContentLicense: CC BY-SA 2.5

Body:
I want to replace selected text(or insert new text after cursor position if nothing is selected).
The new text is entered from another textbox.

 I want to be able to insert new text without clicking first (focusing) in  the textarea.

meaning: first select text to replace inside textarea, then enter new text into the textbox and click the button.

<textarea id='text' cols="40" rows="20">
</textarea>

    <input id="input" type="text" size="35">
    <input type="button" onclick='pasteIntoInput(document.getElementById("input").value)' value="button"/>

function pasteIntoInput(text) {
  el=document.getElementById("text");
  el.focus();
  if (typeof el.selectionStart == "number"&& typeof el.selectionEnd == "number") {
    var val = el.value;
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
    el.selectionEnd = el.selectionStart = selStart + text.length;
  }
  else if (typeof document.selection != "undefined") {
    var textRange = document.selection.createRange();
    textRange.text = text;
    textRange.collapse(false);
    textRange.select();
  }
}

Online example:
link text

Body:
Alright, correct me where I am wrong.

1) When text in the textarea is selected, then the button is clicked, the selected text is replaced by the text in the input.

2) When no text is selected, no matter the cursor position, text is automatically added at the very end of the textarea.

If those are the only stipulations, then this javascript would suffice, otherwise I need more information on what you want it to do.

function pasteIntoInput(text) {
  el=document.getElementById("text");
  el.focus();
  if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number" && el.selectionStart != el.selectionEnd) {
    var val = el.value;
    var selStart = el.selectionStart;
    el.value = val.slice(0, selStart) + text + val.slice(el.selectionEnd);
    el.selectionEnd = el.selectionStart = selStart + text.length;
  }
  else
    el.value += text;
}

Sorry that I cannot be of more assistance, it would be beneficial to understand the use of the function, so I could give the desired action.


答:
Not very sexy, but it works

Iterate over list and build an object using the ids as keys with values of arrays of the first names.

Empty list (if you plan to overwrite it).

Walk through the resultant object making arrays for each id with its next sibling element being an array of the names from the value associated with that id, and push them into list (or a fresh array if maintaining the original list).

var list = [
      {'first': 'morgan', 'id': 1},
      {'first': 'eric', 'id': 1},
      {'first': 'brian', 'id': 2 },
      {'first': 'derek', 'id' : 2},
      {'first': 'courtney', 'id': 3},
      {'first': 'eric', 'id': 4},
      {'first': 'jon', 'id':4},
    ],
    o = {}, p;

list.forEach( ( v ) => {
    if ( !o[ v.id ] ) {
        o[ v.id ] = [];
    }
    o[ v.id ].push( v.first );
} );

list = []; // if overwriting

for ( p in o ) {
    if ( o.hasOwnProperty( p ) ) {
        list.push( [ parseInt( p ), o[ p ] ] );
    }
}

console.log( JSON.stringify( list ).replace( /,/g, ", " ) );```

Edited to add parseInt() (noticed in another answer) since the question's example expected output does indeed show numerals as integers, not strings.

And changed the demo output to stringifyed JSON (also noticed (easier to read) in other answers).

Title: using .reduce() on an a list of objects

Body:
Not very sexy, but it works

Iterate over list and build an object using the ids as keys with values of arrays of the first names.

Empty list (if you plan to overwrite it).

Walk through the resultant object making arrays for each id with its next sibling element being an array of the names from the value associated with that id, and push them into list (or a fresh array if maintaining the original list).

var list = [
      {'first': 'morgan', 'id': 1},
      {'first': 'eric', 'id': 1},
      {'first': 'brian', 'id': 2 },
      {'first': 'derek', 'id' : 2},
      {'first': 'courtney', 'id': 3},
      {'first': 'eric', 'id': 4},
      {'first': 'jon', 'id':4},
    ],
    o = {}, p;

list.forEach( ( v ) => {
    if ( !o[ v.id ] ) {
        o[ v.id ] = [];
    }
    o[ v.id ].push( v.first );
} );

list = []; // if overwriting

for ( p in o ) {
    if ( o.hasOwnProperty( p ) ) {
        list.push( [ parseInt( p ), o[ p ] ] );
    }
}

console.log( JSON.stringify( list ).replace( /,/g, ", " ) );

Edited to add parseInt() (noticed in another answer) since the question's example expected output does indeed show numerals as integers, not strings.

And changed the demo output to stringifyed JSON (also noticed (easier to read) in other answers).


问:
Adding disabled option in codeigniter form_dropdown
I'm trying to figure out how to add a disabled option in my dropdown, using codeIgniter. New to CI, and I've tried googling it a bit, but couldn't find an answer.

My code for a dropdown looks like this:

```<code>    echo form_dropdown('category', array('0' => 'Choose a category...')  + $categories, '0');
</code>```

This gives me a dropdown with all my options from the variable $categories, with "Choose a category..." (value 0) at top. Now how to I make the first one disabled? I know how to make it select a specific one, which I've set it to do here.

Can anyone help me? Thanks

答:
Solution:

Change the 437th string of form_helper.php:

from

```<code>.(in_array($key, $selected) ? ' selected="selected"' : '').’>'
</code>```

to

```<code>.(in_array($key, $selected) ? ' disabled="disabled"' : '').’>'
</code>```

and use selected feature as disabled. Looks like an lifehack, but it works

Body:
I'm trying to figure out how to add a disabled option in my dropdown, using codeIgniter. New to CI, and I've tried googling it a bit, but couldn't find an answer.

My code for a dropdown looks like this:

    echo form_dropdown('category', array('0' => 'Choose a category...')  + $categories, '0');

This gives me a dropdown with all my options from the variable $categories, with "Choose a category..." (value 0) at top. Now how to I make the first one disabled? I know how to make it select a specific one, which I've set it to do here.

Can anyone help me? Thanks

Body:
Solution:

Change the 437th string of form_helper.php:

from

.(in_array($key, $selected) ? ' selected="selected"' : '').’>'

to

.(in_array($key, $selected) ? ' disabled="disabled"' : '').’>'

and use selected feature as disabled. Looks like an lifehack, but it works


问:
Inconsistent intervals with System.Windows.Forms.Timer
Please be kind, I'm just learning C# and inheriting this application from a former-employee is my first C# project.

I am observing inconsistent and slow periods with System.Windows.Forms.Timer.  The application is written in C# with MS Visual Studio.

The timer is set for an interval of 100 msec yet I am observing periods ranging from 110 msec to 180 msec.

I am using several tools to observe this including:
- a SW oscilloscope (the Iocomp.Instrumentation.Plotting.Plot package),
- a real oscilloscope,
- letting the timer run for some time and comparing the number of ticks * 100 msec to both the system time and to a stopwatch.

In all cases I am observing a 10% lag that becomes evident within the first few seconds.

The methods that are executed with each tick take fewer than 4 msec to run.  There is no time-consuming asynchronous processing happening, either.  This shouldn't matter, though, as the timer tick is an interrupt, not an event added to an event handler queue (as far as I know).

Has anyone experienced a problem like this before?  What were the root causes?

Thanks.

答:
This is old, but in case anyone comes here looking for an actually correct answer:

From https://msdn.microsoft.com/en-us/library/system.windows.forms.timer(v=vs.110).aspx (emphasis mine):

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

So with Windows.Forms.Timer you can get 55ms, 110ms, 165ms, etc.; which is consistent with what you were seeing. If you need higher precision, try System.Timers.Timer or System.Threading.Timer


问:
Debugging bundled and versioned javascript files
I've used Bundleconfig.cs to bundle my javascript files as follows:

```<code>bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
             "~/Scripts/spectrum.js",
              "~/Scripts/notify.js",
              "~/Scripts/spin.min.js"));
   BundleTable.EnableOptimizations = true;
</code>```

Then in my .cshtml file, I've got the following:

```<code>@Scripts.Render("~/bundles/resultscripts");
</code>```

This renders in chrome as:

```<code><script src="/bundles/resultscripts?v=3ozhz2yni5K8Is0g9QoONh_MkoivcBzooVIUD-a0Ngw1"></script>
</code>```

Then I have the following under system.web in my Web.config (not sure how much this matters):

```<code><compilation debug="true" targetFramework="4.5.2" />
</code>```

This is good because it allows bundle versioning.  However, some of my javascript doesn't seem to be firing, and when in Chrome, I can now no longer place breakpoints in my individual javascript files.  Or to be more clear, I can't find notify.js for example.  I'm guessing this is because the bundle is being minified.

If I set BundleTable.EnableOptimizations = false; my javascript files render but are no longer versioned.

I was wondering if anyone could point me in the right direction so that I can find the individual files when bundling with versions?

I checked out this: Script bundles not rendering individual files in debug, and am using the same syntax, but my files are not getting rendered individually.

答:
I hope below statement will be helpful  for you:

when we are not in a debug compilation and have not turned off the EnableOptimizations feature, MVC will combine those files in our bundles, compress (minify) them and output only a single script tag

Source : https://stackoverflow.com/a/21271866/3397630

Body:
I've used Bundleconfig.cs to bundle my javascript files as follows:

bundles.Add(new ScriptBundle("~/bundles/resultscripts").Include(
             "~/Scripts/spectrum.js",
              "~/Scripts/notify.js",
              "~/Scripts/spin.min.js"));
   BundleTable.EnableOptimizations = true;

Then in my .cshtml file, I've got the following:

@Scripts.Render("~/bundles/resultscripts");

This renders in chrome as:

Then I have the following under system.web in my Web.config (not sure how much this matters):

<compilation debug="true" targetFramework="4.5.2" />

This is good because it allows bundle versioning.  However, some of my javascript doesn't seem to be firing, and when in Chrome, I can now no longer place breakpoints in my individual javascript files.  Or to be more clear, I can't find notify.js for example.  I'm guessing this is because the bundle is being minified.

If I set BundleTable.EnableOptimizations = false; my javascript files render but are no longer versioned.

I was wondering if anyone could point me in the right direction so that I can find the individual files when bundling with versions?

I checked out this: Script bundles not rendering individual files in debug, and am using the same syntax, but my files are not getting rendered individually.


问:
Scaling down a BMP image in C
```<code> int main(void) {
    setvbuf( stdout, NULL, _IONBF, 0 );

    //Input File
    FILE* infile;
    infile = fopen("test.bmp", "rb");

    //Vars for image
    char bm[2];
    int imageSize;
    int fileSize;
    int width, height;
    char restOfDataOne[12];
    char restOfDataTwo[28];

    //Read Header Info
    fread(bm, 1, 2, infile);
    fread(&fileSize, 1, 4, infile);
    imageSize = fileSize - 54;
    fread(restOfDataOne, 1, 12, infile);
    fread(&width, sizeof(int), 1, infile);
    fread(&height, sizeof(int), 1, infile);
    fread(restOfDataTwo, 1, 28, infile);
    int rowWidth = width * 3;
    //Read Image Data
    unsigned char image[height][(width * 3)];
    fread(image, sizeof(char), imageSize, infile);

    //Close
    fclose(infile);

    //#################################################
    //Small BMP
    //#################################################
    FILE* smallOut;
    smallOut = fopen("small.bmp", "wb");

    //Small Vars
    int imageSizeSmall = imageSize / 4;
    int fileSizeSmall = imageSizeSmall + 54;
    int widthSmall = width / 2;
    int heightSmall = height / 2;
    int smallRowWidth = widthSmall * 3;
    unsigned char imageSmall[heightSmall][smallRowWidth];

    //Image Data
    int c, d, e;
    //For every 4 pixels.. store one in small image
    for(c = 0; c < rowWidth; c++) {
       for(d = 0; d < height; d++) {
            //imageSmall[d/2][c/2] = image[d][c];
            for(e = 0; e < 3; e++) {
                //grab every 1 out of 4 and place into small?
            }
       }
    }
</code>```

So I have the following code which reads the bmp image, then I need to scale it down and output it to the smaller version which is half the width and half the height, therefore being 4 times smaller in all. So I know I have to grab 1 out of every 3 pixels? and put it into my new smallImage, but I have tried multiple things with nested for loops and just can't get the algorithm down. I have viewed multiple posts here on stackexchange but people are using libraries, which I cannot use. (Homework). I'm not looking for someone to do it for me, just looking for someone to point me in the right direction or give me a hint?
Full code here.
https://pastebin.com/ZVmXtmCx

答:
You have a nice and detailed study for your problem at the following address:

http://www.davdata.nl/math/bmresize.html

I quote:

This is done by scanning these pixels, left to right, top to bottom
  while projecting the destination pixel over the source bitmap.

Title: Scaling down a BMP image in C

Body:
 int main(void) {
    setvbuf( stdout, NULL, _IONBF, 0 );

    //Input File
    FILE* infile;
    infile = fopen("test.bmp", "rb");

    //Vars for image
    char bm[2];
    int imageSize;
    int fileSize;
    int width, height;
    char restOfDataOne[12];
    char restOfDataTwo[28];

    //Read Header Info
    fread(bm, 1, 2, infile);
    fread(&fileSize, 1, 4, infile);
    imageSize = fileSize - 54;
    fread(restOfDataOne, 1, 12, infile);
    fread(&width, sizeof(int), 1, infile);
    fread(&height, sizeof(int), 1, infile);
    fread(restOfDataTwo, 1, 28, infile);
    int rowWidth = width * 3;
    //Read Image Data
    unsigned char image[height][(width * 3)];
    fread(image, sizeof(char), imageSize, infile);

    //Close
    fclose(infile);

    //#################################################
    //Small BMP
    //#################################################
    FILE* smallOut;
    smallOut = fopen("small.bmp", "wb");

    //Small Vars
    int imageSizeSmall = imageSize / 4;
    int fileSizeSmall = imageSizeSmall + 54;
    int widthSmall = width / 2;
    int heightSmall = height / 2;
    int smallRowWidth = widthSmall * 3;
    unsigned char imageSmall[heightSmall][smallRowWidth];

    //Image Data
    int c, d, e;
    //For every 4 pixels.. store one in small image
    for(c = 0; c < rowWidth; c++) {
       for(d = 0; d < height; d++) {
            //imageSmall[d/2][c/2] = image[d][c];
            for(e = 0; e < 3; e++) {
                //grab every 1 out of 4 and place into small?
            }
       }
    }

So I have the following code which reads the bmp image, then I need to scale it down and output it to the smaller version which is half the width and half the height, therefore being 4 times smaller in all. So I know I have to grab 1 out of every 3 pixels? and put it into my new smallImage, but I have tried multiple things with nested for loops and just can't get the algorithm down. I have viewed multiple posts here on stackexchange but people are using libraries, which I cannot use. (Homework). I'm not looking for someone to do it for me, just looking for someone to point me in the right direction or give me a hint?
Full code here.
https://pastebin.com/ZVmXtmCx


问:
Compound/Complex C-String in Xcode/Cocoa
I am creating an SQLite3 program.  I am creating the database within the code.  I have about 15 columns. Example below:

```<code>NSString *createSQL = "CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           /*COLUMN #1 */
                   CLASS TEXT,          /*COLUMN #2 */
                   ...
                   COMPLETED TEXT);";  /*COLUMN #15 */
</code>```

When I compile I am getting "missing terminating character error.  I did some research and saw that because it is a C-String it will process the CR\LF as a continuation character. I don't want to create a line of codes that scrolls the right most margin of the screen every time I need to do something with SQL.   Is there a way that I can create a string that can be broken up on separate lines without getting this error?

答:
Hello i think you forget to place @ character at the begining of string as required in Objective C

NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           //COLUMN #1
                   CLASS TEXT,          //COLUMN #2
                   ...
                   COMPLETED TEXT);";  //COLUMN #15

Body:
I am creating an SQLite3 program.  I am creating the database within the code.  I have about 15 columns. Example below:

NSString *createSQL = "CREATE TABLE IF NOT EXISTS FIELDS (DATE TEXT PRIMARY KEY,
                   NAME TEXT,           /*COLUMN #1 */
                   CLASS TEXT,          /*COLUMN #2 */
                   ...
                   COMPLETED TEXT);";  /*COLUMN #15 */

When I compile I am getting "missing terminating character error.  I did some research and saw that because it is a C-String it will process the CR\LF as a continuation character. I don't want to create a line of codes that scrolls the right most margin of the screen every time I need to do something with SQL.   Is there a way that I can create a string that can be broken up on separate lines without getting this error?


问:
Valgrind: INVALID READ OF SIZE 1 in constructor
I am getting an invalid read of size 1 in the following function:

ubigint.cpp

```<code>ubigint::ubigint (unsigned long that){
   //DEBUGF ('~', this << " -> " << uvalue)
   ostringstream convert;  // stream for converting numbers to strings
   convert << that;  // output the number to the stream

    for(string::reverse_iterator rit = convert.str().rbegin(); rit != convert.str().rend(); rit++) // iterate through the string
    {
        ubig_value.push_back(*rit); // push the character
    }
    size_t current_size = ubig_value.size();
    while(current_size != 0 && ubig_value.back() == '0')
    {
        ubig_value.pop_back();
        current_size--;
    }

}
</code>```

ubigint.h

```<code>// $Id: ubigint.h,v 1.11 2016-03-24 19:43:57-07 - - $

#ifndef __UBIGINT_H__
#define __UBIGINT_H__

#include <exception>
#include <iostream>
#include <limits>
#include <utility>
using namespace std;

#include "debug.h"
#include "relops.h"

    class ubigint {
       friend ostream& operator<< (ostream&, const ubigint&);
       private:
          /*using unumber = unsigned long;
          unumber uvalue {};
          */
          using udigit_t = unsigned char;
          using ubigvalue_t = vector<udigit_t>;
          ubigvalue_t ubig_value;

       public:
          void multiply_by_2();
          void divide_by_2();

          ubigint() = default; // Need default ctor as well.
          ubigint (unsigned long);
          ubigint (const string&);

          ubigint operator+ (const ubigint&) const;
          ubigint operator- (const ubigint&) const;
          ubigint operator* (const ubigint&) const;
          ubigint operator/ (const ubigint&)const;
          ubigint operator% (const ubigint&) const;

          bool operator== (const ubigint&) const;
          bool operator<  (const ubigint&) const;

          //helper functions
          string vectorToString(ubigvalue_t& myVector)const;
    };

    #endif
</code>```

Error Message:

```<code>==4025== Invalid read of size 1
==4025==    at 0x40309C: ubigint::ubigint(unsigned long) (ubigint.cpp:23)
==4025==    by 0x40412F: udivide(ubigint const&, ubigint) (ubigint.cpp:260)
==4025==    by 0x404418: ubigint::operator/(ubigint const&) const (ubigint.cpp:285)
==4025==    by 0x40709D: bigint::operator/(bigint const&) const (bigint.cpp:89)
==4025==    by 0x40CCEB: do_arith(iterstack<bigint>&, char) (main.cpp:35)
==4025==    by 0x40D58F: main (main.cpp:143)
</code>```

I didn't put the other functions because I think that the cause of the problem is the constructor. I noticed that I was comparing ubig_value.back() against the integer 0. I changed it to char and that still didn't solve the problem. What is wrong with the constructor?. Line 23 is ubig_value.pop_back();. When I run the program without using valgrind, it runs properly.

答:
convert.str() returns a temporary string instance, by value. Two calls to convert.str() produce different instances of string, so convert.str().rbegin() and convert.str().rend() do not form a valid range - they are iterators into different containers.

Moreover, rit is a dangling iterator - the string it points into, being a temporary, is gone by the time the iterator is used.

Therefore, your function exhibits undefined behavior.

Body:
I am getting an invalid read of size 1 in the following function:

ubigint.cpp

ubigint::ubigint (unsigned long that){
   //DEBUGF ('~', this << " -> " << uvalue)
   ostringstream convert;  // stream for converting numbers to strings
   convert << that;  // output the number to the stream

    for(string::reverse_iterator rit = convert.str().rbegin(); rit != convert.str().rend(); rit++) // iterate through the string
    {
        ubig_value.push_back(*rit); // push the character
    }
    size_t current_size = ubig_value.size();
    while(current_size != 0 && ubig_value.back() == '0')
    {
        ubig_value.pop_back();
        current_size--;
    }

}

ubigint.h

// $Id: ubigint.h,v 1.11 2016-03-24 19:43:57-07 - - $

#ifndef __UBIGINT_H__
#define __UBIGINT_H__

#include <exception>
#include <iostream>
#include <limits>
#include <utility>
using namespace std;

#include "debug.h"
#include "relops.h"

    class ubigint {
       friend ostream& operator<< (ostream&, const ubigint&);
       private:
          /*using unumber = unsigned long;
          unumber uvalue {};
          */
          using udigit_t = unsigned char;
          using ubigvalue_t = vector<udigit_t>;
          ubigvalue_t ubig_value;

       public:
          void multiply_by_2();
          void divide_by_2();

          ubigint() = default; // Need default ctor as well.
          ubigint (unsigned long);
          ubigint (const string&);

          ubigint operator+ (const ubigint&) const;
          ubigint operator- (const ubigint&) const;
          ubigint operator* (const ubigint&) const;
          ubigint operator/ (const ubigint&)const;
          ubigint operator% (const ubigint&) const;

          bool operator== (const ubigint&) const;
          bool operator<  (const ubigint&) const;

          //helper functions
          string vectorToString(ubigvalue_t& myVector)const;
    };

    #endif

Error Message:

==4025== Invalid read of size 1
==4025==    at 0x40309C: ubigint::ubigint(unsigned long) (ubigint.cpp:23)
==4025==    by 0x40412F: udivide(ubigint const&, ubigint) (ubigint.cpp:260)
==4025==    by 0x404418: ubigint::operator/(ubigint const&) const (ubigint.cpp:285)
==4025==    by 0x40709D: bigint::operator/(bigint const&) const (bigint.cpp:89)
==4025==    by 0x40CCEB: do_arith(iterstack<bigint>&, char) (main.cpp:35)
==4025==    by 0x40D58F: main (main.cpp:143)

I didn't put the other functions because I think that the cause of the problem is the constructor. I noticed that I was comparing ubig_value.back() against the integer 0. I changed it to char and that still didn't solve the problem. What is wrong with the constructor?. Line 23 is ubig_value.pop_back();. When I run the program without using valgrind, it runs properly.


问:
Replacing N-level for loops with recursion in C++
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

```<code>HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World
</code>```

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

```<code>#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}
</code>```

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?

答:
If the only possibilities is for a word to appear or not appear, that makes two possibilities. So for n words you have 2^n combinations. So you just count through the 2^n numbers from 0 (including) to 2^n-1 (including) and map each bit to one word.

No recursion needed, just one counting for loop.

Body:
I have been trying for some time now to come up with a way to compute all the various combinations of strings of words for some time now. Unlike most methods for combining on the web though, the algorithm must produce every combination, including those in which all the combined elements aren't in a single combination. ie, if I am combining 'Hello', 'New' and 'World', the combinations I am looking for are:

HelloNewWorld
HelloNew
HelloWorld
Hello
NewWorld
New
World

A professor from my college did come up with a quick and dirty solution for doing just that, but it is using nested for loops.

#include <iostream>
#include <vector>
#include <array>
#include <string>

int main()
{
std::vector<std::array<std::string, 2>> vec(3);
vec[0] = {"Hello", ""};
vec[1] = {"New", ""};
vec[2] = {"World", ""};
for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            std::cout << vec[0][i] + vec[1][j] + vec[2][k] << std::endl;
}

As you might imagine, I desired a way to make this actually somewhat usable and portable. I know that this is possible with recursion, I just don't know how to implement it. Optimally, I would like to make this tail-recursive if at all possible, as the plan is to compute very large combinations. What would be the best way to do this recursively, and would it be easy to make tail-recursive?


问:
How to read file chunk by chunk from S3 using aws-java-sdk
I am trying to  read large file into chunks from S3  without cutting any line for parallel processing.

Let me explain by example:
There is file of size 1G on S3. I want to divide this file into chucks of 64 MB. It is easy I can do it like  :

```<code>S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));

InputStream stream = s3object.getObjectContent();

byte[] content = new byte[64*1024*1024];

while (stream.read(content)  != -1) {

//process content here

}
</code>```

but problem with chunk is it may have 100 complete line and one incomplete. but I can not process incomplete line and don't want to discard it.

Is any way to handle this situations ? means all chucks have no partial line.

答:
100 complete line and one incomplete

do you mean you need to read the stream line by line? If so, instead of using a an InputStream try to read the s3 object stream by using BufferedReader so that you can read the stream line by line but I think this will make a little slower than by chunk.

```<code>        S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader in = new BufferedReader(new InputStreamReader(s3object.getObjectContent()));
        String line;
        while ((line = in.readLine()) != null)  {

//process line here

        }
</code>```

Body:
I am trying to  read large file into chunks from S3  without cutting any line for parallel processing.

Let me explain by example:
There is file of size 1G on S3. I want to divide this file into chucks of 64 MB. It is easy I can do it like  :

S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));

InputStream stream = s3object.getObjectContent();

byte[] content = new byte[64*1024*1024];

while (stream.read(content)  != -1) {

//process content here

}

but problem with chunk is it may have 100 complete line and one incomplete. but I can not process incomplete line and don't want to discard it.

Is any way to handle this situations ? means all chucks have no partial line.

Body:
100 complete line and one incomplete

do you mean you need to read the stream line by line? If so, instead of using a an InputStream try to read the s3 object stream by using BufferedReader so that you can read the stream line by line but I think this will make a little slower than by chunk.

        S3Object s3object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader in = new BufferedReader(new InputStreamReader(s3object.getObjectContent()));
        String line;
        while ((line = in.readLine()) != null)  {

//process line here

        }


问:
How to extract a subset of ColumnDataSource in bokeh?
The question is in the title:
how to extract a subset of ColumnDataSource in bokeh ?
Thanks.
David</p>

答: If you're asking for slicing the rows this answer might guide you and then you can apply regular Python slicing notation on the accessed result.</p>


问:
Up and down casting after adding new static const ints to derived types
I am working on a system that will take a stream of data and sort it into various output streams. The objects that pass through the system are all of the same type, but it is necessary that the end user of the system can make certain changes to the type passed though the system by subclassing the class of the data objects.

Inspired by the accepted answer to this question Base enum class inheritance, my data object class will provide a set of constant values. Users will be able to subclass the data class and add new static consts int. For example:

```<code>class Base       /* provided as part of system */
{
public:
    static const int OUTPUT_STREAM_TYPE_1 = 0;
    static const int OUTPUT_STREAM_TYPE_2 = 1;

    int mSomeMemberVariables;

    bool SomeMethods(int stream_type);
}

class Derived : public Base       /* provided by user */
{
public:
    static const int OUTPUT_STREAM_TYPE_3 = 2;
}
</code>```

My question is, can my users safely cast Derived to Base for passing through the system, and then back to Derived once they receive them in whichever stream the system selected? I suspect yes, because statics are not contained in instances, and so instances of Base and Derived should be identical. But is this guaranteed to work?

答: I don't think static_cast will work. dynamic_cast is guaranteed to work, but you must have at least one virtual function in the base class and you must check for a null result. reinterpret_cast isn't guaranteed, but it should work on most compilers provided there's no multiple inheritance.

Body:
I am working on a system that will take a stream of data and sort it into various output streams. The objects that pass through the system are all of the same type, but it is necessary that the end user of the system can make certain changes to the type passed though the system by subclassing the class of the data objects.

Inspired by the accepted answer to this question Base enum class inheritance, my data object class will provide a set of constant values. Users will be able to subclass the data class and add new static consts int. For example:

class Base       /* provided as part of system */
{
public:
    static const int OUTPUT_STREAM_TYPE_1 = 0;
    static const int OUTPUT_STREAM_TYPE_2 = 1;

    int mSomeMemberVariables;

    bool SomeMethods(int stream_type);
}

class Derived : public Base       /* provided by user */
{
public:
    static const int OUTPUT_STREAM_TYPE_3 = 2;
}

My question is, can my users safely cast Derived to Base for passing through the system, and then back to Derived once they receive them in whichever stream the system selected? I suspect yes, because statics are not contained in instances, and so instances of Base and Derived should be identical. But is this guaranteed to work?


问:
How do I make multiple click responsive canvases in javascript?
The code below is supposed to create 10x10 colored boxes at the tooltip in the canvas it is within, alternating between reddish and bluish on a gray background.  I want each canvas to respond to the mouse only when it is within the canvas.  The code below makes 4 square gray canvases, but when the mouse is over the leftmost one, colored boxes appear in the rightmost canvas.  No other canvases work.

So here are my two questions.

Why is only one canvas active?

Why do boxes appear on the wrong canvas?

<!DOCTYPE html>

<canvas id="c0" width="201" height="201"></canvas>
<canvas id="c1" width="201" height="201"></canvas>
<canvas id="c2" width="201" height="201"></canvas>
<canvas id="c3" width="201" height="201"></canvas>

```

答:
It is because you didn't declare the variable instance, causing it to be defined in the global scope. instance keeps getting overwrote by your for loop and therefore in all 4 handlers, the instance variables are all pointing to the same object. Correctly declaring a variable in a closure is very important.

```<code>var instance = value;      // declare function-scoped variable
let instance = value;      // declare block-scoped variable
function workings(args){}  // declare a function
</code>```

Here is a version of your code that has been fixed:

<!DOCTYPE html>

<canvas id="c0" width="201" height="201"></canvas>
<canvas id="c1" width="201" height="201"></canvas>
<canvas id="c2" width="201" height="201"></canvas>
<canvas id="c3" width="201" height="201"></canvas>

```

Body:
It is because you didn't declare the variable instance, causing it to be defined in the global scope. instance keeps getting overwrote by your for loop and therefore in all 4 handlers, the instance variables are all pointing to the same object. Correctly declaring a variable in a closure is very important.

var instance = value;      // declare function-scoped variable
let instance = value;      // declare block-scoped variable
function workings(args){}  // declare a function

Here is a version of your code that has been fixed:

<!DOCTYPE html>
<html>
<body>
<canvas id="c0" width="201" height="201"></canvas>
<canvas id="c1" width="201" height="201"></canvas>
<canvas id="c2" width="201" height="201"></canvas>
<canvas id="c3" width="201" height="201"></canvas>

<script>
var colorno = ["#F77", "#077"];
var the = { 'c0': {}, 'c1': {}, 'c2': {}, 'c3': {} };
var box = 10;

// declare function
function workings(name) {
    // declare variables
    var instance = the[name];
    var canvas = instance.canvas = document.getElementById(name);
    // assign values
    instance.name = name;
    instance.context = canvas.getContext("2d");
    instance.index = 0;
    instance.context.fillStyle = "#777";
    instance.context.fillRect(0, 0, canvas.width, canvas.height);

    // attach click listener
    canvas.addEventListener("click", function(e) {
        instance.context.fillStyle = colorno[++instance.index&1];
        instance.context.fillRect(
          // calculate correct coordinates
          e.pageX - canvas.offsetLeft - box / 2,
          e.pageY - canvas.offsetTop - box / 2,
          box, box);
    }, true);
};

// invoke function
for (var key in the) workings(key);
</script>

</body>
</html>


问:
How to get a dot notation of a python module?
I am writing a custom django model field which has serialize and unserialize operations, on unserialize, I am using the import_by_path to get the class and initialise an instance.

On the opposite, I need to serialize an instance to the database, in my case all I need to get the dot notation of the module.

What I am asking is, how I can, eg I have the datetime module

```<code>from datetime import datetime
</code>```

how to output datetime in dot notation to string "datetime.datetime" ?

答:
```<code>import inspect

from datetime import datetime

inspect.getmro(datetime)[0]
</code>```

That should return 'datetime.dateime'

Body:
I am writing a custom django model field which has serialize and unserialize operations, on unserialize, I am using the import_by_path to get the class and initialise an instance.

On the opposite, I need to serialize an instance to the database, in my case all I need to get the dot notation of the module.

What I am asking is, how I can, eg I have the datetime module

from datetime import datetime

how to output datetime in dot notation to string "datetime.datetime" ?

Body:
import inspect

from datetime import datetime

inspect.getmro(datetime)[0]

That should return 'datetime.dateime'


问:
How to efficiently swap elements in a dataframe?
Suppose that we have the following dataframe:

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D
</code>```

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

```<code>for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

```<code>set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E
</code>```

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

```<code>tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}
</code>```

How to go about this case? Thanks!

答:
Here is an option using data.table

```<code>library(data.table)
setDT(tmp)[(as.integer(R1) - as.integer(R2))%%2 != 0, c('R2', 'R1') := .(R1, R2)]
tmp
#    x R1 R2
#1:  1  B  B
#2:  2  A  B
#3:  3  D  C
#4:  4  B  E
#5:  5  B  D
#6:  6  E  C
#7:  7  D  E
#8:  8  E  D
#9:  9  D  B
#10:10  D  A
</code>```

Body:
Suppose that we have the following dataframe:

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
TRUE), R2 = sample(LETTERS[1:5], 10, replace = TRUE)))

    x R1 R2
1   1  B  B
2   2  B  A
3   3  C  D
4   4  E  B
5   5  B  D
6   6  E  C
7   7  E  D
8   8  D  E
9   9  D  B
10 10  A  D

I want to do the following: if the difference between the level index
of factor R1 and that of factor R2 is an odd number, the levels of the
two factors need to be switched between them, which can be performed
through the following code:

for(ii in 1:dim(tmp)[1]) {
   kk <- which(levels(tmp$R2) %in% tmp[ii,'R2'], arr.ind = TRUE) -
which(levels(tmp$R1) %in% tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

More concise and efficient ways to achieve this?

P.S. A slightly different situation is the following.

set.seed(1)
(tmp <- data.frame(x = 1:10, R1 = sample(LETTERS[1:5], 10, replace =
 TRUE), R2 = sample(LETTERS[2:6], 10, replace = TRUE)))

   x R1 R2
   1  C  B
   2  B  B
   3  C  E
   4  E  C
   5  E  B
   6  D  E
   7  E  E
   8  D  F
   9  C  D
  10  A  E

Notice that the factor levels between the two factors, R1 and R2, slide by one level; that is, factor R1 does not have level F while factor R2 does not have level A. I want to swap the factor levels based on the combined levels of the two factors as shown below:

tl <- unique(c(levels(tmp$R1), levels(tmp$R2)))
for(ii in 1:dim(tmp)[1]) {
   kk <- which(tl %in% tmp[ii,'R2'], arr.ind = TRUE) - which(tl %in%
      tmp[ii,'R1'], arr.ind = TRUE)
   if(kk%%2!=0) { # swap the their levels between the two factors
      qq <- tmp[ii,]$R1
      tmp[ii,]$R1 <- tmp[ii,]$R2
      tmp[ii,]$R2 <- qq
  }
}

How to go about this case? Thanks!

Body:
Here is an option using data.table

library(data.table)
setDT(tmp)[(as.integer(R1) - as.integer(R2))%%2 != 0, c('R2', 'R1') := .(R1, R2)]
tmp
#    x R1 R2
#1:  1  B  B
#2:  2  A  B
#3:  3  D  C
#4:  4  B  E
#5:  5  B  D
#6:  6  E  C
#7:  7  D  E
#8:  8  E  D
#9:  9  D  B
#10:10  D  A


问:
Call UpdateBookmark & useAforB as Boolean code assistance
I've been putting some code together with some help from people on this website. I've run into a bit of a snag - Im using the Call UpdateBookmark function to replace previously entered information into the word document and im having issues implementing this into my existing code.

```<code>Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
        Call UpdateBookmark("Form", tbForm.Value)
        Call UpdateBookmark("Form2", tbForm.Value)
        Call UpdateBookmark("AGN", tbGN.Value)
        Call UpdateBookmark("AFN", tbFN.Value)
        Call UpdateBookmark("LGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("RGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("LFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("RFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("DOB", tbDOB.Value)
        Call UpdateBookmark("LT", cbLT.Value)
        Call UpdateBookmark("PN", tbPN.Value)
        Call UpdateBookmark("PN2", tbPN.Value)
        Call UpdateBookmark("PN3", tbPN.Value)
        Call UpdateBookmark("PN4", tbPN.Value)
        Call UpdateBookmark("Issued", tbissue.Value)
        Call UpdateBookmark("Expiry", tbexpiry.Value)
        Call UpdateBookmark("LTD", tbLTD.Value)
        Call UpdateBookmark("LTD2", tbLTD.Value)
        Call UpdateBookmark("Narrative", tbNarrative.Value)
        Call UpdateBookmark("PRR", tbPRR.Value)
        Call UpdateBookmark("Recommendation", cbRecommendation.Value)
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange

End Sub
</code>```

I get an error which reads Compile error: ByRef argument type mismatch whenever I try to run the code - is anyone able to give me some assistance?? Thanks guys.

Entire code added for clarity

```<code>Option Explicit
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TBLPGN, TBLPFN), en

    If CheckBox1.Value = True Then ComboBoxLodge.Value = "Applicant"
    If CheckBox1.Value = False Then ComboBoxLodge.Value = "Lodging parent"

End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
Private Sub cmdCancel_Click()
    Unload Me
End Sub

Private Sub cmdClear_Click()
tbForm.Value = Null
tbFN.Value = Null
tbGN.Value = Null
tbdob.Value = Null
cbLT.Value = Null
tbPN.Value = Null
tbissue.Value = Null
tbexpiry.Value = Null
tbLTD.Value = Null
tbNarrative.Value = Null
tbPRR.Value = Null
cbRecommendation.Value = Null
CheckBox1.Value = False
ComboBoxLodge.Value = Null
End Sub

Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
        Call UpdateBookmark("Form", tbForm.Value)
        Call UpdateBookmark("Form2", tbForm.Value)
        Call UpdateBookmark("AGN", tbGN.Value)
        Call UpdateBookmark("AFN", tbFN.Value)
        Call UpdateBookmark("LGN" useAforB _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("RGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("LFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("RFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("DOB", tbdob.Value)
        Call UpdateBookmark("LT", cbLT.Value)
        Call UpdateBookmark("PN", tbPN.Value)
        Call UpdateBookmark("PN2", tbPN.Value)
        Call UpdateBookmark("PN3", tbPN.Value)
        Call UpdateBookmark("PN4", tbPN.Value)
        Call UpdateBookmark("Issued", tbissue.Value)
        Call UpdateBookmark("Expiry", tbexpiry.Value)
        Call UpdateBookmark("LTD", tbLTD.Value)
        Call UpdateBookmark("LTD2", tbLTD.Value)
        Call UpdateBookmark("Narrative", tbNarrative.Value)
        Call UpdateBookmark("PRR", tbPRR.Value)
        Call UpdateBookmark("Recommendation", cbRecommendation.Value)
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange

End Sub

Private Sub Tbform_Change()
    tbForm = UCase(tbForm)
End Sub

Private Sub Tbpn_Change()
    tbPN = UCase(tbPN)
End Sub

Private Sub tbPRR_Change()
    tbPRR = UCase(tbPRR)
End Sub

Private Sub UserForm_Initialize()
    With cbLT
        .AddItem "lost"
        .AddItem "stolen"
    End With
    With cbRecommendation
        .AddItem "I believe there is an entitlement to have the l/t flag turned off as the applicant has not contributed to the loss of Passport number: "
        .AddItem "I believe there is no entitlement to have the l/t flag turned off as the applicant has contributed to the loss of Passport number:  "
    End With
    With ComboBoxLodge
        .AddItem "Lodging parent"
        .AddItem "Applicant"
     End With
     With CheckBox1
        CheckBox1.Value = True
    End With
lbl_Exit:
    Exit Sub
End Sub
</code>```

答:
Your Sub UpdateBookmark expect two String-type arguments, but in some cases you're passing four arguments: it's not clear what the intent is there.

Did you mean something like

```<code>Call UpdateBookmark("LGN", IIf(useAforB, tbGN.Value, TBLPGN.Value))
</code>```

?

Body:
I've been putting some code together with some help from people on this website. I've run into a bit of a snag - Im using the Call UpdateBookmark function to replace previously entered information into the word document and im having issues implementing this into my existing code.

Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
        Call UpdateBookmark("Form", tbForm.Value)
        Call UpdateBookmark("Form2", tbForm.Value)
        Call UpdateBookmark("AGN", tbGN.Value)
        Call UpdateBookmark("AFN", tbFN.Value)
        Call UpdateBookmark("LGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("RGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("LFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("RFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("DOB", tbDOB.Value)
        Call UpdateBookmark("LT", cbLT.Value)
        Call UpdateBookmark("PN", tbPN.Value)
        Call UpdateBookmark("PN2", tbPN.Value)
        Call UpdateBookmark("PN3", tbPN.Value)
        Call UpdateBookmark("PN4", tbPN.Value)
        Call UpdateBookmark("Issued", tbissue.Value)
        Call UpdateBookmark("Expiry", tbexpiry.Value)
        Call UpdateBookmark("LTD", tbLTD.Value)
        Call UpdateBookmark("LTD2", tbLTD.Value)
        Call UpdateBookmark("Narrative", tbNarrative.Value)
        Call UpdateBookmark("PRR", tbPRR.Value)
        Call UpdateBookmark("Recommendation", cbRecommendation.Value)
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange

End Sub

I get an error which reads Compile error: ByRef argument type mismatch whenever I try to run the code - is anyone able to give me some assistance?? Thanks guys.

Entire code added for clarity

Option Explicit
Private Sub CheckBox1_Click()
    Dim en As Boolean
    en = Not CheckBox1.Value
    EnableControls Array(TBLPGN, TBLPFN), en

    If CheckBox1.Value = True Then ComboBoxLodge.Value = "Applicant"
    If CheckBox1.Value = False Then ComboBoxLodge.Value = "Lodging parent"

End Sub

'utility sub: enable/disable controls
Private Sub EnableControls(cons, bEnable As Boolean)
    Dim con
    For Each con In cons
        With con
            .Enabled = bEnable
            .BackColor = IIf(bEnable, vbWhite, RGB(200, 200, 200))
        End With
    Next con
End Sub
Private Sub cmdCancel_Click()
    Unload Me
End Sub

Private Sub cmdClear_Click()
tbForm.Value = Null
tbFN.Value = Null
tbGN.Value = Null
tbdob.Value = Null
cbLT.Value = Null
tbPN.Value = Null
tbissue.Value = Null
tbexpiry.Value = Null
tbLTD.Value = Null
tbNarrative.Value = Null
tbPRR.Value = Null
cbRecommendation.Value = Null
CheckBox1.Value = False
ComboBoxLodge.Value = Null
End Sub

Private Sub cmdOk_Click()
    Dim useAforB As Boolean
    useAforB = CheckBox1.Value

    Application.ScreenUpdating = False
    With ActiveDocument
        Call UpdateBookmark("Lodge", ComboBoxLodge.Value)
        Call UpdateBookmark("Form", tbForm.Value)
        Call UpdateBookmark("Form2", tbForm.Value)
        Call UpdateBookmark("AGN", tbGN.Value)
        Call UpdateBookmark("AFN", tbFN.Value)
        Call UpdateBookmark("LGN" useAforB _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("RGN", useAforB, _
                                     tbGN.Value, TBLPGN.Value)
        Call UpdateBookmark("LFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("RFN", useAforB, _
                                     tbFN.Value, TBLPFN.Value)
        Call UpdateBookmark("DOB", tbdob.Value)
        Call UpdateBookmark("LT", cbLT.Value)
        Call UpdateBookmark("PN", tbPN.Value)
        Call UpdateBookmark("PN2", tbPN.Value)
        Call UpdateBookmark("PN3", tbPN.Value)
        Call UpdateBookmark("PN4", tbPN.Value)
        Call UpdateBookmark("Issued", tbissue.Value)
        Call UpdateBookmark("Expiry", tbexpiry.Value)
        Call UpdateBookmark("LTD", tbLTD.Value)
        Call UpdateBookmark("LTD2", tbLTD.Value)
        Call UpdateBookmark("Narrative", tbNarrative.Value)
        Call UpdateBookmark("PRR", tbPRR.Value)
        Call UpdateBookmark("Recommendation", cbRecommendation.Value)
    End With
    Application.ScreenUpdating = True
    Unload Me
End Sub

Sub UpdateBookmark(BookmarkToUpdate As String, TextAtBookmark As String)
   Dim BookmarkRange As Range
   Set BookmarkRange = ActiveDocument.Bookmarks(BookmarkToUpdate).Range
   BookmarkRange.Text = TextAtBookmark
   ActiveDocument.Bookmarks.Add BookmarkToUpdate, BookmarkRange

End Sub

Private Sub Tbform_Change()
    tbForm = UCase(tbForm)
End Sub

Private Sub Tbpn_Change()
    tbPN = UCase(tbPN)
End Sub

Private Sub tbPRR_Change()
    tbPRR = UCase(tbPRR)
End Sub

Private Sub UserForm_Initialize()
    With cbLT
        .AddItem "lost"
        .AddItem "stolen"
    End With
    With cbRecommendation
        .AddItem "I believe there is an entitlement to have the l/t flag turned off as the applicant has not contributed to the loss of Passport number: "
        .AddItem "I believe there is no entitlement to have the l/t flag turned off as the applicant has contributed to the loss of Passport number:  "
    End With
    With ComboBoxLodge
        .AddItem "Lodging parent"
        .AddItem "Applicant"
     End With
     With CheckBox1
        CheckBox1.Value = True
    End With
lbl_Exit:
    Exit Sub
End Sub

Body:
Your Sub UpdateBookmark expect two String-type arguments, but in some cases you're passing four arguments: it's not clear what the intent is there.

Did you mean something like

Call UpdateBookmark("LGN", IIf(useAforB, tbGN.Value, TBLPGN.Value))

?


问:
addEventListener for the same event
So I have a few div tags that I have currently hidden, and I want to display them one after the other by hitting the enter key.

What I want to happen: I hit enter and the first div tag is revealed, and then I hit enter a second time to see the second div tag.

What is happening instead: I hit enter once and both div tags show up.

In this case, the first div tag I want to reveal is "intro", and the second is "body". I am running this website on jsbin, and I am using chrome, if that helps.

This is my JavaScript:

```<code>//***********************************************************

//  BODY MODULE

var bodyController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("evidence").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolBody: enterBool,
    enterListenBody: function(){
      enterListen();
    }
  }
})();

//***********************************************************

//  INTRO MODULE

var introController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("body").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolIntro: enterBool,
    enterListenIntro: function(){
      enterListen();
    }
  }
})();

 //***********************************************************

 //  CONTROL MODULE

 var controller = (function(introCtrl, bodyCtrl, evidenceCtrl, infoCtrl,
 conclusionCtrl){
  var eventListeners = function(){
     introCtrl.enterListenIntro();
     bodyCtrl.enterListenBody();
  };

  return{
    init: function(){
      eventListeners();
    }
  }
 })(introController, bodyController, evidenceController,
    infoController, conclusionController);

 //***********************************************************

 controller.init();
</code>```

答:
You can put the ids of your divs in an array, or you could assign a common class to all divs that you want to appear one by one.  Assuming the first, this code simply grabs the id of the next div to display from the array and increments the counter.  You could add more divs to the array and it would work.</p>

```<code>var divs = ["evidence", "body"];
var counter = 0;
document.addEventListener("keyup", function(event){
  if(counter < divs.length && event.keyCode == 13){
    document.getElementById(divs[counter]).style.display = 'block';
    counter++;
  }
});
</code>```

Title: addEventListener for the same event

Body:
So I have a few div tags that I have currently hidden, and I want to display them one after the other by hitting the enter key.

What I want to happen: I hit enter and the first div tag is revealed, and then I hit enter a second time to see the second div tag.

What is happening instead: I hit enter once and both div tags show up.

In this case, the first div tag I want to reveal is "intro", and the second is "body". I am running this website on jsbin, and I am using chrome, if that helps.

This is my JavaScript:

//***********************************************************

//  BODY MODULE

var bodyController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("evidence").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolBody: enterBool,
    enterListenBody: function(){
      enterListen();
    }
  }
})();

//***********************************************************

//  INTRO MODULE

var introController = (function(){
  var enterBool;

  var reveal = function(){
    if(enterBool){
      document.getElementById("body").style.display = "block";
      enterBool = false;
    }
  };

  var enterListen = function(){
    document.addEventListener("keydown", function(event){
      if(event.keyCode === 13){
        document.addEventListener("keyup", function(event){
          if(event.keyCode === 13){
            enterBool = true;
            reveal();
          }
        });
      }
    });
  };

  return{
    enterBoolIntro: enterBool,
    enterListenIntro: function(){
      enterListen();
    }
  }
})();

 //***********************************************************

 //  CONTROL MODULE

 var controller = (function(introCtrl, bodyCtrl, evidenceCtrl, infoCtrl,
 conclusionCtrl){
  var eventListeners = function(){
     introCtrl.enterListenIntro();
     bodyCtrl.enterListenBody();
  };

  return{
    init: function(){
      eventListeners();
    }
  }
 })(introController, bodyController, evidenceController,
    infoController, conclusionController);

 //***********************************************************

 controller.init();

Body:
You can put the ids of your divs in an array, or you could assign a common class to all divs that you want to appear one by one.  Assuming the first, this code simply grabs the id of the next div to display from the array and increments the counter.  You could add more divs to the array and it would work.

var divs = ["evidence", "body"];
var counter = 0;
document.addEventListener("keyup", function(event){
  if(counter < divs.length && event.keyCode == 13){
    document.getElementById(divs[counter]).style.display = 'block';
    counter++;
  }
});


问:
PHP Class on Class, get Parent
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

```<code>class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}
</code>```

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

答:
The only possible way here is to explicitly pass the reference to your root class object:

```<code>function root(){
   $this->son = new son($this);
   $this->daughter = new daughter($this);
}
</code>```

And accept it in the son and daughter constructors.

```<code>class son
{
    private $root;

    public function son($root)
    {
        $this->root = $root;
    }
}

class daughter
{
    private $root;

    public function daughter($root)
    {
        $this->root = $root;
    }

    public function doSomethingToBrother()
    {
        $this->root->son->some_method();
    }
}
</code>```

Title: PHP Class on Class, get Parent

Body:
Let's say I have three classes. One being the parent and two being "childs". However, I'm not using  class - extends -:

class root
{
   function root(){
      $this->son = new son();
      $this->daughter = new daughter();
   }
}
class son
{
 ...
}
class daughter
{
  ...
}

How could I call a function of son from a function of daughter? In other words, how could I reference the class root from son/daughter so that I could call functions of each other, from each other?

Body:
The only possible way here is to explicitly pass the reference to your root class object:

function root(){
   $this->son = new son($this);
   $this->daughter = new daughter($this);
}

And accept it in the son and daughter constructors.

class son
{
    private $root;

    public function son($root)
    {
        $this->root = $root;
    }
}

class daughter
{
    private $root;

    public function daughter($root)
    {
        $this->root = $root;
    }

    public function doSomethingToBrother()
    {
        $this->root->son->some_method();
    }
}


问:
Throttling API AJAX requests in Node (getting rate limited) - Using AXIOS for AJAX calls...
I am getting rate limited making too many requests per second to an API.

I am importing contacts into my database and mapping the data to my DB's schema.

The API  initially returns its contact 'groups' (ie categories) as an array of links which need to all have separate API calls made in order to retrieve the actual value.

I must iterate over every contact AND make separate API calls for every link in the array associated with each contact. I quickly hit my rate limit (max 10 per second according to API docs) and get a bunch of incomplete entries and errors as a result.

I am using Axios library to make the requests in Node.

My code is below - any help solving this dilemma would be greatly appreciated - thank you!

```<code>        .then(authUser => {

            // RETURN A LIST OF CONTACTS FROM API

            axios.get('url', {
              headers: {
                Authorization: credentials
              }
            })
            .then(response => {

              // MAP OVER EACH CONTACT
              response.data.map( contact => {

                let groups = contact.groupLinks.map(group => {

                    // MAP OVER EACH LINK IN EACH CONTACTS GROUP ARRAY AND MAKE AJAX REQUEST.
                    return axios.get(`${group.url}/?alt=json`, {
                      headers: {
                        Authorization: 'credentials'
                      }
                    })
                    .then(result => {
                      return result.data
                    })
                    .catch(err => {
                      console.error('FETCH GROUP MEMBERSHIP FAILURE', err.response.data.error)
                      next(err)
                    })
                  })

                return Promise.all(groups)
                .then( response => {
                  return [contact, response]
                })
</code>```

答:
I'm not familiar with AXIOS so I'm not sure this is possible.  When you use the array/object map to have each group call it's url how would an external variable be bound?  Could you do something like this?

// MAP OVER EACH CONTACT
response.data.map( contact => {
/*right here set an interval
*/
var interval = 0;
let groups = contact.groupLinks.map(group => {
    //increment interval
    interval += 150;

    // MAP OVER EACH LINK IN EACH CONTACTS GROUP ARRAY AND MAKE AJAX REQUEST.
    setInterval(function()
      {
          return axios.get(`${group.url}/?alt=json`, {
          headers: {
            Authorization: 'credentials'
          }
        })
        .then(result => {
          return result.data
        })
        .catch(err => {
          console.error('FETCH GROUP MEMBERSHIP FAILURE', err.response.data.error)
          next(err)
        })
      }, interval);
  })```

Otherwise I would move the processing of the group response to a recursive function that accepts the group returned from the API, makes the necessary calls, pop the group just called, then calls itself on a 150ms delay.

Body:
I am getting rate limited making too many requests per second to an API.

I am importing contacts into my database and mapping the data to my DB's schema.

The API  initially returns its contact 'groups' (ie categories) as an array of links which need to all have separate API calls made in order to retrieve the actual value.

I must iterate over every contact AND make separate API calls for every link in the array associated with each contact. I quickly hit my rate limit (max 10 per second according to API docs) and get a bunch of incomplete entries and errors as a result.

I am using Axios library to make the requests in Node.

My code is below - any help solving this dilemma would be greatly appreciated - thank you!

        .then(authUser => {

            // RETURN A LIST OF CONTACTS FROM API

            axios.get('url', {
              headers: {
                Authorization: credentials
              }
            })
            .then(response => {

              // MAP OVER EACH CONTACT
              response.data.map( contact => {

                let groups = contact.groupLinks.map(group => {

                    // MAP OVER EACH LINK IN EACH CONTACTS GROUP ARRAY AND MAKE AJAX REQUEST.
                    return axios.get(`${group.url}/?alt=json`, {
                      headers: {
                        Authorization: 'credentials'
                      }
                    })
                    .then(result => {
                      return result.data
                    })
                    .catch(err => {
                      console.error('FETCH GROUP MEMBERSHIP FAILURE', err.response.data.error)
                      next(err)
                    })
                  })

                return Promise.all(groups)
                .then( response => {
                  return [contact, response]
                })

Body:
I'm not familiar with AXIOS so I'm not sure this is possible.  When you use the array/object map to have each group call it's url how would an external variable be bound?  Could you do something like this?

// MAP OVER EACH CONTACT
response.data.map( contact => {
/*right here set an interval
*/
var interval = 0;
let groups = contact.groupLinks.map(group => {
    //increment interval
    interval += 150;

    // MAP OVER EACH LINK IN EACH CONTACTS GROUP ARRAY AND MAKE AJAX REQUEST.
    setInterval(function()
      {
          return axios.get(`${group.url}/?alt=json`, {
          headers: {
            Authorization: 'credentials'
          }
        })
        .then(result => {
          return result.data
        })
        .catch(err => {
          console.error('FETCH GROUP MEMBERSHIP FAILURE', err.response.data.error)
          next(err)
        })
      }, interval);
  })

Otherwise I would move the processing of the group response to a recursive function that accepts the group returned from the API, makes the necessary calls, pop the group just called, then calls itself on a 150ms delay.


问:
How do I extend Django admin's DateFieldListFilter class ?
I am a newbie with Django and have a model with a DateTime field which is shown in the django admin.

In the list_filter option when I specify the fieldname I get the basic Django filter interface for date fields with 4 links (today, this month, past 7 days, etc.)

I now want to add a "next 7 days" option. This will require a minor tweak by extending the DateFieldListFilter class. However, Django throws the system check (admin.E114) The value of 'list_filter[0]' must not inherit from 'FieldListFilter'. when I try to extend it.

The only way it seems possible after a bit of search is by extending the SimpleListFilter class but it seems like a lot of work for such a small thing. (since I will have to duplicate functionality already taken care of in DateFieldListFilter)

Is there a simpler way of achieving this?

答:
Assume we have a model called Book with a published_at field which is a DateTimeField.  You could then achieve this type of filtering by doing something like this (code is based on DateFieldListFilter as seen in https://github.com/django/django/blob/4ad2f862844d35404e4798b3227517625210a72e/django/contrib/admin/filters.py):

```<code>import datetime

from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter
from django.utils.translation import gettext_lazy as _

class MyDateTimeFilter(DateFieldListFilter):
    def __init__(self, *args, **kwargs):
        super(MyDateTimeFilter, self).__init__(*args, **kwargs)

        now = timezone.now()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        today = now.date()

        self.links += ((
            (_('Next 7 days'), {
                self.lookup_kwarg_since: str(today),
                self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
            }),
        ))

class BookAdmin(admin.ModelAdmin):
    list_filter = (
        ('published_at', MyDateTimeFilter),
    )
</code>```

Body:
Assume we have a model called Book with a published_at field which is a DateTimeField.  You could then achieve this type of filtering by doing something like this (code is based on DateFieldListFilter as seen in https://github.com/django/django/blob/4ad2f862844d35404e4798b3227517625210a72e/django/contrib/admin/filters.py):

import datetime

from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter
from django.utils.translation import gettext_lazy as _

class MyDateTimeFilter(DateFieldListFilter):
    def __init__(self, *args, **kwargs):
        super(MyDateTimeFilter, self).__init__(*args, **kwargs)

        now = timezone.now()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        today = now.date()

        self.links += ((
            (_('Next 7 days'), {
                self.lookup_kwarg_since: str(today),
                self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
            }),
        ))

class BookAdmin(admin.ModelAdmin):
    list_filter = (
        ('published_at', MyDateTimeFilter),
    )


问:
Failed when running the codes that mixed java with androidstudio

My project struct

("https://i.stack.imgur.com/EykkL.png")

Build.gradle content as below

```<code>apply plugin: 'java'
apply plugin: 'kotlin'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}

// override the sourceSet flow other answers.
sourceSets {
    main.java.srcDirs+= 'src/main/java'
    main.kotlin.srcDirs+= 'src/main/kotlin'
    main.resources.srcDirs += 'src/main/resources'
}
</code>```

Exception when I run it

It may be compiled successfuly but when I run the kotlin codes.
It throws the exception below. And the java codes run ok.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
    at KotMainKt.main(kotMain.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more
</code>```

答:
I add the codes belows at build.gradle and fix this problem.

Links:Configuring Gradle with Kotlin

jar {
    manifest {
        attributes 'Main-Class': 'KotMainKt'
    }

```<code>from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
</code>```

}

Body:
My project struct

("https://i.stack.imgur.com/EykkL.png")

Build.gradle content as below

apply plugin: 'java'
apply plugin: 'kotlin'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre8:$kotlin_version"
}

sourceCompatibility = "1.7"
targetCompatibility = "1.7"
buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}

// override the sourceSet flow other answers.
sourceSets {
    main.java.srcDirs+= 'src/main/java'
    main.kotlin.srcDirs+= 'src/main/kotlin'
    main.resources.srcDirs += 'src/main/resources'
}

Exception when I run it

It may be compiled successfuly but when I run the kotlin codes.
It throws the exception below. And the java codes run ok.

Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
    at KotMainKt.main(kotMain.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    ... 1 more

Body:
I add the codes belows at build.gradle and fix this problem.

Links:Configuring Gradle with Kotlin

jar {
    manifest {
        attributes 'Main-Class': 'KotMainKt'
    }

from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }

}


问:
text in index.html is bottom aligned, I want it to be top alined
I have a html file that when renders the text is bottom aligned. When the web-browser is open wide, the whole text is very far from the top as it can been seen here:

Now if I make the web-browser window narrower the text goes up like this:

Here is what I have in the html file:

```<code><div class="post">

        <h1>Title of Sample Work 2</h1>

        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>

        <p>Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.</p>
</code>```

and here is what I have in the css:

```<code>.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}
</code>```

I tried to add position: absolute; to .post{ like this:

```<code>.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
    position: absolute;
}
</code>```

but then it messes up left and right margins as it can be seen here:

As can be seen the right margin now is much smaller than left margin.

Any suggestion on how I align the text to the top without messing up left and right margin is really appreciated.

答:
You could use a meadia query to set the margin based on the width of the screen.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp </p>

Body:
I have a html file that when renders the text is bottom aligned. When the web-browser is open wide, the whole text is very far from the top as it can been seen here:

Now if I make the web-browser window narrower the text goes up like this:

Here is what I have in the html file:

Title of Sample Work 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.

Integer dolor nibh, blandit et suscipit in, egestas eu diam. Maecenas imperdiet posuere odio, et tempus sapien efficitur et. Aliquam nec augue efficitur, consectetur elit at, efficitur purus. Fusce sem augue, congue ac metus et, molestie tempus velit. Quisque vitae arcu porttitor, porta augue mollis, consectetur magna. Aenean ante orci, sagittis quis vehicula sit amet, finibus in risus. Sed eu elementum urna. Curabitur quis consequat nunc. Sed sollicitudin purus ac leo volutpat, sit amet rhoncus neque malesuada. Phasellus enim ante, ornare non sapien non, mattis sollicitudin lorem. Phasellus suscipit magna felis, sed ullamcorper tellus molestie ut. Phasellus tincidunt fringilla imperdiet. Fusce rhoncus ultrices sapien, vitae dignissim nunc tincidunt in.

and here is what I have in the css:

.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

I tried to add position: absolute; to .post{ like this:

.post {
    margin-top: 5em;
    margin-left: 2em;
    margin-right: 2em;
    position: absolute;
}

but then it messes up left and right margins as it can be seen here:

As can be seen the right margin now is much smaller than left margin.

Any suggestion on how I align the text to the top without messing up left and right margin is really appreciated.


问:
How can i catch error in C# from RAISERROR of sql server?
Here is my stored procedure code called "uspTest"

```<code>BEGIN TRY
SELECT 3 / 0;
END TRY

BEGIN CATCH
RAISERROR('D', 16, 3);
END CATCH
</code>```

And Here is my c# code in visual studio

```<code>    public IHttpActionResult RegisterUser(RegisterModelView registerViewModel)
    {

        try
        {
            using (AusHerbEntities ctx = new AusHerbEntities())
            {
                ctx.uspTest();
                Console.Write("i am in try block");
            }

        }

        catch (Exception e)
        {
            Console.Write(e.Message);

        }
        return Ok();
    }
</code>```

When I run this code, the Catch block in C# code is not called, but I expect it to be called because the Stored Procedure raises error.

How can I get this code work?

I just want to do RAISERROR in catch block in Stored Procedure and catch the error in c# code.

答: Do you need the try-catch in SQL? If you're only using it to rollback the transaction, then you can simply set XACT_ABORT ON and dispense with the try-catch. The transaction will be rolled back, and any error will bubble through to the client. Here is a good article on the subject: https://www.simple-talk.com/sql/t-sql-programming/defensive-error-handling/</p>

Body:
Here is my stored procedure code called "uspTest"

BEGIN TRY
SELECT 3 / 0;
END TRY

BEGIN CATCH
RAISERROR('D', 16, 3);
END CATCH

And Here is my c# code in visual studio

    public IHttpActionResult RegisterUser(RegisterModelView registerViewModel)
    {

        try
        {
            using (AusHerbEntities ctx = new AusHerbEntities())
            {
                ctx.uspTest();
                Console.Write("i am in try block");
            }

        }

        catch (Exception e)
        {
            Console.Write(e.Message);

        }
        return Ok();
    }

When I run this code, the Catch block in C# code is not called, but I expect it to be called because the Stored Procedure raises error.

How can I get this code work?

I just want to do RAISERROR in catch block in Stored Procedure and catch the error in c# code.


问:
NodePort, LoadBalance Services - What happens with Routing?
The k8s docs aren't very clear what happens with routing when using the different service types, leading me to a series of questions:

To help the question, assume the following cluster setup:

3 Nodes: N_a, N_b, N_c

1 Service: S_1

2 Pods: P_x1, P_x2 that are part of the service S_1

P_x1 is running on N_a

P_x2 is running on N_b

1) When using a NodePort for S_1 using port x, do ALL nodes in a cluster make the service available on port x? OR do ONLY the nodes running the pods that make up the service make the service available on port x? So in both scenarios, N_a and N_b will make S_1 available on port x, but can I hit N_c on port x?

2) Using NodePort for S_1 still, if I hit N_a on port x, will I only be routed to P_x1 (e.g., the pods for that service running locally on the Node), or may I be routed to P_x2, so off the Node and over the network again?

3) If I run S_1 as a LoadBalanced service, will the load-balancer provisioned only route requests to N_a and N_b? With those requests when hitting N_a and N_b only being routed to pods P_x1 and P_x2 respectively? So one hop over the network, or will it talk to all three nodes and rely on them each doing a second level of routing/load-balancing? (Which seems quite inefficient).

4) Does the Ingress controller function any differently for routing (other than being L7 rather than L4) than a LoadBalanced service?

答:
1) Yes. NodePort opens a port on all worker nodes. When you create a Service, an iptables rule is created on all worker nodes. When a pod on any node accesses this Service's IP, the iptables rule on the physical node where the pod resides will redirect its packets accordingly.

2) Both. A Service does WRR load-balancing across all the associated pods.

3) I do bare-metal deployments so I can't answer this qn.

4) Afaik, Ingress is a replacement to the LoadBalancer. Instead of depending on the cloud provider's reverse proxy, you deploy your own Ingress that runs in the k8s cluster.