text:
Q: Fontpath is not passed through intent In my app there is an activity say Activity A which has an image view with some text views. code is listed below
    public class EidCardFinal extends Activity {

        private ImageView imageView;
        private TextView receiver, sender, messagebody;
        private Intent intent;
        private Bundle bundle;
        private static final int FONT_SELECT = 1;

        // public String filepath = "MyFileStorage";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_eid_card_final);
            intent = getIntent();
            String message1 = intent.getStringExtra("RECEIVER");
            String message2 = intent.getStringExtra("SENDER");
            String message3 = intent.getStringExtra("MESSAGEBODY");
            String check_click = intent.getStringExtra("bttnclick");
            imageView = (ImageView) findViewById(R.id.imageView1);
            receiver = (TextView) findViewById(R.id.textView1);
            sender = (TextView) findViewById(R.id.textView2);
            messagebody = (TextView) findViewById(R.id.textView3);
            receiver.setText(message1);
            sender.setText(message2);
            messagebody.setText(message3);

            // Selected image id
            if ("BUTTONCLICK".equals(check_click)) {
                String path = intent.getStringExtra("image");
                Uri myUri = Uri.parse(path);
                imageView.setImageURI(myUri);

            } else {
                int position = intent.getExtras().getInt("id");
                ImageAdapter imageAdapter = new ImageAdapter(this);

                // ImageView imageView = (ImageView) findViewById(R.id.imageView1);
                imageView.setImageResource(imageAdapter.thumbIds[position]);

    case R.id.change_fonts:
                Intent fontintent = new Intent();
                bundle = getIntent().getExtras();
                fontintent.putExtras(bundle);
                fontintent.setClass(getApplicationContext(), FontSelection.class);
                this.startActivityForResult(fontintent, FONT_SELECT);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == FONT_SELECT) {
                Bundle pathadd= data.getExtras();
                String fontadd = pathadd.getString("FONTPATH");

                //intent = getIntent();
                /*String message1 = data.getStringExtra("RECEIVER");
                String message2 = data.getStringExtra("SENDER");
                String message3 = data.getStringExtra("MESSAGEBODY");
                //String check_click = intent.getStringExtra("bttnclick");
                imageView = (ImageView) findViewById(R.id.imageView1);
                receiver = (TextView) findViewById(R.id.textView1);
                sender = (TextView) findViewById(R.id.textView2);
                messagebody = (TextView) findViewById(R.id.textView3);
                receiver.setText(message1);
                sender.setText(message2);
                messagebody.setText(message3);*/

                //bundle = getIntent().getExtras();
                Typeface tyfa = Typeface.createFromAsset(getAssets(), fontadd);
                receiver.setTypeface(tyfa);
                sender.setTypeface(tyfa);
                messagebody.setTypeface(tyfa);
                s

}
    }
}

From menu, user is taken to another activity say Activity B from where a custom font can be selected for Activity A. Code is listed below
public class FontSelection extends Activity {

String[] fontpath = { "fonts/android_7.ttf", "fonts/doridrobot.ttf",
        "fonts/droidsansmono.ttf", "fonts/droidserif-bold.ttf",
        "fonts/green-avocado.ttf", "fonts/lokicola.ttf",
        "fonts/outwrite.ttf", "fonts/painting-the-light.ttf",
        "fonts/roboto-black.ttf", "fonts/roboto-boldcondensed.ttf",
        "fonts/roboto-medium.ttf", "fonts/roboto-regular.ttf" };

String[] fontname = { "android_7", "doridrobot", "droidsansmono",
        "droidserif-bold", "green-avocado", "lokicola", "outwrite",
        "painting-the-light", "roboto-black", "roboto-boldcondensed",
        "roboto-medium", "roboto-regular" };

private Intent fontpathintent = new Intent();
private Bundle bundle1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_font_selection);

    RadioButton radio1 = (RadioButton) findViewById(R.id.radioButton1);
    Typeface tf1 = Typeface.createFromAsset(getAssets(), fontpath[0]);
    radio1.setTypeface(tf1);
    radio1.setText(fontname[0]);

    RadioButton radio2 = (RadioButton) findViewById(R.id.radioButton2);
    Typeface tf2 = Typeface.createFromAsset(getAssets(), fontpath[1]);
    radio2.setTypeface(tf2);
    radio2.setText(fontname[1]);

    RadioButton radio3 = (RadioButton) findViewById(R.id.radioButton3);
    Typeface tf3 = Typeface.createFromAsset(getAssets(), fontpath[2]);
    radio3.setTypeface(tf3);
    radio3.setText(fontname[2]);

    RadioButton radio4 = (RadioButton) findViewById(R.id.radioButton4);
    Typeface tf4 = Typeface.createFromAsset(getAssets(), fontpath[3]);
    radio4.setTypeface(tf4);
    radio4.setText(fontname[3]);

    RadioButton radio5 = (RadioButton) findViewById(R.id.radioButton5);
    Typeface tf5 = Typeface.createFromAsset(getAssets(), fontpath[4]);
    radio5.setTypeface(tf5);
    radio5.setText(fontname[4]);

    RadioButton radio6 = (RadioButton) findViewById(R.id.radioButton6);
    Typeface tf6 = Typeface.createFromAsset(getAssets(), fontpath[5]);
    radio6.setTypeface(tf6);
    radio6.setText(fontname[5]);

    RadioButton radio7 = (RadioButton) findViewById(R.id.radioButton7);
    Typeface tf7 = Typeface.createFromAsset(getAssets(), fontpath[6]);
    radio7.setTypeface(tf7);
    radio7.setText(fontname[6]);

    RadioButton radio8 = (RadioButton) findViewById(R.id.radioButton8);
    Typeface tf8 = Typeface.createFromAsset(getAssets(), fontpath[7]);
    radio8.setTypeface(tf8);
    radio8.setText(fontname[7]);

    RadioButton radio9 = (RadioButton) findViewById(R.id.radioButton9);
    Typeface tf9 = Typeface.createFromAsset(getAssets(), fontpath[8]);
    radio9.setTypeface(tf9);
    radio9.setText(fontname[8]);

    RadioButton radio10 = (RadioButton) findViewById(R.id.radioButton10);
    Typeface tf10 = Typeface.createFromAsset(getAssets(), fontpath[9]);
    radio10.setTypeface(tf10);
    radio10.setText(fontname[9]);

    RadioButton radio11 = (RadioButton) findViewById(R.id.radioButton11);
    Typeface tf11 = Typeface.createFromAsset(getAssets(), fontpath[10]);
    radio11.setTypeface(tf11);
    radio11.setText(fontname[10]);

    RadioButton radio12 = (RadioButton) findViewById(R.id.radioButton12);
    Typeface tf12 = Typeface.createFromAsset(getAssets(), fontpath[11]);
    radio12.setTypeface(tf12);
    radio12.setText(fontname[11]);

}

public void onRadioButtonClick(View view) {

    bundle1 = getIntent().getExtras();

    // Is the button now checked?
    boolean checked = ((RadioButton) view).isChecked();
    // Check which radio button was clicked
    switch (view.getId()) {

    case R.id.radioButton1:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[0]);

        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        fontpathintent.putExtras(bundle1);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton2:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[1]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton3:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[2]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton4:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[3]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton5:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[4]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton6:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[5]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton7:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[6]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton8:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[7]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton9:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[8]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton10:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[9]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        break;
    case R.id.radioButton11:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[10]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    case R.id.radioButton12:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[11]);
        fontpathintent.putExtras(bundle1);
        fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        startActivity(fontpathintent);
        break;
    }
}

my problem is, upon selection of font, there is no change in activity A, i mean font in activity A remains unchanged.
changed the code, but still no luck
case R.id.radioButton1:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[0]);

        // fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        // fontpathintent.putExtras(bundle1);
        // startActivity(fontpathintent);
        setResult(1, fontpathintent);
        finish();
        break;
    case R.id.radioButton2:
        if (checked)
            fontpathintent.putExtra("FONTPATH", fontpath[1]);
        // fontpathintent.setClass(getApplicationContext(),EidCardFinal.class);
        // fontpathintent.putExtras(bundle1);
        // startActivity(fontpathintent);
        setResult(1, fontpathintent);
        finish();
        break;

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            // Bundle pathadd= data.getExtras();
            String customfont = data.getStringExtra("FONTPATH");
            // String fontadd = pathadd.getString("FONTPATH");

            // intent = getIntent();
            /*
             * String message1 = data.getStringExtra("RECEIVER"); String
             * message2 = data.getStringExtra("SENDER"); String message3 =
             * data.getStringExtra("MESSAGEBODY"); //String check_click =
             * intent.getStringExtra("bttnclick"); imageView = (ImageView)
             * findViewById(R.id.imageView1); receiver = (TextView)
             * findViewById(R.id.textView1); sender = (TextView)
             * findViewById(R.id.textView2); messagebody = (TextView)
             * findViewById(R.id.textView3); receiver.setText(message1);
             * sender.setText(message2); messagebody.setText(message3);
             */

            // bundle = getIntent().getExtras();
            Typeface tyfa = Typeface.createFromAsset(getAssets(),
                    customfont);
            receiver.setTypeface(tyfa);
            sender.setTypeface(tyfa);
            messagebody.setTypeface(tyfa);

        }

i think there is some problem while calling onActivityResult() as i have tried below line of code, but no result as well. can anyone suggest what is going wrong?
tyfa = Typeface.createFromAsset(getAssets(),
                        "fonts/outwrite.ttf");

A: use another field and give each item with unique id then use getextra and putextra methods may be it will help

A: You should not start the first activity again, instead of that you should set results of the secont activity and close it. The first activity will then get the results in the onActivityResult method.
Here is an example how that works

A: problem solved. Actually i was using requestCode instead of resultcode in setResult(), and that was the culprit.


text:
Q: Highstock: Plot name labels I am using the Highstock and I've been reading the API documentation to look for the plot labeling however, was unsuccessful.
When I do something like
xAxis: {
               labels: {
               enabled: true,
               name: plot one name,
               floor: 0,
             }
           }

or
series: [{
data: XData,
name: plot one name
}

it does not give me the label at the bottom.
It works in the highchart, but highstock. Is there a documentation / APi to add plot label inside the graph ?
for example, in the following link of the highchart is the plot label of "tokyo" and "london" http://www.highcharts.com/demo/line-labels

A: The labels you are looking for is called the legend (API).
It is disabled by default in Highstock. You can enable it by adding this code:
legend: {
    enabled: true
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting back to the first page in the stack in Flutter In my Flutter app I want to get back to the home page by removing everything but the first page from the stack.
I've found two ways of doing it and they both seem to work but since I'm fairly new to Flutter I was wondering of one of these methods is best :-
Navigator.of(context).popUntil((route) => route.isFirst);

Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);

A: You can use both of them.
But, in my own opinion (as I read the docs), in order to use the pushNamedAndRemoveUntil method, you need to name your routes.
On the other hand, If you do not use named routes, you can use the popUntil method. Because it's not using named routes and much simpler.

A: The answer is pushAndRemoveUntil. There is a method like this available for you, if you don't want to use named route in your flutter app. Read about it here.
So, now what you can do it:
// It accepts Route object, so we can use Material Page Route
// We name your first page as HomePage, so don't get Confused
Navigator.pushAndRemoveUntil(context,
   MaterialPageRoute(builder: (context) => HomePage()),
   (_) => false
);

Read about MaterialPageRoute class, and add it to your bucket, because it is a very useful thing, if you don't know about it already.


text:
Q: Select continuous groups by field, using the specified order I need help solving the following tasks, where I need to use window functions. But I can not figure out how to get the id from a subquery sample to sort and apply aggregating functions:
Given table:
create temp table users(id bigserial, group_id bigint);
insert into users(group_id)
values (1), (1), (1), (2), (1), (3);

In this table, sorted by ID, you need:
to allocate continuous groups on group_id taking into account the

*

*specified order of rows group (there are 4 of them)

*count the number of records in each group

*calculate the minimum record ID in the group
The result should be:
one of the columns is the group_id, another is the number of records, or the minimum id value, depending on the task. Rows should be sorted by id.
Output like this:
 group_id | count
----------+-------
        1 |     3
        2 |     1
        1 |     1
        3 |     1

Partial solution of the second task, without ordering:
SELECT COUNT(*), group_id
FROM ( SELECT id, id - ROW_NUMBER() OVER (PARTITION BY group_id ORDER
BY id) AS res, group_id FROM users)new_table
GROUP BY group_id,res;

That returns:
 group_id | count
----------+-------
        1 |     3
        3 |     1
        1 |     1
        2 |     1

A: I would guess this is what you are looking for:
SELECT group_id
     , count(*) AS row_count  -- 2. count the number of records in each group
     , min(id)  AS min_id     -- 3. calculate the minimum record ID in the group
FROM  (
   SELECT id
        , group_id
        , id - row_number() OVER (PARTITION BY group_id ORDER BY id) AS res
   FROM   users
   ) sub
GROUP  BY group_id, res
ORDER  BY min_id;  -- 1. specified order of rows group

Of course, if there can be gaps in the serial column id, you have to use:
  row_number() OVER (ORDER BY id)
- row_number() OVER (PARTITION BY group_id ORDER BY id) AS res

Typically, gaps in serial columns have to be expected.
Related answers with more explanation and links:

*

*Select longest continuous sequence

*Grouping or Window

*Serial numbers per group of rows for compound key


text:
Q: advantages of tensorflow over numpy for general computation I was reading over this tensorflow tutorial which specifies how to run a simulation of water ripples using tensorflow. My understanding is that tensorflow variables and placeholders are used in place of generic python variables, but is there any specific (i.e. performance) advantage to using tensorflow over just numpy?

A: First of all, there are very fundamental differences between libraries like TensorFlow and NumPy. In TensorFlow you basically define a computation graph in a symbolic manner and nothing is computed unless you call the function run from class Session. It is very important to be careful about calling the run function only once (or only if required) so that you avoid redundant computation.
Speaking of performance, libraries like TensorFlow and Theano are good at pruning and optimizing the whole computation graph (before running) and using very optimized kernels to run the operations in the graph on available devices, including GPU. GPU is very fast and useful in doing matrix operations, but NumPy can not take advantage of it. NumPy runs the computation mostly using C++ based code, but unlike TensorFlow it does not apply a graph optimization to the whole computation graph. In fact, there is no such a thing as graph in NumPy. TensorFlow takes the whole computation to a different runtime space and then returns the concrete results after actual execution.
In case you are curious about what exactly is a kernel, the original TensorFlow paper defines it as: "A kernel is a particular implementation of an operation that can be run on a particular type of device (e.g., CPU or GPU)."
There are fairly simple, but good benchmarks at this blog post which show by numbers how much and when TensorFlow is better than NumPy.
To understand how actually TensorFlow works, This post may be useful too.
If your problem is not a big one which needs to deal with large scale matrices and lots of matrix operations, then I would say NumPy is easier to use and you don't need to be worried about performance.


text:
Q: Pipeline metacharacter in variable in bash In my bash script I need to check if logger binary exists. If so, I pipe the application output to it.
Edit--------
| It needs to be piping, the application should work permanently.
---------------
I tried to put the pipeline stuff to a variable and use it later. Something like:
if [ -e /usr/bin/logger ]; then
  OUT=| /usr/bin/logger
fi

application  param1  2>&1   $OUT   >  /dev/null &

but it doesn't work, the output is not piped to the logger. If I put the pipeline stuff directly into the application startline, it works. Unfortunately the real script becomes too complicated if I use command lines with and without logger stuff in if/else statements - the reason is that I already have if/else there and adding new ones will double the number of cases.
Simple test application
TMP=| wc -m
echo aas bdsd vasd $TMP

gives

$ ./test.sh
  0
  aas bdsd vasd

Seems that somehow command1 and command2 are executed separately.
I managed to solve the problem (in both test and real scripts) using eval and putting the conditional stuff in double quotes.
TMP="| wc -m"
eval echo aas bdsd vasd $TMP

$ ./test.sh
  14

It feels like a workaround. What is the right way to do it?

A: The correct way to do this is to use if/else:
if [ -e /usr/bin/logger ]
then
    application  param1  2>&1 | /usr/bin/logger >  /dev/null &
else
    application  param1 > /dev/null 2>&1 &
fi

Edit:
In the case of a complex construct, you should use a function:
foo () {
    if [ ... ]
    then
        do_something
    else
        something_else
    fi
    while [ ... ]
    do
        loop_stuff
    done
    etc.
}

Then your log/no log if stays simple:
if [ -e /usr/bin/logger ]
then
    foo  2>&1 | /usr/bin/logger >  /dev/null &
else
    foo > /dev/null 2>&1 &
fi

A: Just to throw another option into the mix, you could move the pipe outside the variable:
if [ -e /usr/bin/logger ]; then
    logcmd=/usr/bin/logger
else
    logcmd=/bin/cat
fi

application param1 2>&1 | $logcmd >/dev/null &

This avoids having duplicate commands for the two cases (or having to wrap everything in functions, per Dennis' suggestion).  The disadvantage is that it's inefficient about how it handles the case where logger doesn't exist -- creating a cat process just to feed output to /dev/null is a complete waste.  But a cat process isn't that big a resource drain, so if it makes your code cleaner it might be worth the waste.

A: Try
if [ -e /usr/bin/logger ]; then
  logger $(application  param1 2>&1)
fi

General rule: don't put commands inside variables and call it through the variable. Just run it directly off your script.

A: I tried a similar code and specified the last line like this and it worked
application  param1  &2>1   ${OUT}   >  /dev/null

A: While ghostdog74's answer is correct, there is certainly a way to make this work
if [ -e /usr/bin/logger ]; then
  OUT='| /usr/bin/logger'
fi

eval application param1 2>&1 $OUT > /dev/null

But I highly recommend that you think twice before using eval, and then don't use it.


text:
Q: Launching FastAPI/uvicorn app as a Windows Task on startup in Windows Server 2019 I'm trying to setup Windows Server 2019 to launch my FastAPI/uvicorn application(s) on startup, regardless of a user actually logging in.
The settings in the attached screenshots have successfully "run" the task, but when I curl an endpoint, the connection is refused. By contrast, if I just run the command to launch the app manually, it responds successfully.
Task properties, General tab
Task properties, Triggers/Edit Trigger tab
Task properties, Actions/Edit Action tab
Task properties, Conditions tab
Task properties, Settings tab
The content of my server.py file:
import uvicorn
from multiprocessing import cpu_count, freeze_support

def start_server(host="ip goes here",
                 port=port goes here,
                 num_workers=1,
                 loop="asyncio",
                 reload=False):
    uvicorn.run("main:app",
                host=host,
                port=port,
                workers=num_workers,
                loop=loop,
                reload=reload
                )

if __name__ == '__main__':
    freeze_support()
    start_server(num_workers=2)

What am I doing wrong? Is there a better way to accomplish what I'm going for here?


text:
Q: Buildozer, WSL adb not finding device, adb in Powershell works I have a python program using PySimpleGUI. It works on Windows, a pure Linux machine and it also works on the WSL. I'd like to use it on my phone(Pixel 7 pro). Buildozer makes the apk file but during the process 'buildozer android deploy run logcat' it runs the adb devices cmd and finds nothing. The adb devices from a PowerShell works fine. It probably has something to do with the virtual machine WSL provides. I've queried google and read pages of information and suggestions and nothing so far works.
Please let me know if I can provide anymore info that will help solve this.
I've tried running the adb in the build environment manually, outside build script of buildozer, with the same results, no devices found.
I'd like to move on the next step of trying or troubleshooting the app on my phone.
Thanks in advance, Craig


text:
Q: Why is my Select Option showing behind the jquery UI dialog? I am trying to make a character Creation form and am using select fields for certain information of which there are only so many possibilities but when I run the script my options show up behind the dialog (which the select element is placed in) that I created how can I fix this???
<!doctype html>

  <meta charset="utf-8">
  <title>Icebreaker Characters</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/trontastic/jquery-ui.css">

All Form Fields are required.

   <form>
    <fieldset>
     Code Name:
     <input type="text" name="cname" id="cname" class="text ui-widget-content ui-corner-all">
     First Name:
     <input type="text" name="fname" id="fname" class="text ui-widget-content ui-corner-all">
     Middle Name:
     <input type="text" name="mname" id="mname" class="text ui-widget-content ui-corner-all">
     Last Name:
     <input type="text" name="lname" id="lname" class="text ui-widget-content ui-corner-all">
     Eye Color:
     <input type="color" name="eye" id="eye" class="text ui-widget-content ui-corner-all">
     Hair Color:
     <input type="color" name="hcol" id="hcol" class="text ui-widget-content ui-corner-all">
     <fieldset>
      Hair Style:
      <select name="hstyle" id="hstyle">
       <option>Straight</option>
       <option>Curly</option>
      </select>
     </fieldset>

     <input type="submit" tabindex="-1" style="position:absolute; top:-1000px;">
    </fieldset>
   </form>

Existing Characters:

       Code Name

       First Name

       Middle Name

       Last Name

       Eye Color

       Hair Color

  <button id="Create-character">Create New Character</button>

A: Set the z-index of .ui-selectmenu-menu to 102.
The z-index of the dialog is greater than the select menu.
You can see the working fiddle here: https://jsfiddle.net/th1x3xro/3/


text:
Q: User-defined function results do not appear in Excel I wrote user-defined function called myaverage, which calculates weighted average of 3 numbers:
Function myaverage(x, y, z) As Double
    Dim a As Single
    Dim x As Double
    Dim y As Double
    Dim z As Double
    a = 0.4 * x + 0.5 * y + 0.1 * z
    myaverage = a
End Function

But if I type  =myaverage(A1:A3), I cannot see the result.

A: Simplify your function to something like this:
Function myaverage(x As Double, y As Double, z As Double) As Double
    myaverage = 0.4 * x + 0.5 * y + 0.1 * z
End Function

In Excel cell, use this:
= myaverage(A1, B1, C1)

A: You had double declarations. I mean, x was alreaday declared in the signature and you re-declared it in the function body. So this will work:
Public Function myaverage(x As Double, y As Double, z As Double) As Double
    myaverage = 0.4 * x + 0.5 * y + 0.1 * z
End Function

*

*Do not forget the function must be placed in Module (e.g. Module1). See Step 2 in this tutorial.

*If you change the code, always re-test your function for language errors using menu Debug > Compile. If errors are shown, fix them.

A: If you want to use range A1:C1 as the input argument then UDF has to be written accordingly:
Public Function RangeAverage(rRef As Range) As Double
    With rRef
        RangeAverage = 0.4 * .Cells(1).Value2 + 0.5 * .Cells(2).Value2 + 0.1 * .Cells(3).Value2
        End With
End Function


text:
Q: iOS11 handle firebase push notification when app removed from background Code :
FirebaseApp.configure()
application.registerForRemoteNotifications()
requestNotificationAuthorization(application: application)

NotificationCenter.default.addObserver(self, selector:
    #selector(tokenRefreshNotification), name:
    NSNotification.Name.InstanceIDTokenRefresh, object: nil)

//in iOS9 called didreceiveremote method when app is killed
let notification = launchOptions?[.remoteNotification]
if notification != nil {
    self.application(application, didReceiveRemoteNotification: notification as! [AnyHashable : Any])
}

@objc func tokenRefreshNotification(_ notification: Notification) {
    if let refreshedToken = InstanceID.instanceID().token() {
        print("InstanceID token: \(refreshedToken)")

        UserDefaults.standard.setPushToken(value:refreshedToken)
    }

}

func requestNotificationAuthorization(application: UIApplication) {
    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
    } else {
        let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

}

extension AppDelegate : UNUserNotificationCenterDelegate {
    // iOS10+, called when presenting notification in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) willPresentNotification: \(userInfo)")
        //TODO: Handle foreground notification
        completionHandler([.alert])
    }

    // iOS10+, called when received response (default open, dismiss or custom action) for a notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        NSLog("[UserNotificationCenter] applicationState: \(applicationStateString) didReceiveResponse: \(userInfo)")
        //TODO: Handle background notification
        if UIApplication.shared.applicationState == .active {
            //TODO: Handle foreground notification
        } else {
            //TODO: Handle background notification

        }
        completionHandler()
    }

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
        NSLog("[RemoteNotification] applicationState: \(applicationStateString) didReceiveRemoteNotification for iOS9: \(userInfo)")

        if UIApplication.shared.applicationState == .active {
            //TODO: Handle foreground notification
        } else {
            //TODO: Handle background notification

        }
    }
}

I am developing an app which has target of iOS9 and firebase push notification feature. My requirement is the app removed from background and the user tap push notification then move to a screen(Ex. AccountVC). In iOS 9 I could able to handle push notification when app is removed from background. But in iOS11 I do not know how to handle when app is removed from background. Any help will be appreciated, thanks in advance


text:
Q: Cylindrical coordinates: Paradox? Let's say the vector field $\vec A_1 = \begin{pmatrix} r\\ 0 \\ z\end{pmatrix}$ in cylindrical coordinates is given and I want to calculate $\vec A_1 \cdot \vec e_r$, where $\vec e_r = \begin{pmatrix} \cos(\phi) \\ \sin(\phi) \\ 0\end{pmatrix}$
1) $ \begin{pmatrix} r \\ 0 \\ z\end{pmatrix} \cdot \begin{pmatrix} \cos(\phi) \\ \sin(\phi) \\ 0\end{pmatrix} = r \cos(\phi)  $
2)  $\vec A_1 = \begin{pmatrix} r\\ 0 \\ z\end{pmatrix} = r \cdot\vec e_r + z \cdot \vec e_z$
thus $\vec A_1 \cdot \vec e_r = r \cdot\vec e_r \cdot \vec e_r + z \cdot \vec e_r \cdot \vec e_z= r$
Which one is right and where is the mistake?


text:
Q: appending values in a global map in clojure I declared a map in clojure using
             (def finalMap {})

I am appending values to it inside a function using assoc but they are not appending, the map is remaining empty. I think it is due to immutability, can I in some way make a global map mutable.The function is a recursive one and I am appending values each time the function is called.
          (defn func [arg1 arg2]
            ;(map append inside let)
            (dorun (for [i (range 0 index)]
              (do
                (func(arg1 arg2))))))

Can you help me with the correct way to do this?

A: If you want a mutable map then you should create an atom:
(def final-map (atom {}))

Also normally you would use assoc to add more key value pairs to it. However you will need to use swap! just to be able to call assoc:
(swap! final-map assoc :a "a value")

This will add a key/value pair where the key is the keyword :a and the value is the String "a value".
It might be good to view some other examples of using assoc. Realise that in the code above assoc is being called with the old value of final-map as its first argument, and returning the new value of final-map.


text:
Q: Wondering how to debug Node.js learnyounode "filter ls" exercise I'm working through the learnyounode exercises. Specifically "filter ls". If you're not familiar with this exercise please refer to this description of it.
Here is the official solution:
var fs = require('fs');
var path = require('path');
fs.readdir(process.argv[2], function (err, list) {
  list.forEach(function (filename) {
    if (path.extname(filename) === '.' + process.argv[3]) {
      console.log(filename);
    }
  });
});

Here is my solution:
var fs = require('fs');
var path = require('path');
var directory = process.argv[2];
var fileExtension = "." + process.argv[3];

function sortFiles (callback){

    fs.readdir(directory, function(err,files){

        if(err) return callback(err);

        callback(null,files);
    });
};

sortFiles(function(err,files){
    var fileExt = "";
    for(var i = 0; i < files; i++){
        debugger;
        fileExt = path.extname(files[i]);

        if(fileExt === fileExtension){
            console.log(files[i]);
        };
    };
});

The problem:
My code outputs nothing. As far as I can tell, there biggest difference between my code and the official solution is the following:
      list.forEach(function (filename) {
        if (path.extname(filename) === '.' + process.argv[3]) {
        console.log(filename);
      }

vs:
    for(var i = 0; i < files; i++){

        fileExt = path.extname(files[i]);

        if(fileExt === fileExtension){
            console.log(files[i]);
        };
    };

2 Questions:
1) How do I debug this code? I tried node debug node.js. From that I can see that when my directory is a folder that contains a cs file and a js file, files is an array, but each index contains "".
2) Why is my approach of a simple for loop not working? Why did they chose .foreach? Is there any reason other than it being more terse?

A: 1) https://github.com/node-inspector/node-inspector
2) Forgot to check the length:
for(var i = 0; i < files.length; i++){
                         --^--

But forEach reads better, and it is more idiomatic.


text:
Q: What's the purpose of the default kubernetes service? When you run: kubectl get svc -n default, you will have a kubernetes service with Type as ClusterIP already there.
What is the purpose of this service? Any references appreciated.
I'm running in Minikube
xyz:Kubernetes _$ kubectl describe svc/kubernetes
Name:              kubernetes
Namespace:         default
Labels:            component=apiserver
               provider=kubernetes
Annotations:       <none>
Selector:          <none>
Type:              ClusterIP
IP:                10.0.0.1
Port:              https  443/TCP
TargetPort:        8443/TCP
Endpoints:         10.0.2.15:8443
Session Affinity:  ClientIP
Events:            <none>

xyz:Kubernetes _$ kubectl cluster-info
Kubernetes master is running at https://192.168.99.100:8443

A: It is so that every Pod within your cluster can make API requests of the Kubernetes master without having to hard-code the API URL therein. Your ~/.kube/config may very well have the "external" address of your Kubernetes master, but it makes very little sense for API traffic to leave the cluster and then re-enter the cluster for a Pod that could be co-located on the same Node. Pods are able to use the Service Account credentials injected by kubernetes, unless that Service Account feature is disabled per-Pod.
Your application is free to make use of that functionality, too, if it wishes -- for example -- to discover any annotations on its Pod, or how many other replicas there are in its Deployment, and so forth.
I guess the tl;dr is that for 90% of the Pods it doesn't matter, and for the remaining 10% it is super convenient.

A: AFAIK the kubernetes service in the default namespace is a service which forwards requests to the Kubernetes master ( Typically kubernetes API server).
So all the requests to the kubernetes.default service from the cluster will be routed to the configured Endpoint IP. In this scenario its the kubernetes master IP
For example
Lets checkout the output of kubectl describe svc kubernetes and look at the the Endpoint IP.

Now lets check our cluster info
kubectl cluster-info

Please note that the kubernetes master is running at the same IP as the Endpoints IP of kubernetes.default service.
Hope it helps.

A: So this kubernetes service in default uses kupe-apiserver pod in the backend & if this goes down we'll not be able to communicate with master, kubectl commnds wont work


text:
Q: Java String Timestamp Conversion to 12 Hour AM/PM With Correct Time I have a string timestamp like the following, 2021-06-22T21:54:18.496Z, I am trying to convert this into a 12 hour am/pm. I've tried the following:
String myTime = "2021-06-22T21:54:18.496Z";
var zonedDateTime = ZonedDateTime.parse(myTime).format(DateTimeFormatter.ofPattern("MMMM dd, yyyy h:mm a"));
System.out.println(zonedDateTime);

The output appears correct June 22, 2021 9:54 PM but the time is incorrect. I'm thinking I need to get and set the correct time zone first before the parse but I'm not sure how to go about doing that.
Any help would be most appreciated.

A: Edit:
I edited the answer to show how to use your JVM's current default time zone, and a specific time zone.
public static void main(String[] args) {
    String myTime = "2021-06-22T21:54:18.496Z";
    parseFormatAndPrintWithSpecificTimeZone(myTime);
    parseFormatAndPrintUsingDefaultTimeZone(myTime);
}

private static void parseFormatAndPrintUsingDefaultTimeZone(String myTime) {
    var zonedDateTime = ZonedDateTime.parse(myTime)
            .format(DateTimeFormatter.ofPattern("MMMM dd, yyyy h:mm:ss.SSS a").withZone(
                    ZoneId.systemDefault() // Get the JVM's current default time zone. Can change at any moment during runtime. If important, confirm with the user.x
                    ));
    System.out.println("Time using my JVM current default time zone:"+ zonedDateTime);

}

private static void parseFormatAndPrintWithSpecificTimeZone(String myTime) {

    var zonedDateTime = ZonedDateTime.parse(myTime)
            .format(DateTimeFormatter.ofPattern("MMMM dd, yyyy h:mm:ss.SSS a").withZone(
                    ZoneId.of("Asia/Singapore") //Specified TimeZone
                    ));
    System.out.println("Time using specific timezone (singapore in this case):"+zonedDateTime);

}

A: tl;dr
Substitute your desired ZoneId, FormatStyle, &  Locale.
Instant
.parse( "2021-06-22T21:54:18.496Z" )
.atZone(
    ZoneId.of( "Europe/Istanbul" )             // Or ZoneId.systemDefault()
)
.format(
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.FULL )
    .withLocale( Locale.FRANCE )               // Or Locale.getDefault()
)

See that code run live at IdeOne.com.
Notice the different date and time-of-day, but still representing same moment, the same point on the timeline.

mercredi 23 juin 2021 à 00:54:18 Heure d'Europe de l'Est

Details
While the Answer by N.M. is correct, I suggest a slightly different approach.
Your input string 2021-06-22T21:54:18.496Z is in standard ISO 8601 format. The T separates the date portion from the time-of-day portion. The Z on the end means an offset-from-UTC of zero hours-minutes-seconds. The Z is pronounced "Zulu", for "Zulu time".
The appropriate type for this specific kind of string of Instant. No need to specify a formatting pattern, as the java.time classes by default use ISO 8601 formats when parsing/generating text.
Instant instant = Instant.parse( "2021-06-22T21:54:18.496Z" ) ;

An Instant represents a moment in UTC, always in UTC, meaning an offset of zero.
Note that your input, and an Instant, use an offset-from-UTC but lack a time zone. A time zone is named history of the past, present, and future changes to the offset used by the people of a particular region. A real time zone name uses a format of Continent/Region.
If you want to adjust from an offset of zero to a particular time zone, specify a ZoneID to produce a ZonedDateTime.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

You may choose to specify a format when generating text to represent the value within our ZonedDateTime object. But I suggest soft-coding, to let java.time automatically localize. Specify a Locale to determine localization issues.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM ).withLocale(locale ) ;
String output = zdt.format( f ) ;


text:
Q: WYSIWYG with possibility of uploading images form client's disc It would be great if I could upload an image from my hard drive using wysiwig HTML editor on my website. Editors like FCKeditor or CKeditor provide this option but images can be upload only to one folder whitch needs to be specify in 'someconfig' file.
I need wysiwig editor where I could dynamicly create string with 'uploadFolderPath' while implementing eg. in php code.
something like:
$editor -> new Editor();
$editor -> uploadFolderPath = "blabla/blabla/";

Thanks for any kind of help.

A: There is an excellent Javascript image/media manager called CKFinder, which works very well with CKEditor, and according to this documentation it looks like its directory can be configured at runtime.
The only drawback is that this software is not free, although you can use the unlicensed version which has a banner.

A: In my project I am using Tinymce editor with tinybrowser plugin for upload/manage imges and  videos. I have modified its configuration file so that I can set current upload folder in session. Also I can have different upload locations for different instances of editor in the same page.


text:
Q: Difference between the different Solution interfaces When writing an VSIX and you want to access information about the given solution you can simply do DTE2.Solution which will return Solution, so far so good. When looking at the MSDN I can see that there exist multiple solution interfaces: Solution, Solution2, Solution3 and Solution4.
I noticed that the VSIX SDK rather often does this, for whatever reason, in order to offer different functionality. In this case I can't really spot any big difference and I am not really sure when I should use which. Should you always go for Solution4 since it implements all the predecessors?

A:
... for whatever reason, in order to offer different functionality

These are COM interfaces so they're subject to COM rules.  Once an interface is published, it is immutable, so adding functionality is done by defining a new interface that inherits from the old.
Numeric suffixes were the convention Microsoft used for versioning COM interfaces.  .NET guidelines for interfaces advise against this but, for consistency, the pattern continues in Visual Studio.
Querying a COM interface involves reference counting.  That means a call to QueryInterface to get a pointer to the desired interface, and ultimately a call to Release to tell the object you no longer need the reference.  The object itself is responsible for its lifetime.  The constructor (called by the object's class factory) starts its reference count at 1, and Release deallocates the memory (deletes itself) when the reference count hits 0.
Note that "reference" in this context is not the same as a .NET reference.  It's a counted copy of a pointer to one of the object's interfaces.
In the early days, it took a bit of work to make sure you handled the reference correctly.  If you can query a newer interface with the combined functionality, that was less work than querying both interfaces separately and ensuring that both were released properly.  Inheriting an interface made things easier by reducing reference management.
Now, we have smart pointers, like CComPtr/_com_ptr_t, that can handle those details for you.  In the managed world, Runtime-Callable Wrappers (RCW) count that among their responsibilities.
In .NET, it's just as easy to create a new interface as it is to inherit an existing one, and just as easy to use the interface in either case.  It's just a matter of a reference cast and sometimes that happens implicitly.
C# 8 adds default implementations but that's a .NET-specific feature.  Remember, Visual Studio is still using COM interfaces at its core.  Default implementations violate the COM rules.

Should you always go for Solution4 since it implements all the predecessors?

That depends on what you're targeting.  As a general rule, use the minimal interface version that has the members you need.  If you need members from Solution and Solution3, use Solution3, but not Solution4.
On the other hand, if you know you're targeting at least a version of Visual Studio that implements Solution4, there's no reason you couldn't use Solution4.  Once you're certain that you're not accidentally preventing your extension from running in the Visual Studio versions you want to target, it falls to your preference.


text:
Q: Encriptar en Angular y desencriptar en PHP con AES Estoy encriptando una cadena del lado de Angular con la librería crypto-js para luego poder desencriptarla en PHP. Tras mucho buscar por foros no encuentro la forma de desencriptar la cadena que genera este codigo typescript utilizando PHP.
Si alguien supiese como hacerlo se lo agradecería mucho.
import * as CryptoJS from 'crypto-js';

encrypt(value : string) : string {
   var key = CryptoJS.enc.Utf8.parse('1234567890123456');
   var iv = CryptoJS.lib.WordArray.random(16);
   var encrypted = CryptoJS.AES.encrypt(value, key, {
      iv: iv
   });

   return iv.concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64);
}


text:
Q: C# Socket.AcceptAsync doesn't make completed event in mac I tried to socket programming with AcceptAsync and SocketAsyncEventArgs.
I wrote my code if Client access to Server, AcceptAsync make completed event and try to receive.
But when I try. Client Socket completly access to Server Socket. But Server's AcceptAsync return 'true' and don't make Completed Event.
By the way, In Debug Mode, AcceptAsync's blocking is true and AcceptAsync return 'false' and Client and Server Socket send and recv each other by manually call OnAccecptCompleted Method.
I tried to this similar Questioin's Solution.
My Server Code is this :
Socket _listenerSocket;
    Action<Socket> _onAcceptHandler;

    public void Init(IPEndPoint endPoint, Action<Socket> onAcceptHandler) {
        Console.WriteLine("Init");
        _listenerSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        _onAcceptHandler += onAcceptHandler;

        _listenerSocket.Bind(endPoint);

        _listenerSocket.Listen(10);

        SocketAsyncEventArgs args = new SocketAsyncEventArgs();
        args.SetBuffer(null, 0, 0);
        args.Completed += new EventHandler<SocketAsyncEventArgs>(OnAccecptCompleted);
        RegisterAccept(args);
    }

    void RegisterAccept(SocketAsyncEventArgs args) {
        Console.WriteLine("RegisterAccept");
        args.AcceptSocket = null;
        try {
            bool pending = _listenerSocket.AcceptAsync(args);
            Console.WriteLine($"pending {pending}");
            if (pending == false) {
                Console.WriteLine("RegisterAccept_pending==false");
                OnAccecptCompleted(null, args);
            }
        }
        catch(Exception e) {
            Console.WriteLine(e.ToString);
        }

    }

    void OnAccecptCompleted(object sender, SocketAsyncEventArgs args) {
        Console.WriteLine("OnAcceptCompleted");
        if(args.SocketError == SocketError.Success) {
            _onAcceptHandler.Invoke(args.AcceptSocket);
        }
        else {
            Console.WriteLine(args.SocketError.ToString());
        }

        RegisterAccept(args);
    }

My endPoint arg's Code is this :
        string host = Dns.GetHostName();
        IPHostEntry ipHost = Dns.GetHostEntry(host);
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);

My OnAcceptHandler Method code is this :
static void OnAcceptHandler(Socket clientSocket) {
        try {
            // Recv
            byte[] recvBuff = new byte[1024];
            int recvByte = clientSocket.Receive(recvBuff);
            string recvData = Encoding.UTF8.GetString(recvBuff, 0, recvByte);
            Console.WriteLine($"[From Client] : {recvData}");

            // Send
            byte[] sendBuff = Encoding.UTF8.GetBytes("Welcome  to Server!");
            clientSocket.Send(sendBuff);

            // DisConnect
            //clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
        }
        catch(Exception e) {
            Console.WriteLine(e.ToString());
        }

    }

When AcceptAsync don't make 'Completed Event', My socket status is like this.

*

*Add 01 :
I fix this problem but It just temporary solution.
After Init() I tried to Thread.Sleep(), Send / Recv Problem is fixed.
I don't know why but it works.
If someone know why this happen or guess why, please comment under this question.
Thanks.

*Add 02 :
If Thread.Sleep()'s time is low, Socket communicate is stop on Client's Socket.Recv part and Server's AcceptAsync doesn't make Completed Event.
Fixed Server's Main() :
static void Main(string[] args) {
        // DNS
        string host = Dns.GetHostName();
        IPHostEntry ipHost = Dns.GetHostEntry(host);
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);

        //Console.WriteLine($"host : {host}, ipHost : {ipHost}, ipAddr : {ipAddr}, endPoint : {endPoint.Address}");

        // set Listener Socket
        _listener.Init(endPoint, OnAcceptHandler);
        Console.WriteLine("Listening...");
        Thread.Sleep(2000);
        //Console.WriteLine(_listener.args.SocketError );
        while (true) {
            ;
        }
    }

*

*Add 03 :
if Thread.Sleep Work in While(), It Client and Sernver's communicatioin is never stop.(sometimes delay but never stop)

This is Fixed code :
static void Main(string[] args) {

        // DNS
        string host = Dns.GetHostName();
        IPHostEntry ipHost = Dns.GetHostEntry(host);
        IPAddress ipAddr = ipHost.AddressList[0];
        IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);

        //Console.WriteLine($"host : {host}, ipHost : {ipHost}, ipAddr : {ipAddr}, endPoint : {endPoint.Address}");

        // set Listener Socket
        _listener.Init(endPoint, OnAcceptHandler);
        Console.WriteLine("Listening...");

        //Console.WriteLine(_listener.args.SocketError );
        while (true) {
            Thread.Sleep(1);
        }
    }

I guess this is Mac's work assign Policy issue. Am I right?


text:
Q: Compile error when explicitly calling the base class destructor on a derived pointer Just like the title says. The following contrived example seems to work on codepad: http://codepad.org/4cgGmvDQ and under GCC 4.1.2 on my Linux box.
#include<stdlib.h>
#include<new>

class IBase
{
public:
    virtual ~IBase(){}
};

class B : public IBase
{
public:
    virtual ~B(){}
};

class D : public B
{
public:
    virtual ~D(){ }
};

int main()
{
    void* p = malloc(sizeof(D));

    D* d = new(p) D();

    B* b = static_cast<B*>(d);

    b->~IBase();

    free(p);
}

But Visual Studio Pro 2012 11.0.61030.00 Update 4 fails with:
main.cpp(30): error C2300: 'B' : class does not have a destructor called '~IBase'
Obviously the example could easily be reworked to avoid the issue, but my actual code base doesn't give me any other options. Is anyone familiar with this particular failing of the Microsoft compiler?

A: This is not a bug in MSVC. From the standard, §3.4.5 [basic.lookup.classref]/p2-3 (quoting N3936, emphasis mine):

If the id-expression in a class member access (5.2.5) is an
  unqualified-id, [...]
If the unqualified-id is ~type-name, the type-name is looked up
  in the context of the entire postfix-expression. If the type T of
  the object expression is of a class type C, the type-name is also
  looked up in the scope of class C. At least one of the lookups
  shall find a name that refers to (possibly cv-qualified) T.

In your code, T is B, and lookup for IBase obviously can't find a name that refers to B. Therefore, your code is ill-formed. If g++ accepts it, it's either a bug or an extension.
Since it sounds like the actual type B represents is "unspeakable" in your real code, but IBase is OK to write, the simplest solution would be simply to cast b to IBase *.

A: This is a known bug. As to "why" it fails, I have no answer. The workaround for your example may be:
b->IBase::~IBase();

A: Base Class Destructors are invoked automatically. If you call the base class destructor manually then when the object gets destroyed it will be invoked a second time.


text:
Q: Amazon EC2 504 Gateway Time-out I have only a single amazon EC2 free-tier instance. It's hosting two Django sites that currently get almost no traffic, barely a handful of requests per day. The server is apache with mod_wsgi, and apache is configured with WSGIDaemonProcess, like
WSGIDaemonProcess mysite.com processes=4 threads=4 display-name=%{GROUP} user=djangoUser group=djangoUser python-path=/srv/mysite:/srv/mysite/venv/lib/python2.7/site-packages
WSGIProcessGroup mysite.com

for each of the two sites. The sites were previously hosted on linode with the same configs and setup without issue, so I'm kind of surprised to be having issues.
Very frequently (more than 50% of the time) when accessing the sites, I get a 504 Gateway Time-out and the access attempt does not even register in the apache error or access logs at all, so it's hard to debug.
I've seen similar threads here discussing elastic load balancing, but that is not my case. I'm not sure how to proceed to route out and resolve the issue.
Here is an arbritrary screenshot of top at a given time when a request is made:

EDIT
I eventually figured out this was a misconfigured fail2ban script that added my ip to an iptables blacklist for a finite time. My first request would work, but subsequent requests would be blocked by iptables until the time limit expired, leading the 504s.

A: EC2 t2.micro instances are horrible. There, I said it. Horrible. If you're running a non-interactive application, and you don't mind if a certain job takes 10 times longer to run than it should, then t2.micros can work OK. For any type of interactive web application, though, they're worthless.
My guess is that if you'd watch top during the periods where this is happening, you will see a high percentage of CPU steal and/or iowait. Sadly, the only thing you can do to remedy this is to upgrade to a larger instance.
If you do not need the more advanced features available to you in AWS, it's not a great solution as far as performance-per-dollar goes. Linode, DO, and other VPS providers handily out-perform EC2 instances of similar size.


text:
Q: Recommended patterns to consume an asynchronous microservice from a client? so our use case is to have a microservice which is very expensive (takes time to run). this service is consumed by any client.
i've read about some patterns for best practices for consuming, for example:

*

*use WebSockets - which will make the server able to send the result back to the client.

*Constant polling (i don't like it much)

*Leases - it's some kind of polling - the client will acquire a lease for X minutes, and will renew it every few minutes until a response comes - but if the response comes back, the client will still have to wait for it (although the result is ready already) - this will make cleanup easier (clients which abandoned the requests)

i'd love to hear about your best practices in this event-driven microservices architecture
thanks!

A: Sounds like you need a pubsub framework/product, e.g. ActiveMQ, RabbitMQ, ZeroMQ (NetMQ) or maybe even Redis pubsub/queues


text:
Q: Variable in SQL query syntax I want to make a simple SQL query like:
SELECT * FROM table WHERE $variable_2 = $variable_1

instead of a default one:
SELECT * FROM table WHERE column_name = $variable_1

It seems like first example doesn't work at all. Is it even possible to modify SQL query syntax in such way?

A: as this reference answer for:
in link:
Use Variable as SQL column Name in query
answer1:
declare @ColumnName varchar(50)

declare @sql nvarchar(max)

set @ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))

set @sql = 'select ' + @ColumnName + ' from SalesTable'

print @sql

EXEC sp_sqlexec @sql

answer 2:
declare @ColumnName varchar(50)

declare @sql nvarchar(max)

set @ColumnName = 'SalesData_' + convert(varchar(2),datepart(dd,getdate()))

set @sql = 'select ' + @ColumnName + ' from yourschema.SalesTable'

print @sql


text:
Q: How add dependencies into groovy script? I try to add HttpBuilder into groovy script, but can do it only manually (Alt+Ctrl+Shift+S add dependencie). But when I start script I have error in line of creating new httpbuilder instance java.lang.ClassNotFoundException: org.apache.http.client.HttpClient. I manualy add HttpClient, butClassNotFoundException: net.sf.json.JSONObject and so on. But when I add Ini library it works fine.
I also tried to use @Grab
main()
def main() {
    @Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7' )
    def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org')

And have compilation error
Error:Groovyc: While compiling GroovyTests: java.lang.RuntimeException: Error grabbing Grapes -- [download failed: net.sf.json-lib#json-lib;2.3!json-lib.jar]
And net in def http = new groovyx.net.http.HTTPBuilder('http://www.codehaus.org') is red and Cannot resolve a symbol 'net' error
will be glad to any help

A: Since you have now installed the groovy executables as per the comments, the following code:
@Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://jsonplaceholder.typicode.com')
def res  = http.get(path: '/users')

println "Number of users: ${res.size()}"

should now run and print:
─➤ groovy solution.groovy
Number of users: 10

─➤

(tested on Groovy Version: 2.5.8 JVM: 1.8.0_232 Vendor: AdoptOpenJDK OS: Linux)
One thing that might be disrupting the artifact resolution is if you have a custom grapeConfig.xml file. This file (if it exists) should be under <user home dir>/.groovy/grapeConfig.xml and the default text that groovy uses if no grapeConfig.xml file is present can be found here:
https://github.com/apache/groovy/blob/master/src/resources/groovy/grape/defaultGrapeConfig.xml
In addition, if you need to debug grapes downloads, you should try the following flags (again as mentioned in the comments):
─➤ groovy -Dgroovy.grape.report.downloads=true -Divy.message.logger.level=4 yourGroovyScript.groovy

which should print information on what grapes are actually doing when the resolution fails.
What does your groovy -v look like? i.e. what version of groovy and what jdk are you on?


text: Q: java.lang.ClassNotFoundException: org.apache.commons.collections.SequencedHashMap I am unable to resolve this error. I tried all the .jar files related to this. I guess I am having some problems in my Hibernate.hbm.xml. Inputs will be appreciated.


text:
Q: How can I keep the trailing slash after choosing a directory from the zsh completion options? In zsh, when I press tab 2 times to enter the "completion menu", select a directory and press enter, it first adds the chosen directory with a trailing slash to the command, but as soon as I press space to add more arguments, it removes it.
i.e. "rsync foo/" gets changed to "rsync foo " after pressing space.
Is there a way to disable this behaviour?
It forces me to always add slashes manually for commands like rsync in particular.

A: To retain the / added after completing directories or symbolic links to directories, turn off the option auto_remove_slash which is on by default.
setopt no_auto_remove_slash

For many commands, retaining the trailing slash makes no difference for directories, but causes the command to act on the target directory instead of the symbolic link if the argument is a symbolic link to a directory. For an rsync source argument, a trailing slash causes the directory to be merged into the destination rather than copied to a subdirectory.


text:
Q: LaTeX3 expand token list in sequence I've just started learning expl3 programming and trying to create a parser for drawing a type of TikZ/PGF plot. Basically I want
\begin{pck}
    plot node1 .3 .3;
    plot node2 .7 .7;
\end{pck}

to expand into
\begin{tikzpicture}
    \begin{axis}[xmin=0, xmax=1,
                 ymin=0, ymax=1]
        \node (node1) at (axis cs:.3, .3) [circle, draw] {};
        \node (node1) at (axis cs:.7, .7) [circle, draw] {};
    \end{axis}
\end{tikzpicture}

The text has in the environment has to be completely parsed first, before expanding it to the TikZ code as I want to do some processing of some of the arguments.
I have the following code so far.
\documentclass{article}

\usepackage[check-declarations]{expl3}
\usepackage{environ}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\ExplSyntaxOn

\tl_new:N \pck_objects_tl

\seq_new:N \pck_labels
\seq_new:N \pck_xs
\seq_new:N \pck_ys
\seq_new:N \pck_edgs_left
\seq_new:N \pck_edgs_right

\tl_new:N \pck_label
\tl_new:N \pck_x
\tl_new:N \pck_y
\tl_new:N \pck_edg_left
\tl_new:N \pck_edg_right

\cs_new:Npn \pck_draw {
    \bool_do_until:nn {\seq_if_empty_p:N \pck_labels} {
        \seq_pop_left:NN \pck_labels \pck_label
        \seq_pop_left:NN \pck_xs \pck_x
        \seq_pop_left:NN \pck_ys \pck_y

        \node~(\pck_label)~at~(axis~cs\c_colon_str~\pck_x,~\pck_y)~[circle, draw]~\bgroup \egroup ; \par
    }
}

\NewEnviron{pck}[1][] {
    \pck_parse:V \BODY

    \begin{tikzpicture}
        \begin{axis}[xmin=0, xmax=1,
                     ymin=0, ymax=1]
            \pck_draw
        \end{axis}
    \end{tikzpicture}\par
}

\cs_new_protected:Npn \pck_parse:n #1{
    \tl_set:Nn \pck_objects_tl{#1}
    \tl_remove_all:Nn \pck_objects_tl{\par}
    \tl_replace_all:Nnn \pck_objects_tl{plot~}{\pck_parse_plot:w}
    \tl_use:N \pck_objects_tl
}

\cs_generate_variant:Nn \pck_parse:n {V}

\cs_new_protected:Npn \pck_parse_plot:w #1 ~ #2 ~ #3 ; {
    \seq_put_right:Nn \pck_labels {#1}
    \seq_put_right:Nn \pck_xs {#2}
    \seq_put_right:Nn \pck_ys {#3}
}

\ExplSyntaxOff

\begin{document}
    \begin{pck}
        plot node1 .3 .3;
        plot node2 .7 .7;
    \end{pck}
\end{document}

However, this code draws all of the nodes on top of each other. I believe it is because when the sequences, eg. \pck_labels, are popped to the token list \pck_label, the token list is not expanded into node1 or node2 immediately, but the expansions happen last so the all expand to node2 etc. I really can not figure out how to expand the tokens the correct way, I have tried with with generating variants with the f and x spesifications and using \exp_after and \use. Any suggestions?
Also, since I am completely new to expl3, I am very happy to receive any feedback on the code in general!

A: This code will solve your problems. I do not use more than one sequence. By doing some x-type expansion it will plot your points. Please note that you should add suffixes containing the data type in l3 names.

\documentclass{article}

\usepackage[check-declarations]{expl3}
\usepackage{environ}
\usepackage{pgfplots}
\pgfplotsset{compat=1.15}

\ExplSyntaxOn

\tl_new:N \pck_objects_tl
\seq_new:N \pck_plot_seq

\cs_new:Npn \pck_node:nnn #1#2#3 {
    \node~(#1)~at~(axis~cs\c_colon_str#2,#3)~[circle, draw] { };
}
\cs_generate_variant:Nn \pck_node:nnn {xxx}

\cs_new:Npn \pck_draw {
    \seq_map_inline:Nn \pck_plot_seq
        {
            \clist_set:Nn \l_tmpa_clist { ##1 }
            \pck_node:xxx { \clist_item:Nn \l_tmpa_clist { 1 } }
                { \clist_item:Nn \l_tmpa_clist { 2 } }
                { \clist_item:Nn \l_tmpa_clist { 3 } }
        }
}

\NewEnviron{pck}[1][] {
    \pck_parse:V \BODY
    \begin{tikzpicture}
        \begin{axis}[xmin=0, xmax=1,
                     ymin=0, ymax=1]
            \pck_draw
        \end{axis}
    \end{tikzpicture}\par
}

\cs_new_protected:Npn \pck_parse:n #1{
    \tl_set:Nn \pck_objects_tl{#1}
    \tl_remove_all:Nn \pck_objects_tl{\par}
    \tl_replace_all:Nnn \pck_objects_tl{plot~}{\pck_parse_plot:w}
    \tl_use:N \pck_objects_tl
}

\cs_generate_variant:Nn \pck_parse:n { V }

\cs_new_protected:Npn \pck_parse_plot:w #1 ~ #2 ~ #3 ; {
    \seq_put_right:Nn \pck_plot_seq {#1,#2,#3}
}

\ExplSyntaxOff

\begin{document}
    \begin{pck}
        plot node1 .3 .3;
        plot node2 .7 .7;
        plot node3 .5 .5;
    \end{pck}
\end{document}


text:
Q: Disable Console Logging from MongoDB in Eclipse I'm using a Mongo Database to store information from my Java program.
I'm using Eclipse and MongoDB 3.0
The problem I am having is that whenever my program has any interaction with Mongo it fills the console with red text from JULLogger.
I do not currently have any code to set the logger level, as all examples I have found on here or elsewhere online have given the error:
    Logger mongoLogger = Logger.getLogger( "org.mongodb.driver" );
    mongoLogger.setLevel(Level.SEVERE);

   "The method getLogger(String) is undefined for the type Logger"

Here is the output:
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Cluster created with settings {hosts=[127.0.0.1:27017],
    mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description
    ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=127.0.0.1:27017,
    type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Opened connection [connectionId{localValue:1, serverValue:117}] to 127.0.0.1:27017
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Monitor thread successfully connected to server with description
    ServerDescription{address=127.0.0.1:27017, type=STANDALONE,
    state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 0, 7]},
    minWireVersion=0, maxWireVersion=3, electionId=null,
    maxDocumentSize=16777216, roundTripTimeNanos=587005}
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Opened connection [connectionId{localValue:2, serverValue:118}] to 127.0.0.1:27017
    Document{{_id=567045259311932a6406b4e2, time=16:51:48, data=[31C, 38C, 20C]}}
    Dec 16, 2015 8:49:58 AM com.mongodb.diagnostics.logging.JULLogger log
    INFO: Closed connection [connectionId{localValue:2, serverValue:118}] to
    127.0.0.1:27017 because the pool has been closed.

Could anyone advise me on how to remove all the Mongo logs from my console?

A: Thank you very much Ross for your suggestion:
java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(java.util.logging.Level.SEVERE);
In fact the correct code was this, so only a minor change:
java.util.logging.Logger.getLogger("org.mongodb.driver").setLevel(Level.SEVERE);
I can confirm that I am not longer receiving any logs from mongo within the console at runtime.

A: You can try this solution Just add following dependency in your pom file or add this jar manually
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <version>1.7.22</version>
</dependency>

Read these

*

*http://grokbase.com/t/gg/mongodb-user/153eg0pczd/deactivate-logging-in-the-java-driver

*https://www.slf4j.org/manual.html#swapping
for more and detailed explanation
I faced this similar kind of issue and it worked for me.

A: I tried all the above but none worked.the One which finally worked is
The one which finally worked for me is as below.
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
loggerContext.getLogger("org.mongodb.driver").setLevel(Level.ERROR);

Please note the imports as well:
    import ch.qos.logback.classic.Level;
    import ch.qos.logback.classic.LoggerContext;
    import org.slf4j.LoggerFactory;


text:
Q: How to enlarge a leaflet polygon box by 5%? I create a square polygon by using the min and max values of the latitude and longitude of the furtherst points of my incoming data.
$poly = " $maxLng $maxLat , $minLng $maxLat , $minLng $minLat , $maxLng $minLat , $maxLng $maxLat ";

But this means that at least two markers are always the borders of this box. How can I push out the points and enlarge the overall size of the box by say 5% in all directions but I still need the lat/lon of each of those corners?

A: A small example of how to use the turfjs library and the transformScale method

const map = L.map('mapid').setView([52.308478623663355, 19.281005859375004], 6);

L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 18,
  attribution: '© OpenStreetMap contributors'
}).addTo(map);

const test = [
  [54.80068486732236, 18.292236328125004],
  [53.89786522246521, 14.611816406250002],
  [51.055207338584964, 15.281982421875002],
  [49.57510247172322, 19.138183593750004],
  [50.57626025689928, 23.642578125000004],
  [52.214338608258224, 23.148193359375004],
  [52.86912972768522, 23.741455078125],
  [54.29729354239267, 22.928466796875004],
  [54.29729354239267, 19.489746093750004],
  [54.80068486732236, 18.292236328125004]
];

L.polygon(test, {
  color: 'red'
}).addTo(map);

var poly = turf.polygon([test]);
var scaledPoly = turf.transformScale(poly, 1.05);

const {
  coordinates
} = scaledPoly.geometry;

L.polygon(coordinates, {
  color: 'white'
}).addTo(map);
* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
}

body {
  min-height: 100%;
}

#mapid {
  width: 100%;
  height: 100%;
}
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />


text:
Q: XMLREADER Using PHP Get Named ATTRIBUTE Value I am using XMLREADER with PHP to parse an XML file. I need to change the code to get the value of an attribute.
The XML:
<color eye="Green eyes" ethnicity="" hair="Brown Hair"/>

This is one method I've tried:
elseif($xml->nodeType == XMLReader::ELEMENT && $xml->name == 'color') {
    $xml->read();
        if($xml->nodeType == XMLReader::ATTRIBUTE && $xml->name == 'eye') {
           $value4[] = $xml->value;
           $r4 = array_values($value4);
        }
}

I have also tried:
elseif($xml->nodeType == XMLReader::ELEMENT && $xml->name == 'color') {
        $value4[] = $xml->getAttribute('eye');
        $r4 = array_values($value4);
    }

Using the code directly above I was able to get the 'eye' attribute value, but when I changed what's in () to 'hair' I didn't get anything.
Of the 2 methods I've tried, which is the right one, if either, and what does it look like I am doing wrong? Thank you in advance.


text:
Q: Autotab contenteditable divs or adding function to input type: text I have 3 contenteditable divs.  The first and third divs have a function that simulates changing the character associated with a key event, typing out a pre-programmed string as the user types, and the second div is straightforward- what the user types appears in the div.  This can be seen here: http://jsfiddle.net/vRXph/4/.  I've included the code for the first div here for convenience:
var list1 = "Sing in me, Muse, and through me tell the story".replace(/\s/g,
 "\xA0").split("")
function transformTypedCharacter1(charStr) {
    var position = $("#verse1").text().length;
    if (position >= list1.length) return '';
    else return list1[position];
}

function insertTextAtCursor1(text) {
    var sel, range, textNode;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0).cloneRange();
            range.deleteContents();
            textNode = document.createTextNode(text);
            range.insertNode(textNode);

            // Move caret to the end of the newly inserted text node
            range.setStart(textNode, textNode.length);
            range.setEnd(textNode, textNode.length);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        range.pasteHTML(text);
    }
}

$("#verse1").keypress(function(evt) {
    if (evt.which) {
        var charStr = String.fromCharCode(evt.which);
        var transformedChar = transformTypedCharacter1(charStr);
        if (transformedChar != charStr) {
            insertTextAtCursor1(transformedChar);
            evt.preventDefault();
            return false;
        }
    }
});

I want to autotab between these divs.  In the first div, the autotab function would be called after the final pre-programmed character is typed, and for the second div the autotab would be called after a certain number of characters (lets say 5 characters, just to keep it short as a test).
My first question (of 3): How do I autotab between contenteditable divs?
I have found a way to autotab between input type: text fields here: http://jsfiddle.net/Ukkmu/73/ but I cannot seem to apply this to my divs.  I attempted, and failed, to do this here: http://jsfiddle.net/Ukkmu/76/.
    function auTab (currentDiv, currentDivSize, currentDivLength, nextDiv) {
    if(currentDivSize == currentDivLength){
        $('#' + currentDiv).next().focus();
    };
};

$('div[id^="verse"]').keyup(function() {
    var thisDiv = $(this).attr('id');
    var thisDivSize = $(this).attr('size');
    var thisDivLength = $(this).val().length;

    auTab(thisDiv, thisDivSize, thisDivLength);
});

As you can see, the system just ignores the autotab function.  I created a size of "5" on my first div as a test.  I don't know if this is possible, but I did it because I saw that the autotab function is dependent on size.  My second question (of 3) is: Can I assign a size or maxlength attribute to a contenteditable div?  If I can, and if the autotabbing relies on this attribute, then I would simply assign the size of the first div to be the number of characters in my pre-programmed string (and for the second div I would assign 5 characters as test, as I mentioned above).
An alternative would be to change my contenteditable divs to input type: text fields.  I did this here: http://jsfiddle.net/Ukkmu/74/, but as you can see my original function that I described in the first paragraph of this question no longer works.  I end up with a repeated character (the "S" from my pre-programmed string) before the first field, instead of my pre-programmed string in the first field.  For this test I put the size of the field as 3, just as a test.  The final version would be the size of the entire pre-programmed string.  My 3rd question (of 3), if applicable: How can I apply the function that simulates changing the character associated with a key even to input type= text fields?
My application of this code is that this is an art project.  As the user types, the output on the screen alternates between a classic text (in this case, Homer's The Odyssey), and what the user is actually typing.
Sorry if this is a very long post, but I wanted to include as much information as possible.

A: My solution, thanks to pckill, answers question 3.  I used input type: text fields with the following function:
var list1 = "This is a test.".replace(/\s/g, "\xA0").split("")
function transformTypedChar1(charStr) {
    var position = $("#verse1").val().length;
    if (position >= list1.length) return '';
    else return list1[position];
}


text:
Q: Use Django Model class inheritance to create an audit log for a table I want to use http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance to subclass an existing model for the purpose of creating a complete history of every change ever made to any record in the original table.

class Foo:
  data = models.TextField()
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

  def save():
    super(...)
    audit = FooAuditLog.createFromFoo(self)

class FooAuditLog(Foo):
  history_for = models.ForeignKey(Foo)

  def createFromFoo(foo):
    ... #Create the auditlog entry from the original record.

So every time I create or update a record of type "Foo", I want to take a snapshot of the Foo record and add another entry into FooAuditLog.  My goal is to have a complete revision history for every Foo record so that I can track each and every change made to each record over time.
What are the pitfalls of this approach?  If there are ForeignKey relationships to and out of Foo, do I have to worry about cascade deletes/updates between Foo and FooAuditLog?

A: Why not use something made such as the Audit Trail app? I can't really see how inheritance really fits into the abstraction needed for logging. Audit Trail uses a simple declaration in the class which packages all of the activities.

A: Two possible pre-coded solutions are https://github.com/etianen/django-reversion and http://code.djangoproject.com/wiki/AuditTrail . More options are at https://www.djangopackages.com/grids/g/model-audit/
As you note, foreign key references are tricky, especially for Many-To-Many models.  You have to decide if the old models are a constraint on new tables, else break those relationships which complicates "undo" considerably.


text:
Q: SignalR client function not being called Overview
I am having real problems getting my SignalR server/hub to call a javascript function on my SignalR client.
What I have tried

*

*I have read more tutorials and viewed so many examples (including the official docs) of how this should work that it is almost ridiculous.

*I have tried commenting out all but the core functionality.

*I have ensure that the server and client functions are not the same and spelt correctly.

*I have turned logging on also but no errors have appeared in the Firebug console.

Enviornment
The SignalR code in question has been implemented in an ASP.net MVC4 project using VB.net with MySQL and Entity framework v5. I am debugging the system on my local development machine in Visual Studio 2012 with IISExpress.
Code snippets
global.asax.vb:
Sub Application_Start()

    MiniProfilerEF.Initialize()

    AreaRegistration.RegisterAllAreas()

    ' Register the default hubs route: ~/signalr
    RouteTable.Routes.MapHubs()

    WebApiConfig.Register(GlobalConfiguration.Configuration)
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)
    RouteConfig.RegisterRoutes(RouteTable.Routes)
    BundleConfig.RegisterBundles(BundleTable.Bundles)
    AuthConfig.RegisterAuth()

    ' Register custom view
    ViewEngines.Engines.Add(New CustomViewEngine())

End Sub

SignalR initialisation javascript:
$(function () {

    // Proxy created on the fly
    var notification = $.connection.notificationHub;
    //$.connection.notificationHub.logging = true;

    // Declare functions that can be run on the client by the server
    notification.client.sendNotification = onAddNotification;

    // Testing code only
    $("#testButton").click(function () {
        // Run test function on server
        notification.server.runTest();
    });

    // Map the onConnect and onDisconnect functions
    notification.client.connected = function () { };
    notification.client.disconnected = function () { };

    //$.connection.hub.start();
    $.connection.hub.start(function () {
        alert("Notification system connected");
    });
});

// Process a newly received notification from the server
function onAddNotification(message) {

    // Convert the passed json message back into an object
    var obj = JSON.parse(message);

    var parsedDate = new Date(parseInt(obj.Timestamp.substr(6)));

    // Update the notification list
    $('#notifications').prepend('
' + obj.Message + ' at ' + dateFormat(parsedDate, "default") + '
');

    // Update the new notification count
    var count = document.getElementById("notification_count")
    if (count.textContent) {
        //W3C DOM
        count.textContent = obj.Count;
    } else if (anchor.innerText) {
        //Microsoft DOM
        count.innerText = obj.Count;
    }
    //document.getElementById("notification_count").innerHTML = obj.Count + '';

    // Show a brief notification message
    $.sticky(obj.Message, { autoclose: 2000, position: "top-right", type: "st-info" });

};

Hub class:
Public Class NotificationHub
Inherits Hub

ReadOnly Group As String = "Notification"

Public Function RunTest()
    Dim testMessage As New SignalR_Notification_Message

    testMessage.Count = 3
    testMessage.Message = "Some test message"
    testMessage.Timestamp = Now

    Call Notify(testMessage, "joebloggs")
End Function

Public Overrides Function OnConnected() As Task

    Dim db As New MyEntities
    Dim userName As String = Context.User.Identity.Name
    Dim connectionID = Context.ConnectionId

    Dim conn As SignalR_Connection

    ' Attempt to find a retrieve a connection entry with the same Connection ID
    conn = db.SignalR_Connection.Where(Function(s) s.Connection_ID = connectionID).FirstOrDefault

    ' If the connection does not already exist, add it
    If IsNothing(conn) Then
        conn = New SignalR_Connection

        ' Create the new connection entry
        conn.Connection_ID = connectionID
        conn.Username = userName
        conn.Group = Group

        ' Attempt to save the new connection entry
        Try
            db.SignalR_Connection.Add(conn)
            db.SaveChanges()
        Catch ex As Exception
            Dim a As String = ""
            a = ""
        End Try
    End If

    Return MyBase.OnConnected()
End Function

Public Overrides Function OnDisconnected() As Task

    Dim db As New MyEntities
    Dim userName As String = Context.User.Identity.Name
    Dim connectionId As String = Context.ConnectionId

    Dim conn As SignalR_Connection

    ' Attempt to find a retrieve the connection entry
    conn = db.SignalR_Connection.Where(Function(s) s.Connection_ID = connectionId And s.Username = userName).FirstOrDefault

    ' Attempt to remove the connection entry
    Try
        db.SignalR_Connection.Remove(conn)
        db.SaveChanges()
    Catch ex As Exception
        Dim a As String = ""
        a = ""
    End Try

    Return MyBase.OnDisconnected()
End Function

'''
''' Send the notification to the client
'''
Public Sub Notify(Message As SignalR_Notification_Message, Username As String)

    Dim ConnectionIDs As List(Of String)
    Dim Serializer As New JavaScriptSerializer()
    Dim json As String

    ' Attempt to convert the object into json before sending
    Try
        json = Serializer.Serialize(Message)
    Catch ex As Exception
        Exit Sub
    End Try

    ' Get the connection id's this message must go to
    ConnectionIDs = GetUsersConnectionID(Username)

    If Not IsNothing(ConnectionIDs) Then
        ' Send the message to all connection ID's
        For Each ConnectionID In ConnectionIDs
            Clients.Client(ConnectionID).sendNotification(json)
        Next
    End If

End Sub

'''
''' Retrieve a list of connection ID's for the current user
'''
Public Function GetUsersConnectionID(Username As String) As List(Of String)

    Dim db As New MyEntities

    ' Attempt to find a retrieve the connection entries
    Return db.SignalR_Connection.AsNoTracking.Where(Function(s) s.Username = Username).Select(Function(s) s.Connection_ID).ToList

End Function

End Class

HTML (Partial View):
@ModelType Geo_sight.NotificationWindowModel

    <button class="close" data-dismiss="modal">×</button>

Notifications

        @For Each Notification In Model.Notifications
            @
@Html.Raw(Notification.Text)

        Next

    Send test

The problem
With a breakpoint set on the first line of the onAddNotification function:

var obj = JSON.parse(message);

Whenever the Notify function in the Hub is called the client function is practically never called!
Other useful bits

*

*The connection is definitely successful as I can see the connections long-polling in Firebug.

*My user connections are being successfully saved and retrieved from my database in the onConnected and GetUsersConnectionID functions.

*Of the dozens and dozens of times I have tried to run the client function from the server (using the testButton to fire off the notification call on the hub), it has run no more than 3-4 times, neither times of which I have been able to repeat.

*On the very rare and random occasion that the function has run, it has done what it is supposed to do and I have been able to halt execution of the function with a breakpoint in the client.

*I have checked my ~/signalr/hubs script and there is nothing listed under the client function definitions, but is for the server (see below). Is this correct? I'd imagine the client functions should be here?
proxies.notificationHub = this.createHubProxy('notificationHub');
proxies.notificationHub.client = { };
proxies.notificationHub.server = {
    getUsersConnectionID: function (Username) {
        return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["GetUsersConnectionID"], $.makeArray(arguments)));
     },

    notify: function (Message, Username) {
        return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["Notify"], $.makeArray(arguments)));
     },

    runTest: function () {
        return proxies.notificationHub.invoke.apply(proxies.notificationHub, $.merge(["RunTest"], $.makeArray(arguments)));
     }
};

return proxies;

Update 2013-04-04
With a little more debugging, I can make the client run but completely randomly and very occassionally simply by pressing my test button again and again a few seconds after the previous signalR send call finishes.
Here is an example of this from the Firebug console...

Update 2013-04-05
With more and more testing and debugging, I have come across a trait in when the client function does and doesn't call...
As can be seen in my previous update, SignalR has chosen to use Long-polling with a time-out of about 35 seconds.
Having made a number of further repeated calls to the client function, it seems that only the calls made within approximately the first 10 seconds of a long-polls life reach the client and run the function successfully. The calls sent after this period don't seem to come through.
I guess this means my code is sound but why is this happening??
SignalR FAQ question...
I also found something similair to my issue here: SignalR Wiki FAQ's
I am using Windows 7 Professional but i'm not using IIS (im using IIS Express), so could this be the same issue?


text:
Q: Debug.Assert() only triggers when stepping over it I'm using Visual Studio 2010 to write a .NET assertion:
Debug.Assert(false, "Testing Debug.Assert");

When I put a breakpoint on this line of code, wait until the breakpoint hits, and then let the program continue to run, everything works fine: an "Assertion Failed" dialog pops up. However, when I remove the breakpoint and rerun the application, the Debug.Assert() statement is simply ignored.
Does anyone have an idea what might cause this very strange behavior?

A: A colleague of mine immediately knew what the problem was. I had to enable the "Enable Just My Code" flag at "Visual Studio 2010 / Menu / Options / Debugging / General". Apparently this is a bug in Visual Studio 2010".

A: I was experiencing the same problem. Using Trace.Assert works as expected.

Well, Trace.Assert started exhibiting the same behavior on the next debugging session.

Ah, found the problem.

*

*With 'Enable Just My Code" checked.

*

*If 'Thrown' is checked for 'Common Language Runtime Exceptions' in
the 'Exceptions' dialog (Ctrl+Alt+E), the Assert will be thrown.

*If unchecked, the Assert will be thrown.

*With 'Enable Just My Code" unchecked.

*

*If 'Thrown' checked, the Assert will not be thrown.

*If 'Thrown' unchecked, the Assert will be thrown.
Therefore, the Assert will not be thrown when 'Enable Just My Code' is unchecked and 'Thrown' is checked for 'Common Language Runtime Exceptions'.

A: The answers given here did not help but I found out that it was as simple as checking the "Define DEBUG constant" option for the Debug configuration in the project's build settings:


text:
Q: Copy formula result to last cell in row fails intermittently I have some VBA code written which prepares a csv file for me so I can run individual macros on it for each model I have. The issue is every now and then, columns have duplicate data all the way down, rather than results of the formula copied down.
At first I thought it must be a memory issue, as if I rebooted and ran it again, it performed perfectly. This morning, regardless of how many times I rebooted, even once booting into Safe Mode on my Mac, it still did the same errors in the same columns.
What appears to happen on those times when it doesn't work correctly is in the CopyFormulaDownToLastRowOfData macro. It should be copying the results of the formula all the way down; so the results in each cell should be the result for that cell, but instead, it ends up with the result of the first cell copied all the way down. Here is the code for that particular macro
Sub CopyFormulaDownToLastRowOfData()
  Dim LastRow As Long
  LastRow = Cells.Find("*", , xlValues, , xlRows, xlPrevious).Row
  With Range(ActiveCell, Cells(LastRow, ActiveCell.Column))
    .FillDown
    .Value = .Value
  End With
End Sub

Can anyone see any issues with it?
Thanks in advance


text:
Q: no margin in IE7 I made an image gallery that renders correctly everywhere except IE7 - http://ianespinoza.com/.
I am using following structure:

...

         etc....
      </ul

here is the style applied to these elements:
#carouselContainer {
width:934px;
height:145px;
border:none;
overflow:hidden;
position:relative;
left:40px;
top:5px;}

#thumbContrainer {
position:relative;
left:20px;
height:110px;
margin:30px 0px;
width:5000px;
border:none;}

ul.thumb {
list-style: none;
margin: 0;
padding: 0px;}

All renders correctly in all the browsers, except IE7.
In IE 7 div "thumbContrainer" has no top margin, but I really need that margin.

A: Try to replace margin with padding in #thumbContrainer:
#thumbContrainer{
    position:relative;
    left:20px;
    height:110px;
    padding:30px 0px;
    width:5000px;
    border:none;
}

A: Thanks for all the answers and suggestions.
Actually the way I ended up fixing IE7 issue is by giving padding to the parent element - "carouselContainer", and removing margin for the "thumbContrainer".
Although it fixed the issue, still not sure what was wring with the original set up as, even using *margin-top wasn't helping.


text:
Q: Autofill UAC Dialog Win 7 Hy there
I searched a lot on google, but couldn't find an answer. Maybe you have some ideas:
I have two account's on my pc, an admin account an user account. I usually work on my user account. When I want to run an application or install a new application, I have to enter the admin password in the UAC dialog.
Now I want to write a program, witch detects the Win 7 UAC Dialog, and autofill the admin password. I thought, I could detect the UAC dialog, and save the admin password i a buffer. Then I only have to paste the password in the UAC dialog.
Any ideas if this could work, and how I could detect the UAC dialog?
peace!

A: The UAC dialog is DESIGNED to prevent this! Otherwise any virus could install itself without user input! Why are you doing this, instead of changing the UAC settings, or changing your account permissions?


text:
Q: Is there a thumbstick Linux image for checking hardware? Is there a thumbstick Linux image for checking hardware? Ideally I'd like to take it with me to a second hand shop, boot it up and run a quick round of diagnostics on hardware. It must have both latest NV and AMD drivers, as well as specialized software for detecting if they're damaged.

A: You can use the Hiren's BootCD
I used the included Video Memory Stress Test tool to check the video memory on my VAIO laptop after I was getting BSODs. It detected memory faults almost straight away.
It also comes with a great selection of other diagnostic tools.


text:
Q: What is a good choice for an ARM to interface with external memory? I just completed a project using the LPC2132 chip, but ran into problems with using up the whole 64kb of RAM.
For my next project, I'd like to use something that can reference an external, much larger memory chip. What sort of ARM can do this and what do I need to do to get the two devices talking?

A: The larger series of STM32 processors (32-bit Cortex-M3 core) has a FSMC, which is a Flexible Static Memory Controller.
With this you is able to connect Flash, RAM, and other memory peripherals like LCD and such.
I can recommend the STM32F103ZET6 as tcrosley also said, and you can get a development board including flash and sram on ebay for $68 - http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=220619908411

A: I recently had a similar requirement for a new project, and chose the STMicro STM32F103ZET6 (ARM 32-bit Cortex-M3), with 512K of internal Flash and 64K of internal RAM for around $10 in quantity.  It has a memory controller which can address up to 64MB of external memory (26 address bits).  Available in a 144-pin LQFP package.  (I don't like using BGA for prototypes.)  I will be interfacing it with a 2MB Cypress SRAM, without any other glue required (no multiplexing).

A: Maybe an Atmel AT91SAM9G20?
It's a bit of a beast (217-pin BGA package), but it's a great chip for the price. If you're looking for something a little more human-friendly, maybe try the Atmel AT91M42800A. I think that's the smallest MCU that has external memory hardware, at least from Atmel. It's a 144-pin LQFP package.
Atmel has a parametric selector: http://www.atmel.com/dyn/products/param_table_v2.asp?family_id=605&OrderBy=part_no&Direction=ASC
(I guess I should add that I don't work for Atmel; I just happen to be familiar with their stuff.)

A: You don't need an MMU for external RAM memory, the determining factor if you need one is a completely separate issue from simply needing more space.  If you've been coding directly to the metal it may actually make your life easier not having an MMU.  I'd also like to note that an MMU is virtually never an external component but rather on the SoC die.
You can find ARM SoCs in many families that allow external memory from the ARM7 on up for example the NXP LPC2212 Series not saying its the best, just the first ARM7 SoC that came up in google with an external memory interface, there are lots of options.
I'd pay more attention to the features of the various cores in the ARM families as you can find almost all of them in SoC's with external memory controllers.
Now as to what type of memory you need and how to get it working, that depends on the SoC you choose and what memory the external memory controller supports.  For instance the ARM7 SoC i linked supports external SRAM as well as flash's and roms and supports up to 4 16MB banks, so you could hook external flash and SRAM to it at the same time.
You could use separate RAM and flash IC's there are also packages called MCP (Multi Chip Package) that can include both flash and ram in 1 package.  How you choose these devices depends on many factors, you'd need to be more specific about your application.
How easy this is to hook up depends on the speed you need.  Most external memory controller have programmable clock rates.  The memory interface clock rates could be very high at least 10MHz and likely much higher.  In short your very likely not breadboarding something like this, you need to design a PCB and pay special attention to signal integrity issues for these lines.
Your best bet is to pick a core you want to play with and a find one of the many development boards out there with external memory on it.


text:
Q: How to turn all integers in an array into a single number? This is my array
[7, 8, 8, 0, 0, 7, 2, 3, 1]

I know how to add all of these numbers together, but how do I make them into one long number? For example:
788007231