text:
Q: Android - Endless scrolling with SuperSLiM There is any way to implement endless scrolling to load more itens when i use SuperSLiM library?
Normally I'm used to use the LinearLayoutManager.findFirstVisibleItemPosition() method to help me to know when I need load more itens... but now, with linearlayout of SuperSLiM i can't use this.
How can i implement this feature?

A: In place of LinearLayoutManager,use LayoutManager of superslim. I had implemented it in one of demo project. Row code for that is,
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener {
    private int previousTotal = 0; // The total number of items in the dataset after the last load
    private boolean loading = true; // True if we are still waiting for the last set of data to load.
    private int visibleThreshold = 5; // The minimum amount of items to have below your current scroll position before loading more.
    int firstVisibleItem, visibleItemCount, totalItemCount;

    private int current_page = 1;

    private LayoutManager mlayoutManager;

    public EndlessRecyclerOnScrollListener(LayoutManager linearLayoutManager) {
        this.mlayoutManager = layoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);

        visibleItemCount = recyclerView.getChildCount();
        totalItemCount = mlayoutManager.getItemCount();
        firstVisibleItem = mlayoutManager.findFirstVisibleItemPosition();

        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount)
                <= (firstVisibleItem + visibleThreshold)) {
            // End has been reached
            // Do something here
            current_page++;
            loading = true;
        }
    }
    public abstract void onLoadMore(int current_page);
}

I hope this will help you. :)


text:
Q: Change person height to centimeter on click of ToggleButton I have an EditText with a ToggleButton with option feet/inch and centimeters. If a user selects option feet/inches and enter his height. Now I want if user selects centimeters option from ToggleButton then it should automatically change his height to centimeters.
I have tried something like this:
     public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.btnCm:
                toggleHeightButton(R.id.btnCm,R.id.btnFeet,false);
                break;
            case R.id.btnFeet:
                toggleHeightButton(R.id.btnFeet,R.id.btnCm,true);
                enter_height.addTextChangedListener(new CustomTextWatcher(enter_height));
                break;
            case R.id.btnKg:
                toggleweightButton(R.id.btnKg,R.id.btnpound,false);
                break;
            case R.id.btnpound:
                toggleweightButton(R.id.btnpound,R.id.btnKg,true);
                break;

        }
    }

    public class CustomTextWatcher implements TextWatcher {
        private EditText mEditText;
    public CustomTextWatcher(EditText enter_height) {
        mEditText = enter_height;
    }

     public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
    }

    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    public void afterTextChanged(Editable s) {
        int count = s.length();
        String str = s.toString();
        if (count == 1) {
            str = str + "'";
        } else if (count == 2) {
            return;
        } else if (count == 3) {
            str = str + "\"";
        } else if ((count > 4) && (str.charAt(str.length() - 1) != '\"') ){
            str = str.substring(0, str.length() - 2) + str.charAt(str.length() - 1)
                    + "\"";
        } else {
            return;
        }

        mEditText.setText(str);
        mEditText.setSelection(mEditText.getText().length());
    }
}

Can anybody tell me from here how can I approach. I also wanted to validate the height.

A: In your onToggleListener/onClickListener()
//toCm is true if converting from inches to centimeters
private void toggleHeight(int height, boolean toCm) {

    if (height > 0) {
        if (toCm) {
            //2.54cm is equal to 1inch
            return height / 2.54;
        } else {
            return height * 2.54.
        }
    } else {
        return 0;
    }
}

Then you can set your mEditText to the new height which will display it to the user.
There will be some precision loss but seeing as how you simply want to display this to the user, this should work just fine.

redpajama_set_name: RedPajamaStackExchange


text:
Q: STL like container with O(1) performance I couldn't find an answer but I am pretty sure I am not the first one looking for this.
Did anyone know / use / see an STL like container with bidirectional access iterator that has O(1) complexity for Insert/Erase/Lookup  ?
Thank you.

A: tr1's unordered_set (also available in boost) is probably what you are looking for. You don't specify whether or not you want a sequence container or not, and you don't specify what you are using to give O(1) lookup (ie. vectors have O(1) lookup on index, unordered_set mentioned above has O(1) average case lookup based on the element itself).

A: There is no abstract data type with O(1) complexity for Insert, Erase AND Lookup which also provides a bi-directional access iterator.
Edit:
This is true for an arbitrarily large domain. Given a sufficiently small domain you can implement a set with O(1) complexity for Insert, Erase and Lookup and a bidirectional access iterator using an array and a doubly linked list:
std::list::iterator array[MAX_VALUE];
std::list list;

Initialise:
for (int i=0;i<MAX_VALUE;i++)
    array[i] = list.end();

Insert:
if (array[value] != list.end())
    array[value] = list.insert(value);

Erase:
if (array[value] != list.end()) {
    array[value].erase();
    array[value] = list.end();
}

Lookup:
array[value] != list.end()

A: Associative arrays (hashtable) have O(1) lookup complexity, while doubly linked lists have O(1) bidi iteration.

A: One trick I've done when messing about storage optimization is to implement a linked list with an add of O(1)[1], then have a caching operation which provides a structure with a faster O(n) lookup[2]. The actual cache takes some O(n) time to build, and I didn't focus on erase. So I 'cheated' a bit and pushed the work into another operation. But if you don't have to do a ton of adds/deletes, it's not a bad way to do it.
[1] Store end pointer and only add onto the end. No traversal required.
[2] I created a dynamic array[3] and searched against it. Since the data wasn't sorted, I couldn't binsearch against it for O(lg n) time. Although I suppose I could have sorted it.
[3]Arrays have better cache performance than lists.

A: Full list of all the complexity gurantees for the STL can be found here:
What are the complexity guarantees of the standard containers?
Summary:

*

*Insert: No container gurantees O(1) for generic insert.

*

*The only container that has a genric insert gurtantee is: the 'Associative Container'. And this is O(ln(n))

*There are containers the provide limited insert gurantees

*

*Forward sequece gurantee an insert at head of O(1)

*Back sequence gurantee an insert at tail of O(1)

*Erase

*

*The Associative containers gurantee O(1) for erase (If you have an iterator).

*Lookup:

*

*If you mean element access by lookup (as no container has O(1) find capabilities).

*Then Random Access container is the only container with O(1) accesses

So the answer is based on container types.
This is what the standard gurantees are defiend for how does this translate to real containers:
std::vector:    Sequence,   Back        Sequence,                   Forward/Reverse/Random Container
std::deque:     Sequence,   Front/Back  Sequence,                   Forward/Reverse/Random Container
std::list:      Sequence,   Front/Back  Seuqence,                   Forward/Reverse Container
std::set:       Sorted/Simple/Unique    Associative Container,      Forward Container
std::map:       Sorted/Pair/Unique      Associative Container,      Forward Container
std::multiset:  Sorted/Simple/Multiple  Associative Container,      Forward Container
std::multimap:  Sorted/Pair/Multiple    Associative Container,      Forward Container

A: In practice, it may be sufficient to use array (vector) and defer costs of inserts and deletes.
Delete element by marking it as deleted, insert element into bin at desired position and remember offset for larger indices.
Inserts and deletes will O(1) plus O(N) cleanup at convenient time; lookup will be O(1) average, O(number of changes since last cleanup) worst case.

A: You won't be able to fit all of your requirements into one container... something's gotta give ;)
However, maybe this is interesting for you:
http://www.cplusplus.com/reference/stl/


text:
Q: Recover sheet protection password in Excel I have an Excel workbook.
Two years ago I set password protection option for one of the sheets. Now I have forgotten the password. Is there any way to recover the password of that Excel sheet?

A: You cannot recover THE password, but you can unprotect the sheet(The hash used to protect the sheet is quite prone to collisions in the old versions of excel, so generating a collision is quite fast here).
There are scripts availale the will brute force open your sheet within a very short amount of time.
Take a look here for example:
http://www.theofficeexperts.com/VBASamples/Excel02.htm
Here's the code:
Sub PasswordBreaker()
  'Author unknown but submitted by brettdj of www.experts-exchange.com

  Dim i As Integer, j As Integer, k As Integer
  Dim l As Integer, m As Integer, n As Integer
  Dim i1 As Integer, i2 As Integer, i3 As Integer
  Dim i4 As Integer, i5 As Integer, i6 As Integer
  On Error Resume Next
  For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
  For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
  For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
  For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126

 ActiveSheet.Unprotect Chr(i) & Chr(j) & Chr(k) & _
      Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
      Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
  If ActiveSheet.ProtectContents = False Then
      MsgBox "One usable password is " & Chr(i) & Chr(j) & _
          Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
          Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
   ActiveWorkbook.Sheets(1).Select
   Range("a1").FormulaR1C1 = Chr(i) & Chr(j) & _
          Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
          Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
       Exit Sub
  End If
  Next: Next: Next: Next: Next: Next
  Next: Next: Next: Next: Next: Next

End Sub


text:
Q: Building an MSSQL database with ColdFusion or Java from an ".sql" file? I have a .sql file that was created using the MS SQL Management Studio Script Wizard. It contains the entire database schema including views, stored procedures, tables, indexes, etc.
I'm looking for a way to automate the process of creating the database with ColdFusion or Java or even .NET.
I've tried using CFQUERY but it throws all kinds of errors with the .sql file.
I've tried using ANT with sqljdbc4.jar but it also fails on the first line with a "[sql] Failed to execute:  BEGIN TRAN" com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near ''.

A: I highly doubt you can use the scripts generated by the wizard outside of an MS tool. The wizard makes copious use of GO which is not standard T-SQL. Also, commands like CREATE PROCEDURE need to be the first statement within the batch. To run the wizard scripts, you need to use an MS tool like sqlcmd.exe. With the correct permissions, you should be able to run sqlcmd.exe from <cfexecute>.

A: You should be able to execute all the SQL within a <cfquery assuming you have the appropriate permissions.
We generate all our databases like this with CREATES etc in a ColdFusion <cfquery
Do you have the appropriate permissions, what errors are you getting.

A: If you're using ORM, you may set this.ormsettings.sqlscript to point to your .sql file in Application.cfc and it'll be run on ORMReload() when this.ormsettings.dbcreate is set to dropcreate.
http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSED380324-6CBE-47cb-9E5E-26B66ACA9E81.html
Good luck


text:
Q: How to run webapp2(appengine) in Heroku? Here is my project file
Procfile
web: python main.py

requirement.txt
webapp2==2.3

main.py
import webapp2

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.write("hello")

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

still heroku give out a Application Error
what's wrong with my project?

A: Base on their getting started with python it seems like you need gunicorn web server. Try adding gunicorn in your requirements.txt and procfile web: gunicorn main:app
Forgot to add the link:
https://devcenter.heroku.com/articles/python
Also here is my webapp2-starter, it's setup to act like an appengine dev server but works outside app engine.
https://github.com/faisalraja/webapp2-starter


text:
Q: Why AWS Device Farm is allowing to only few devices to run tests? I am working with AWS Device Farm.
I ran tests by selecting some devices randomly it is allowing to run on some devices only. For others it is not allowing to go through. Does anyone know why?
You can see the image below


text:
Q: How to grant xp_delete_file to non-sysadmin login? I want to delete old backups from shared folder, which are located on separate NAS storage, using newly created SQL login. Is there any workaround to execute xp_delete_file using another account which is not a member of sysadmin role?

A: Deleting files on NAS should not be done by sql server. You should rather use powershell to do it.
You can use my function Clean-NASOldFiles which uses robocopy to scan files extremely fast and will then delete based on your input.


text:
Q: How to count null values in postgresql? select distinct "column" from table;

output:
    column
1     0.0
2     [null]
3     1.0

But when I try to count the null values
select count("column") from train where "column" is NULL;

Gives output 0 (zero)
Can you suggest where it's going wrong?

A: Some workaround when you want to count the values on aggregations, including NULL ones, but can't use count(*) (if other columns are different too).
On these cases, you can use this request :
count(distinct("column")) + (CASE bool_or("column" is null) WHEN true THEN 1 ELSE 0 END)

The count(distinct(column)) will count the non null values, and the other part will add 1 if there is a null value

A: Use count(*):
select count(*) from train where "column" is NULL;

count() with any other argument counts the non-NULL values, so there are none if "column" is NULL.

A: Use FILTER
SELECT
  COUNT(*) FILTER (WHERE "column" IS NULL) AS is_null,
  COUNT(*) FILTER (WHERE "column" < 1.0) AS lt_one,
  COUNT(*) FILTER (WHERE "column" > 1.0) AS gt_one,
  COUNT(*) FILTER (WHERE "column" = 1.0) AS just_perfect
FROM "table";

A: Use SUM
SELECT SUM(CASE WHEN column IS NULL THEN 1 ELSE 0 END) AS column_null_tally
FROM table;

A: You get zero because you are counting null (empty) values, you need to count values from a field that is not empty, like the id field.
select count("id_column") from train where "data_column" is NULL;

A: Since

*

*select count(coalesce(t."column", 0)) from table t is the full number with NULL:s and

*select count(t."column") from table t is the number without NULL:s,

this works as well:
Select count(coalesce(t."column", 0)) - count(t."column") FROM table t;

(This answer might also help those who came here to count both NULL and not NULL, at least I was stranded here since I was searching for that).


text:
Q: Android quiz, how to display if answer is correct and randomise answers Hi I am currently working on an Android quiz app which works ok, it reads the questions and gives a ratings bar based on your score out of 8. However, I would also like to be able to randomise the questions to make it a little more interesting and to display if the answer is correct or not, either through a toast or text statement. I have been looking online to try various options and cannot find a way to resolve it without making lots of errors. the code for my main activity is below
Thanks,
package com.example.QuizApp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.ArrayList;
import android.widget.Toast;

public class MyActivity extends Activity {
    /**
     * Called when the activity is first created.
     */

    int score = 0;
    int questionNumber = 0;

    Question questionsObject;
    RadioButton quizAnswerA;
    RadioButton quizAnswerB;
    RadioButton quizAnswerC;
    Button next;
    TextView questionTextView;

    ArrayList<Question> questionsList = new ArrayList<Question>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
//      addListenerOnButton();
        next = (Button) findViewById(R.id.nextButton);

          Question q1 = new Question("How much is an adult ticket with camping for the Isle of Wight?", "£30", "£190", "£200", "£190");
    questionsList.add(q1);
    Question q2 = new Question("How many people can the Isle of Wight festival hold?", "60,000", "75,000", "100,000", "60,000");
    questionsList.add(q2);
    Question q3 = new Question("Which year did the Isle of Wight festival begin?", "1968", "1971", "1995", "1968");
    questionsList.add(q3);
    Question q4 = new Question("What is the name of the town outside which Isle of Wight is held?", "New Forest", "Sandown", "Newport", "Newport");
    questionsList.add(q4);
    Question q5 = new Question("Which date does Isle of Wight start??", "12 June", "18 June", "6 August", "12 June");
    questionsList.add(q5);
    Question q6 = new Question("Who are headline acts on Friday?", "Biffy Clyro and Calvin Harris", "Madonna and LMFAO", "The Red Hot Chilli Peppers", "Biffy Clyro and Calvin Harris");
    questionsList.add(q6);
    Question q7 = new Question("By which alternative name was the revival known as?", "Rebellion", "Rock Island", "Big Day Out", "Rock Island");
    questionsList.add(q7);
    Question q8 = new Question("Who was the first headline act?", "Arthur Brown", "The Rolling Stones", "Jefferson Airplane", "Jefferson Airplane");
    questionsList.add(q8);
    //questions declared and initialised

        //object to create current question
        questionsObject = (Question) questionsList.get(questionNumber);

        //button ID's to link XML
        questionTextView = (TextView) findViewById(R.id.question_1);
        quizAnswerA = (RadioButton) findViewById(R.id.answerA);
        quizAnswerB = (RadioButton) findViewById(R.id.answerB);
        quizAnswerC = (RadioButton) findViewById(R.id.answerC);

        //method to call questions and answers
        setView();

        //on click listener
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
                RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
                if (questionsObject.getCorrectAnswer().equals(answer.getText())) {
                     score++;
                }

                if (questionNumber < questionsList.size()) {
                    questionsObject = questionsList.get(questionNumber);
                    setView();
                } else {
                    Intent intent = new Intent(getApplicationContext(), Results.class);
                    Bundle b = new Bundle();
                    b.putInt("score", score); //"score" is the key to reference the variable score.
                    intent.putExtras(b);
                    startActivity(intent);
                }
            }
        });

    }

    //method to set view of activity using the current object
    private void setView() {
        questionTextView.setText(questionsObject.getQuestion());
        quizAnswerA.setText(questionsObject.getAnswerA());
        quizAnswerB.setText(questionsObject.getAnswerB());
        quizAnswerC.setText(questionsObject.getAnswerC());
        questionNumber++;
    }

}

A: If you wish to randomise the order that the questions are asked, you could use the Collections.shuffle method. Once you've added all the questions, just write
Collections.shuffle(questionList);

To show a toast, you should write:
if (questionsObject.getCorrectAnswer().equals(answer.getText())) {
    Toast.makeText(getApplicationContext(),
                   "Correct!",
                   Toast.LENGTH_SHORT)
                  .show();
    score++;
}
else {
    Toast.makeText(getApplicationContext(),
                   "Sorry! Better luck next time.",
                   Toast.LENGTH_SHORT)
                   .show();
}


text:
Q: Android on Onclick not working I have two buttons on my android app. One works perfectly (ViewLogs) the other (OfflineSync) does not - the code is the same and I get no errors?
package com.teamtba.hcpm;

import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ViewLogs extends Activity {

//Buttons
Button ViewLogs;
Button btnOfflineSync;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_account)

        btnOfflineSync = (Button)findViewById(R.id.btnSyncOffline);

        ViewLogs = (Button)findViewById(R.id.btnCreateLog);
        // Hashmap for ListView
        btnOfflineSync.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent tr = new Intent(ViewLogs.this, CreateLog.class);
                startActivity(tr);
            }
        });

        ViewLogs.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(ViewLogs.this, CreateLog.class);
                startActivity(i);
            }

        });

        btnOfflineSync.setVisibility(View.GONE);

I've cut out the other code that is in there but if you want to see it I can post it (it's mainly just other functions that don't call the button.
I've tried via XML but it generates an error everytime and crashes the app.

A: You have btnOfflineSync.setVisibility(View.GONE);
How are you sending onClick event?

A: Class name ViewLogs and button name ViewLogs  are same, change button name to something

A: - First remarque :
The activity has the same name as the button so try to change the name of the button (to viewLogs)
- Second remarque :
the action of the two buttons has the same function (intent to start CreateLogs.class) .
So, you can use one function (onClick):
btnOfflineSync.setOnClickListener(this);
viewLogs.setOnClickListener(this);
//
}
public void onClick(View v) {
Intent tr = new Intent(ViewLogs.this, CreateLog.class);
                startActivity(tr);
}

and don't forget to implement  OnClickListener
- Third remarque:
you write btnOfflineSync.setVisibility(View.GONE); after the onclickListener (??) How are you sending onClick event ? you can remove this line , an make your button visible
public class ViewLogs extends Activity {

//Buttons
Button viewLogs; //button name changed
Button btnOfflineSync;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view_account)

        btnOfflineSync = (Button)findViewById(R.id.btnSyncOffline);

        viewLogs = (Button)findViewById(R.id.btnCreateLog); //button name changed
        // Hashmap for ListView
        btnOfflineSync.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent tr = new Intent(ViewLogs.this, CreateLog.class);
                startActivity(tr);
            }
        });

        viewLogs.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                Intent i = new Intent(ViewLogs.this, CreateLog.class);
                startActivity(i);
            }

        });


text:
Q: Bulk creation of email account in QMail Is there any command in QMail server that I can create bulk email accounts.
OS : RedHat Linux Enterprises
Email Server : QMail
CP : Plesk 9

A: Yes, I have done it.
I creaed list of email in a text file.
Used the mail.sh command to process the file and created the email address in bulk.


text:
Q: Adding Columns dynamically to Salesforce Reports I need to add columns to a salesforce report dynamically(based on particular conditions). I'm planning to do this with a trigger that is looking for my conditions.  My two questions,

*

*Is it possible to adding columns dynamically for a Report?

*Can we schedule triggers based on time intervals instead of database updates?

Thanks, BR
Madura

A: I'm not aware of any possibility to manipulate Reports from Apex. Report definitions can be retrieved and modified with Metadata API (the one used in Eclipse IDE for example) but that means you'd have to use hacks since Metadata API is not easily available in Apex.
It's a kind of "known problem" and many people have already researched it:

*

*http://boards.developerforce.com/t5/Apex-Code-Development/Is-it-possible-to-call-Metadata-API-from-Apex-code-Getting-Error/td-p/119412

*https://github.com/financialforcedev/apex-mdapi - looks really interesting I'd say

*https://salesforce.stackexchange.com/questions/1082/has-anyone-ever-successfully-invoked-the-metadata-api-from-within-apex
Do you really think that some kind of "dynamic report" is a valid solution for business need though? I mean - users would be confused if they added some columns to the report and next day the report definition will change wiping out their work...

As for the other question - you probably shouldn't use the word "trigger" ;) If you want some Apex to run in time intervals you should have a lookt at job scheduling (write a class that implements Schedulable) and then you can schedule it to run at specific times. Without special tweaking the job can fire even every hour.
Of course there's also option of time-based workflows that would perform a field update and cause some real trigger to fire but that's very data-centric - no guarantees that it will run at time intervals.


text:
Q: Syncing data to/from multiple devices to a cloud? Interested in existing api packages, examples, guides, best practices etc on syncing data from multiple android devices to a server.  This would be  data that is stored in my application and could be sent to/from the server using any means necessary, probably JSON.
The server doesn't have to be java but that would be preferred.


text:
Q: python re regex matching in string with multiple () parenthesis I have this string
cmd = "show run IP(k1) new Y(y1) add IP(dev.maintserial):Y(dev.maintkeys)"

What is a regex to first match exactly "IP(dev.maintserial):Y(dev.maintkeys)"
There might be a different path inside the parenthesis, like (name.dev.serial), so it is not like there will always be one dot there.
I though of something like this:
re.search('(IP\(.*?\):Y\(.*?\))', cmd) but this will also match the single IP(k1) and Y(y1
My usage will be:
If "IP(*):Y(*)" in cmd:
 do substitution of IP(dev.maintserial):Y(dev.maintkeys) to Y(dev.maintkeys.IP(dev.maintserial))

How can I then do the above substitution? In the if condition I want to do this change in order: from IP(path_to_IP_key):Y(path_to_Y_key) to Y(path_to_Y_key.IP(path_to_IP_key)) , so IP is inside Y at the end after the dot.

A: This should work as it is more restrictive.
(IP\([^\)]+\):Y\(.*?\))
[^\)]+ means at least one character that isn't a closing parenthesis.
.*? in yours is too open ended allowing almost anything to be in until "):Y("

A: Something like this?
r"IP\(([^)]*\..+)\):Y\(([^)]*\..+)\)"

You can try it with your string. It matches the entire string IP(dev.maintserial):Y(dev.maintkeys) with groups dev.maintserial and dev.maintkeys.
The RE matches IP(, zero or more characters that are not a closing parenthesis ([^)]*), a period . (\.), one or more of any characters (.+), then ):Y(, ... (between the parentheses -- same as above), ).
Example Usage
import re

cmd = "show run IP(k1) new Y(y1) add IP(dev.maintserial):Y(dev.maintkeys)"

# compile regular expression
p = re.compile(r"IP\(([^)]*\..+)\):Y\(([^)]*\..+)\)")

s = p.search(cmd)
# if there is a match, s is not None
if s:
    print(f"{s[0]}\n{s[1]}\n{s[2]}")
    a = "Y(" + s[2] + ".IP(" + s[1] + "))"
    print(f"\n{a}")

Above p.search(cmd) "[s]can[s] through [cmd] looking for the first location where this regular expression [p] produces a match, and return[s] a corresponding match object" (docs). None is the return value if there is no match. If there is a match, s[0] gives the entire match, s[1] gives the first parenthesized subgroup, and s[2] gives the second parenthesized subgroup (docs).
Output
IP(dev.maintserial):Y(dev.maintkeys)
dev.maintserial
dev.maintkeys

Y(dev.maintkeys.IP(dev.maintserial))

A: You can use 2 negated character classes [^()]* to match any character except parenthesis, and omit the outer capture group for a match only.
To prevent a partial word match, you might start matching IP with a word boundary \b
\bIP\([^()]*\):Y\([^()]*\)

Regex demo


text:
Q: How to make an animation subplot with Matplotlib on Basemap? I'm trying to make a two-panel animation with time. I've found a similar example that I want to do, but I cannot go through with. Here's my code.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.basemap import Basemap

#dummy temperature data with 10 time-steps
y = np.random.randn(10, 60, 100)

fig, ax = plt.subplots(1,2)

ax[0].set_title("aaaa")
m_a = Basemap(projection='kav7',lon_0=0)
lats = np.linspace(90,-90,y.shape[1])
lons = np.linspace(-180,180,y.shape[2])
lons, lats = np.meshgrid(lons,lats)

m_a.drawparallels(np.arange(-90.,99.,30.), labels=[1,0,0,0])
m_a.drawmeridians(np.arange(-180.,180.,60.), labels=[0,0,0,1])
m_a.drawcoastlines(linewidth=0.25)
m_a.pcolormesh(lons,lats,y[0],cmap=plt.cm.bwr, shading='flat',latlon=True)

ax[1].set_title("bbbb")
m_b = Basemap(projection='kav7',lon_0=0)
lats = np.linspace(90,-90,y.shape[1])
lons = np.linspace(-180,180,y.shape[2])
lons, lats = np.meshgrid(lons,lats)

m_b.drawparallels(np.arange(-90.,99.,30.), labels=[1,0,0,0])
m_b.drawmeridians(np.arange(-180.,180.,60.), labels=[0,0,0,1])
m_b.drawcoastlines(linewidth=0.25)
m_b.pcolormesh(lons,lats,y[0],cmap=plt.cm.bwr, shading='flat',latlon=True)

def init():
    fig

def animate(i):
    m_a.pcolormesh(lons,lats,y[i],cmap=plt.cm.bwr,shading='flat',latlon=True)
    m_b.pcolormesh(lons,lats,y[i],cmap=plt.cm.bwr,shading='flat',latlon=True)
    return m_a, m_b

anim = animation.FuncAnimation(fig, animate, init_func=init, frames=10, interval=100) #interval = number of milliseconds between frames

plt.show()

However, the result animation is here⇒enter image description here. Why is this happening? I'm glad if you review the code.

A: I guess you just forgot to specify the axes or the basemap to live in.
m_a = Basemap(projection='kav7',lon_0=0, ax=ax[0])
# ...
m_b = Basemap(projection='kav7',lon_0=0, ax=ax[1])


text:
Q: Computation of a mean (random sum) Let $X_1$, $X_2$, ... be independent and identially distributed positive random variables and define the sum $S_n = X_1 + X_2 + ... + X_n$. Consider the first time $N$ where $S_N \ge b$ with a given positive value $b$.
I need to compute (simplify) $E(NS_N)$. I need an expression in function of simple terms like $E(N)$, $E(X_1)$ etc... How proceed ? I'm not mastering the conditional mean.
Thank you

A: Hints
Do you want to assume independence between $N$ and $X_i$? Then condition on $N$ and separate using independence.
Otherwise, you have to assume at least that $N$ is a stopping time with respect to the $\sigma$-algebra, generated by the $X_i$.
Now assume first that $X_i$ are 0-mean (eventually you will let $X_i = \mu + Y_i$ where $Y_i$ will be 0-mean, but for now assume $\mu=0$).
Now note that the stochastic process $\{S_n\}$ is a martingale, so $\mathbb{E}[S_N] = \mathbb{E}[S_t]$ for any $t$ (by Doob's lemma), in particular for $t=0$, and we know $\mathbb{E}[S_0]=0$.
I think you can argue similarly for the process $\{nS_n\}$, and then apply the construction with $Y_n$ to get your expected value.
To make that construction more formal, let $Y_i = X_i - \mu$ where $\mu = \mathbb{E}[X_1]$ so $\mathbb{E}[Y_1] = 0$ and now $Y_i$ are identical and 0-mean. Let $T_n = \sum_{k=1}^n Y_k$. By the above logic it follows that $\mathbb{E}[N T_N] =0$. But
$$
N T_N = N \sum_{k=1}^N Y_i = N \sum_{k=1}^N (X_i - \mu) = NS_N - \mu N^2
$$
and taking expected values, note that the left-hand side becomes $\mathbb{E}[N T_N] =0$ and you can draw conclusions...


text:
Q: Wrong character encoding in dist jar generated with NetBeans I finally wrote me little app. It's desktop app but it has embedded web server. When I lunched it from NetBeans everything is ok.  When I lunch dist jar I have correct character encoding in GUI, but web server output is corrupted ("?" instead of national characters).
I use NetBeans 6.7.1, jdk1.6.0_16, http server from Java 6 SE and lib Rome 1.0
I don't put any source code here, because I have no idea witch part should I put.
//edit:
data are hardcoded in Strings. Those Strings are passed to Rome as arguments to create RSS nodes, Romes RSS feeds are are written to String and then Strings are passed to HttpHandler.

A: *

*Check the encoding in the source files.

*Check any point where encoding/decoding is performed (often any place where String -> byte[] or byte[] -> String). Anything that converts bytes to Strings is performing an encoding operation myEncoding -> UTF-16.

*Check that you are passing the appropriate encoding information to 3rd party libraries that perform encoding/decoding.

*If generating XML, ensure that the header encoding matches the encoding used to write the bytes (<?xml version="1.0" encoding="UTF-8"?>).

*If serving content over HTTP, ensure that the content type and charset header is correct (e.g. Content-Type: text/html; charset=utf-8). A charset is usually only applicable if serving a text MIME type (it is not applicable for application/rss+xml, for example). Check your MIME documentation.

A: This issue probably has nothing to do with NetBeans. Usually character encoding issues are due to not defining the character encoding somewhere, in which case the actual character encoding will be determined pretty much by luck.
For instance, Java Strings are UTF-16 internally, but the encoding used by Java Readers is determined by the platform default unless explicitly specified.


text:
Q: JS Object filter on attribute doesn't work if attribute doesn't exists I'm filtering an object and I want to keep only attributes where there is a match between a key and a value.
My code is this
  const result = Object.fromEntries(Object.entries(obj).filter(([key, val]) => {
    return val.collection.family.includes('MyValue');
  }));

The issue is that for some attributes collection is not defined, or family is not defined. This cause a console error.
How can I solve?

A: Since it's within a filter, you should be able to use optional chaining safely:
const result = Object.fromEntries(Object.entries(obj).filter(([key, val]) =>
    !!val?.collection?.family.includes('MyValue');
));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining


text:
Q: Speed of Sound/Push in Supersonic Flight I've learned from things like the Veritasium Slink Drop and the old "break the speed of light by pushing on the end of a very long pole" thought experiment that objects have a "speed of push" which is commonly referred to as the speed of sound. My understanding of this being that information about movement can't propagate through a medium faster than the speed of sound in that medium.
So my question is: What happens to air when a supersonic jet flies through it? On the one hand it would seem that air can't move out of the way of the jet faster than the speed of sound in the air, however the jet obviously displaces the air at supersonic speeds anyway. So what's happening?

A: You are right that the air can't get out of the way in a continuous fashion. When you move an object through a fluid at a speed that exceeds the fluid's sound speed, then discontinuities may form known as shocks. The sonic boom associated with superonic jets is one consequence of the formation of these shocks.
Supersonic fluid motion isn't always associated with shocks, though. You can smoothly accelerate fluid to supersonic velocities in a setup such as a de Laval nozzle. But decelerating a supersonic flow often requires a shock. In the rest frame of a supersonic jet, upstream air is approaching supersonically, then shocks and decelerates.
So how does all this fit with the idea that information can't move in a fluid at a speed faster than sound? You have to clearly define what you mean by information carried by the fluid. One way is to think in terms of fluid pressure. If we again think of a nozzle in which fluid is accelerated supersonically, then pressure variations in the supersonic part of the flow won't affect the subsonic part of the flow. People sometimes say that the supersonic part of the flow is carried off "ballistically," and is detached (in terms of pressure) from the subsonic part.

A: Here is a quote by Ernst Mach (from a public lecture):
"If the projectile moves faster than sound, the air ahead of it cannot recede from it quickly enough. The air is condensed and warmed, and thereupon, as all know, the velocity of sound is augmented until the head-wave travels forward as rapidly as the projectile itself, so that there is no need whatever of any additional augmentation of the velocity of propagation. If such a wave were left entirely to itself, it would increase in length and soon pass into an ordinary sound-wave, travelling with less velocity. "
What he's saying there is that the speed of sound ahead of a ballistic projectile actually increases due to the effect of compression -- which raises the temperature of the air in front of the projectile. The formula is of course:
$$c_{ideal}=(\gamma R T)^{0.5}$$
The rest is a continuation of the quote for the sake of context (the public lecture was about the double report of ballistic projectiles from artillery):
"But the projectile is always behind it and so maintains it at its proper density and velocity. Even if the projectile penetrates a piece of cardboard or a board of wood, which catches and obstructs the head-wave, there will, immediately appear at the emerging apex a newly formed, not to say newly born, head-wave. We may observe on the cardboard the reflexion and diffraction of the head-wave, and by means of a flame its refraction, so that no doubt as to its nature can remain."


text:
Q: Chapter number in left right margin I would like to move the chapter number in the right margin (a bit like in the classicthesistheme) but all I tried just results in errors, it would be nice if some could have a look. My MWE is using scrreprt and I can't move to the memoir class.

\documentclass[
fontsize=12pt,
twoside,
a4paper,
parskip=half,
ngerman,
headings=big]
{scrreprt}

\usepackage[english,german]{babel}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{blindtext}
\usepackage{etoolbox}

\DeclareMathAlphabet\EuRoman{U}{eur}{m}{n}
\SetMathAlphabet\EuRoman{bold}{U}{eur}{b}{n}
\newcommand{\eurom}{\EuRoman}

% Define own Chapter style
% Pretty chapter pages
%------------------------------------------
\definecolor{nicered}{rgb}{.647,.129,.149}
\usepackage{soul}
\usepackage{pdfpages}

\makeatletter
\newsavebox{\feline@chapter}
\newcommand\feline@chapter@marker[1][4cm]{%
    \sbox\feline@chapter{%
        \resizebox{!}{#1}{\fboxsep=-0pt%\eurom{A}
            \colorbox{white}{\color{black}$\eurom{\thechapter}$}}}%
%       \rotatebox{90}{%
%           \resizebox{%
%               \heightof{\usebox{\feline@chapter}}+\depthof{\usebox{\feline@chapter}}}%
%           {!}{\scshape\so\@chapapp}}\hspace{.4mm}%Abstand zum Wort Kapitel
        \raisebox{\depthof{\usebox{\feline@chapter}}}{\usebox{\feline@chapter}}%
    }

            \newcommand\feline@chm[1][4cm]{%
                \sbox\feline@chapter{\feline@chapter@marker[#1]}%
                \makebox[0pt][l]{% aka \rlap
                    \makebox[1cm][r]{\usebox\feline@chapter}%
                }
            }

        \renewcommand*{\chapterformat}{%
            \hspace{\leftmargin} \feline@chm[1.61cm] % Height of the colored box
            \hspace{0.3cm}%Abstand zur Colorbox
        }

\patchcmd{\@@makechapterhead}
{\usekomafont{chapter}{#1}}
{\parbox[b]{\dimexpr\textwidth-4cm\relax}{\raggedright\usekomafont{chapter}{#1}}}
{\typeout{great}}
{\typeout{too bad}}
\makeatother
%------------------------------------------

\begin{document}

\chapter{Lorem ipsum dolor sit amet, consectetuer adipiscing elit}
         \blindtext[2]

\end{document}

A: Here is a another suggestion
\documentclass[
fontsize=12pt,
twoside,
a4paper,
parskip=half,
ngerman,
headings=big,
open=right
]
{scrreprt}

\usepackage[english,german]{babel}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{blindtext}
%\usepackage{showframe}

\DeclareMathAlphabet\EuRoman{U}{eur}{m}{n}
\SetMathAlphabet\EuRoman{bold}{U}{eur}{b}{n}
\newcommand{\eurom}{\EuRoman}

% Define own Chapter style
% Pretty chapter pages
%------------------------------------------
\definecolor{nicered}{rgb}{.647,.129,.149}
\usepackage{pdfpages}
\usepackage{etoolbox}

\makeatletter
\newsavebox{\feline@chapter}
\newcommand\feline@chapter@marker[1][4cm]{%
  \sbox\feline@chapter{%
    \resizebox{!}{#1}{\setlength{\fboxsep}{0pt}%
        \colorbox{white}{\color{black}$\eurom\thechapter$}}}%
  \raisebox{\depth}{\usebox{\feline@chapter}}%
}
\renewcommand*{\chapterformat}{%
  \sbox\feline@chapter{\feline@chapter@marker[1.61cm]}%
  \makebox[0pt][l]{%
    \makebox[\dimexpr\textwidth+\marginparsep+\wd\feline@chapter\relax][r]{%
      \usebox\feline@chapter}}%
}
\makeatother

\preto\chapterheadendvskip{%
  \vspace*{-\parskip}%
  {\noindent\setlength\parfillskip{0pt plus 1fil}\rule{\textwidth}{.4pt}\par}%
}

\begin{document}
\tableofcontents
\chapter{Lorem ipsum dolor sit amet, consectetuer adipiscing elit}
\blindtext[2]
\end{document}

Note that I would use open=right if the chapter number should be in the right margin.
Result:

Update as answer of a comment below:
If you want to use \MakeUppercase for the chapter titles you can redefine \chapterlinesformat. Note that the following example needs at least KOMA-Script version 3.19:
\documentclass[
fontsize=12pt,
twoside,
parskip=half,
ngerman,
headings=big,
open=right
]
{scrreprt}[2015/10/03]

\usepackage{babel}
\usepackage[utf8]{inputenc}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{etoolbox}

\usepackage{blindtext}

\DeclareMathAlphabet\EuRoman{U}{eur}{m}{n}
\SetMathAlphabet\EuRoman{bold}{U}{eur}{b}{n}
\newcommand{\eurom}{\EuRoman}

\makeatletter
\newsavebox{\feline@chapter}
\newcommand\feline@chapter@marker[1][4cm]{%
  \sbox\feline@chapter{%
    \resizebox{!}{#1}{\setlength{\fboxsep}{0pt}%
        \colorbox{white}{\color{black}$\eurom\thechapter$}}}%
  \raisebox{\depth}{\usebox{\feline@chapter}}%
}
\renewcommand*{\chapterformat}{%
  \sbox\feline@chapter{\feline@chapter@marker[1.61cm]}%
  \makebox[0pt][l]{%
    \makebox[\dimexpr\textwidth+\marginparsep+\wd\feline@chapter\relax][r]{%
      \usebox\feline@chapter}}%
}
\renewcommand\chapterlinesformat[3]{%
  \ifstr{#1}{chapter}
  {\@hangfrom{#2}{\MakeUppercase{#3}}}
  {\@hangfrom{#2}{#3}}%
}
\makeatother

\preto\chapterheadendvskip{%
  \vspace*{-\parskip}%
  {\noindent\setlength\parfillskip{0pt plus 1fil}\rule{\textwidth}{.4pt}\par}%
}

\begin{document}
\tableofcontents
\chapter{Lorem ipsum dolor sit amet, consectetuer adipiscing elit}
\blindtext[2]
\end{document}

A: think I found a good solution in this thread

\documentclass[
fontsize=12pt,
twoside,
a4paper,
parskip=half,
ngerman,
headings=big]
{scrreprt}

\usepackage[english,german]{babel}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{blindtext}
\usepackage{etoolbox}

\DeclareMathAlphabet\EuRoman{U}{eur}{m}{n}
\SetMathAlphabet\EuRoman{bold}{U}{eur}{b}{n}
\newcommand{\eurom}{\EuRoman}

% Define own Chapter style
% Pretty chapter pages
%------------------------------------------
\definecolor{nicered}{rgb}{.647,.129,.149}
\definecolor{gray}{gray}{0.55}
\usepackage{soul}
\usepackage{pdfpages}
\usepackage{varwidth}
\usepackage[calcwidth,explicit]{titlesec}

%\makeatletter
%\newsavebox{\feline@chapter}
%\newcommand\feline@chapter@marker[1][4cm]{%
%   \sbox\feline@chapter{%
%       \resizebox{!}{#1}{\fboxsep=-0pt%\eurom{A}
%           \colorbox{white}{\color{black}$\eurom{\thechapter}$}}}%
%%      \rotatebox{90}{%
%%          \resizebox{%
%%              \heightof{\usebox{\feline@chapter}}+\depthof{\usebox{\feline@chapter}}}%
%%          {!}{\scshape\so\@chapapp}}\hspace{.4mm}%Abstand zum Wort Kapitel
%       \raisebox{\depthof{\usebox{\feline@chapter}}}{\usebox{\feline@chapter}}%
%   }
%
%
%           \newcommand\feline@chm[1][4cm]{%
%               \sbox\feline@chapter{\feline@chapter@marker[#1]}%
%               \makebox[0pt][l]{% aka \rlap
%                   \makebox[1cm][r]{\usebox\feline@chapter}%
%               }
%           }
%
%       \renewcommand*{\chapterformat}{%
%           \hspace{\leftmargin} \feline@chm[1.61cm] % Height of the colored box
%           \hspace{0.3cm}%Abstand zur Colorbox
%       }
%
%\patchcmd{\@@makechapterhead}
%{\usekomafont{chapter}{#1}}
%{\parbox[b]{\dimexpr\textwidth-4cm\relax}{\raggedright\usekomafont{chapter}{#1}}}
%{\typeout{great}}
%{\typeout{too bad}}
%\makeatother
%%------------------------------------------

\newsavebox\mybox

\newlength\mylen
\newlength\titlewd
\newlength\ftitlewd
\newlength\titleboxwd
\setlength\mylen{3pc}
\setlength\titleboxwd{\dimexpr\textwidth-\mylen\relax}
\setlength\ftitlewd{\titleboxwd}

\newcommand\chapfont{\LARGE\bfseries\raggedleft}

\titleformat{\chapter}[hang]
{\chapfont\filleft}
{}{0pc}
{%
    \begin{lrbox}{\mybox}%
        \begin{varwidth}[t]{\titleboxwd}%
            \chapfont#1%
        \end{varwidth}%
    \end{lrbox}%
    \settowidth\titlewd{\usebox\mybox}%
    \ifdim\titlewd<\titleboxwd%
    \global\setlength\ftitlewd{\titlewd}%
    \fi%
    \parbox[t]{\ftitlewd}{\usebox\mybox}%
    \makebox[0pt][l]{\parbox[b]{4pc}{\hfill\scalebox{3}{\textcolor{gray}{$\eurom{\thechapter}$}}}}%
}%\color{black}$\eurom{\thechapter}$
[\vskip-1.4ex{\makebox[0pt][l]{%
        \hspace*{-\ftitlewd}\rule{\dimexpr\ftitlewd+4pc\relax}{1.5pt}}}%
]
\titleformat{name=\chapter,numberless}[hang]
{\chapfont\filleft}
{}{0pc}
{%
    \begin{lrbox}{\mybox}%
        \begin{varwidth}[t]{\titleboxwd}%
            \chapfont#1%
        \end{varwidth}%
    \end{lrbox}%
    \settowidth\titlewd{\usebox\mybox}%
    \ifdim\titlewd<\titleboxwd%
    \global\setlength\ftitlewd{\titlewd}%
    \fi%
    \parbox[t]{\ftitlewd}{\usebox\mybox}%
}
[\vskip-1.4ex{\makebox[0pt][l]{%
        \hspace*{-\ftitlewd}\rule{\dimexpr\ftitlewd+4pc\relax}{1.5pt}}}%
]
\titlespacing*{\chapter}
{1\mylen}{50pt}{40pt}

\begin{document}

\chapter{Lorem ipsum dolor sit amet, consectetuer adipiscing elit}
         \blindtext[2]

\end{document}


text:
Q: Image within a ng-repeat displayed in a row instead of in a column I'm using ng-repeat to display some images. I think this is more of a CSS issue, but I'm not sure.

How do I display them in row rather than in column (there is no CSS style assigned to them atm)?

A: You are using div tag as container which is block element. Thats why they are coming in column


text:
Q: Stubbing window.location.href with Sinon I am trying to test some client-side code and for that I need to stub the value of window.location.href property using Mocha/Sinon.
What I have tried so far (using this example):
describe('Logger', () => {
    it('should compose a Log', () => {
        var stub = sinon.stub(window.location, 'href', 'http://www.foo.com');
    });
});

The runner displays the following error:

TypeError: Custom stub should be a function or a property descriptor

Changing the test code to:
describe('Logger', () => {
    it('should compose a Log', () => {
        var stub = sinon.stub(window.location, 'href', {
            value: 'foo'
        });
    });
});

Which yields this error:

TypeError: Attempted to wrap string property href as function

Passing a function as third argument to sinon.stub doesn't work either.
Is there a way to provide a fake window.location.href string, also avoiding redirection (since I'm testing in the browser)?

A: You need to use global to mock the window object for your test in beforeEach or it
e.g.
it('should compose a Log', () => {
   global.window = {
       location: {
           href: {
               value: 'foo'
           }
       }
   }
  //.... call the funciton
});

A: Stubs cannot replace attributes, only functions.
The error thrown reinforces this:

TypeError: Custom stub should be a function or a property descriptor

From the documentation:

When to use stubs?
Use a stub when you want to:

*

*Control a method's behavior from a test to force the code down a specific path. Examples include forcing a method to throw an error in order to test error handling.

*When you want to prevent a specific method from being called directly (possibly because it triggers undesired behavior, such as a XMLHttpRequest or similar).

http://sinonjs.org/releases/v2.0.0/stubs/

Possible solution
While many builtin objects can be replaced (for testing) some can't. For those attributes you could create facade objects which you then have to use in your code and being able to replace them in tests.
For example:
var loc = {

    setLocationHref: function(newHref) {
        window.location.href = newHref;
    },

    getLocationHref: function() {
        return window.location.href;
    }

};

Usage:
loc.setLocationHref('http://acme.com');

You can then in your test write
var stub = sinon.stub(loc, 'setLocationHref').returns('http://www.foo.com');

Note the chained returns() call. There was another error in your code: the third argument has to be a function, not value on another type. It's a callback, not what the attribute should return.
See the source code of stub()

A: Use window.location.assign(url) instead of overwriting the value of window.location. Then you can just stub the assign method on the window.location object.
http://www.w3schools.com/jsref/met_loc_assign.asp

UPDATE: I tested this in a headless browser, but it may not work if you run your tests in Chrome. See @try-catch-finally's response.


text: Q: How can I detect whether a Linux kernel has wireless (wlan) support Is it possible for a program (C/C++) to detect the existence of wireless support in the Linux kernel without looking in procfs (e.g. /proc/net/wireless) or sysfs ? Maybe via a netlink socket?


text:
Q: Custom Scaling Function for ListDensityPlot not working I'm attempting to plot a data set with values that span multiple orders of magnitude, both positive and negative. I would like to use a logarithmic scaling to accurately capture this order of magnitude change, but needed to define a custom function to deal with the negative values. I've included the scaling function I use (aL) and its inverse (aE) as well as equivalent code
xR=Table[(Exp[0.06225 i]-1),{i,1,150}];
xt= Table[0.5 i,{i,1,500}];
Lt=Length[xt];LR=Length[xR];
Do[tdata[j] = Sort[Table[RandomReal[{-5, 5}]*10^RandomInteger[{5, 50}], {i, 1, LR}]], {j, 1, Lt}];
Pdat = Flatten[Table[{xt[[j]], xR[[z]], tdata[j][[z]]}, {j, 1, Lt}, {z, 1, LR}], 1];
aL = Sign[#] Log[1 + Abs[#]] &;
aE = Sign[#] (Exp[Abs[#]] - 1) &;
ListDensityPlot[Pdat, ColorFunction -> "BlueGreenYellow", PlotLegends -> True, ScalingFunctions -> {None, "Log", {aL, aE}}]

The plot this creates doesn't look quite right, and the plot legend is a blank bar. I get the following error message:

Coordinate {Indeterminate, Indeterminate} should be a pair of numbers, or a Scaled or Offset form.

Thanks in advance


text: Q: Generate integer numbers with mean and variance How can I sample (integer numbers) from a t-distribution in R when I want to specify the degrees of freedom (df), the mean and variance? For example, how would I sample from a t-distribution with 8 df, mean = 4, and variance = 16?


text:
Q: Python create new column with top values (%) using other's column values I could not find function to get top n% automatically, so I sorted largest and smallest values and calculated numbers to make top 25% and min 25% ranges. What I want to do is to create a flag in new column saying that let's say this customer is in top 25% by revenue.
from heapq import nsmallest
top_max = avg_cust_data.nlargest(10806, ['user_spendings'])
top_min = avg_cust_data.nsmallest(10806, ['user_spendings'])

avg_cust_data['spendings_flag'] = np.where(avg_cust_data['user_spendings'] = top_max, 'Top Max',
                                  np.where(avg_cust_data['user_spendings'] = top_min, 'Top Min', 'AVG'))

A: You can use:
np.random.seed(100)
avg_cust_data = pd.DataFrame(np.random.random((40,1)), columns=['user_spendings'])
print (avg_cust_data)

top_max = avg_cust_data['user_spendings'].nlargest(10)
top_min = avg_cust_data['user_spendings'].nsmallest(10)

avg_cust_data['spendings_flag'] =
np.where(avg_cust_data.index.isin(top_max.index) , 'Top Max',
np.where(avg_cust_data.index.isin(top_min.index), 'Top Min', 'AVG'))

Another solution:
df1 = avg_cust_data.describe()
top_max_treshold = df1.loc['25%', 'user_spendings']
top_min_treshold = df1.loc['75%', 'user_spendings']
print (top_max_treshold)

avg_cust_data = avg_cust_data.sort_values('user_spendings')
avg_cust_data['spendings_flag1'] =
np.where(avg_cust_data['user_spendings'] <= top_max_treshold , 'Top Min',
np.where(avg_cust_data['user_spendings'] >= top_min_treshold, 'Top Max', 'AVG'))

print (avg_cust_data)

A: use pd.qcut
np.random.seed([3,1415])
avg_cust_data = pd.DataFrame(np.random.random((16,1)), columns=['user_spendings'])
avg_cust_data['quartiles'] = pd.qcut(
    avg_cust_data.user_spendings, 4,
    ['Quartile %s' %i for i in range(1, 5)]
)
avg_cust_data

You can even customize the bin edges by percentile and the corresponding labels
np.random.seed([3,1415])
avg_cust_data = pd.DataFrame(np.random.random((16,1)), columns=['user_spendings'])
avg_cust_data['quartiles'] = pd.qcut(
    avg_cust_data.user_spendings, [0., .25, .75, 1.],
    ['Bottom 25%', 'Middle', 'Top 25%']
)
avg_cust_data


text:
Q: This element is causing an element to overflow in Firefox I don't use Bootstrap or reset.css/reboot.css, I am trying to built a website with generic css.
I am doing pretty basic things but I get "This element is causing an element to overflow" literally everywhere. I haven't done layouts without any css framework for quite some time and I can not find anything about this issue. Even a br is causing an overflow! What is this? I don't see any scorlls and everything looks just like I expect. This message is just annoying.

I inspected a little bit more and discovered that images are causing this. But I have
.img-responsive, .responsive {
    height: auto;
    max-width: 100%;
}
.img-thumbnail, .thumbnail {
    padding: 0.25rem;
    background-color: white;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    box-sizing: border-box;
}

And if I delete this image, overflow message will go away for a few elements below. Can anybody tell me what's going on?

A: This will help.
html {
    width: 100%;
}

A: From MDN:

A scroll container is created by applying overflow: scroll to a container, or overflow: auto when there is enough content to cause overflow. The Firefox DevTools make it easy to discover both scrollable elements and any elements that are causing overflow.

In the HTML Pane, a scrollable element has the scroll badge next to it...

You can toggle the scroll badge to highlight elements causing an overflow, expanding nodes as needed to make the nodes visible...

You will also see an overflow badge next to the node causing the overflow.

So, if the container has content that is overflowing, it'll be marked with overflow, as you've noticed. Either adjust the content to not overflow, or adjust the container itself to allow for the content without overflowing. The DevTools badges you've noted can be used to identify which items are overflowing which container.

A: I suggest to create a reset in html
/* ------------ Reset CSS ------------ */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  width: 100vw;
  height: 100vh;
}


text:
Q: Getting Maven to Recognize Local Docker Containers I'm downloaded my company's code repositories to create a local development environment. We're using Docker containers. I'm running a Mac using the Monterey OS with zsh. Plus, we're using maven and I have 3.8.4 installed on my machine.
I cannot get maven to recognize my local repository. I goes to the network repository that I downloaded from and can't find it and gives errors.
At this point, I've done quite a few things hoping they'll fix the problem, so far no luck. I added  C:/Users/mydirectory/.m2/repository to my settings.xml in my maven repository directory.
I can't remember some of the other things I've checked and changed. Yet I can't get maven to use my local downloads. It seems to build the parent but nothing else, and gives messages that it can't resolve and it is definitely looking at the network when it gives me the errors.
It says the POM is missing for the network items. I do have my POM in my parent directory. As a subdirectory, I have my docker-scripts. I have been just manually running the commands, at this point, trying to figure out where my issue is at.
Any suggestions? I want to just use direct path as much as possible, hoping that forces most commands to go where I want them to.

A: After spending way too much time looking at this, had overlooked a typo in a path that I just noticed. Now, it's working.


text:
Q: How to flatten JSON object to an array using Mapping Data Flow? I have the following JSON file
{
    "totalOrderCount": 5,
    "ordersPerPage": 2,
    "orders": {
        "1235": {
            "orderId": 1235,
            "item": "Name 1",
            "price": 10
        },
        "5434": {
            "orderId": 5434,
            "item": "Name 2",
            "price": 12
        }
    }
}

I want to convert orders from objects with key(orderId), values to an array of values. Any ideas on which transformation should I use in Azure Mapping Data Flow?
As an end result, I want to have each order in a separate row so I can process it further in Data Flow.
I tried to follow this link with no success.


text:
Q: MacBook Pro repeatedly freezes, often with odd display glitches I have an older, 2007 15-inch MacBook Pro (model identifier MacBookPro3,1)  which has begun freezing repeatedly.
If I boot into Single User Mode it stays operative, however I've begun to get graphic glitches here too:

Booting to the Mountain Lion recovery partition, a disc, or any other graphic interface I get a freezing hang. This is often before the machine has booted completely.
At other times it will repeatedly reboot.
I have reset SMC and PRAM, and run fsck -fy on the drive.
I should also note that the machine generally kicks up its fan pretty quickly and runs very hot, even in Single User Mode, so I am suspecting overheating, perhaps brought on by the video demands?
Does anyone else have a guess at this and/or another diagnostic step?

A: The symptoms you describe could all be explained by a failing GPU system but before seeking a hardware repair (or quote), I would try reinstalling a clean version of OS X - perhaps the original version that shipped with that Mac to ensure that the hotness and slowness isn't because of added load the new OS has provided and actually something relating to hardware cooling or heat generation.
Your picture is very telling as well.
The three things that hardware could fail are:

*

*LCD panel and cabling

*GPU itself

*VRAM

The patterns you show in single user mode could either be software or hardware. If it's hardware, they will get worse over time (perhaps dramatically worse) and we've already covered the software angle. Usually when the hardware is faulty, you can get poor graphics in single user mode or the boot selection screen - so you might be right it's overheating / the hardware starting to fail.


text:
Q: Multithreading - Not working simultaneous I want to implement a multithread system (two threads will do) and I followed a tutorial
    Thread t1 = new Thread(new ThreadStart(threadA));
    Thread t2 = new Thread(new ThreadStart(threadB));
    t1.Start();
    t2.Start();

The output is unexpected for me as it shows:
"threadA"
"threadA"
"threadA"
"threadB"
"threadB"
"threadB".Is something wrong with my code? Many thanks.

A: The short of it is that threads execute when the CLR and OS schedule them to do so, based on a lot of implementation details that vary from OS to OS and CPU to CPU.
Use of the Thread class does avoid the ThreadPool, which is most of the CLR's level of control over thread scheduling, but the OS kernel still decides when threads run. In your case, where each Thread is simply outputting three lines to the console, it's totally expected that one thread would finish before the OS even kicks off the other one.
HOWEVER, you can never guarantee the order in which threads will run. So, if you were to loop this code (with Join() statements) and run it 100 times, you may see several different permutations of "threadA" and "threadB" displayed as the threads are scheduled at different times by the OS. If two EUs are available at EXACTLY the same time there will be significant overlap; if threadA is somehow considered less important than threadB, threadB may execute in its entirety before threadA even begins.

A: This is happening because in the time that it takes for you to go from t1.Start() to t2.Start(), your t1 has already completed.
Try something like this if you want to see your code alternate a little
Thread t1 = new Thread(
    new ThreadStart(()=>
    {
        for(int i = 0; i < 3; i++)
        {
            System.Console.WriteLine("ThreadA");
            Thread.Sleep(3000)
        }
    }));
Thread t2 = new Thread(
    new ThreadStart(()=>
    {
        for(int i = 0; i < 3; i++)
        {
            System.Console.WriteLine("ThreadB");
            Thread.Sleep(1000)
        }
    }));
t1.Start();
t2.Start();

It should print something like this:
ThreadA
ThreadB
ThreadB
ThreadA
ThreadB
ThreadA

However, this just shows that you cannot guarantee any order when it comes to threading.


text:
Q: Highstock Single Line Series Data format I want to use Highstock  Single Line series chart but there is no documentation about the data format. The data given there is in this format:
/* Jul 2008 */
[1215388800000,25.02],
[1215475200000,25.65],
[1215561600000,24.89],
[1215648000000,25.23],
[1215734400000,24.65],
[1215993600000,24.84],
[1216080000000,24.23],
[1216166400000,24.69],
[1216252800000,24.54],
[1216339200000,23.59],
[1216598400000,23.76],
[1216684800000,23.15],
[1216771200000,23.75],
[1216857600000,22.72],
[1216944000000,23.16],
[1217203200000,22.06],
[1217289600000,22.44],
[1217376000000,22.84],
[1217462400000,22.71],

I am using Django. How do I convert the timestamp fetched fro MySQL 'TIMESTAMP' datatype to this format?


text:
Q: How to solve HTML5 validation error on fb-like box? How to solve this HTML 5 validation error related to Facebook like button?
Here is the text from validation engine:

Line 3170, column 261: Element name fb:like-box cannot be represented as XML 1.0.
…rue" border_color="" stream="false" header="false" height="260" ></fb:like-box>

Here is the code on Line 3170:

<fb:like-box href="http://www.facebook.com/fburlhere" width="250" show_faces="true" border_color="" stream="false" header="false" height="260" ></fb:like-box>

Just after this error, there is also another error which reads:

Element fb:like-box not allowed as child of element div in this context. (Suppressing further errors from this subtree.)

referring to the same line number.

A: The markup are dynamically placed/generated from Facebook itself. You cannot control them, the way you want. But there is a HTML5 version of the Like Box, you can use instead.
When you are generating the code for the like-box. You will get an option like
[Source]


text:
Q: Pip Install SSL Issue I am getting the following SSL issue when running pip install:
python -m pip install zeep
Collecting zeep
  Retrying (Retry(total=4, connect=None, read=None, redirect=None,
status=None)) after connection broken by 'SSLError(SSLError("bad handshake:
Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify
failed')],)",),)': /simple/zeep/

A: I was able to resolve the issue by using the following:
python -m pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --index-url=https://pypi.org/simple/ zeep

A: If using windows then make sure the below three paths are added in Windows environment variable :

*

*....\Anaconda\Library\bin

*....\Anaconda\Scripts

*....\Anaconda

If not using Anaconda then in place of Anaconda the path where python is installed.


text:
Q: Motor monitoring over temporary connection I have an application where I need to determine whether a DC motor that is used as a vibrator is operating correctly. Normally this would be a straightforward problem that could be solved using an accelerometer. The problem with using an accelerometer for my application is the motor is mounted to a mobile structure that is passed down an assembly line like setup. All connections to the mobile assembly and motor need to be temporary. They also need to be made in an automated fashion (no human in the loop).
The motor power connection is a little simpler, the current setup uses copper plates and the weight of the mobile structure to make the connection. Would it be possible to send dynamic signals over a similar type of connection? On paper it looks like it would work, but it seems like noise might be an issue. There is also the fact that all of the connections are temporary, so there may be inconsistencies that would be hard to resolve.
Can anyone think of a better way to determine the health of the motor that would work in this type of an application?

A: Depending on the weight of the structure, you could have an arrangement of pogo pins to connect a data link; this works fine as long as the device is firmly enough connected. I'd suggest a differential type of data link like RS485 or CAN, although if the connection is short and secure you should be able to get I2C to work.
Obviously if the thing is vibrating you have to make sure it's not vibrating enough to break the spring-loaded pogo connection. And the pins have to align mechanically - conical or sloped guide surfaces can do this. Normally you'd clip it in place; magnets may also work for you.

A: A lot of the other answers are suggesting digital communication across the link, which is a potential option, but it does require more hardware, and something to handle the communication on the mobile structure.
Something that may be a little simpler:
Measure the resistance of the total motor circuit after each new connection is made (prior to turning the motor on). By knowing that resistance and the armature current I know the voltage drop across each connection point and the armature coil of the motor. I can then calculate the speed of the motor using it's relationship with the EMF voltage which gives me the following equation (derived from \$V_{in}=E_a+Ia*R_t\$):
\$\omega_m=(V_{in} - I_a*R_t) / K_m\$
\$w_m\$ = motor speed
\$V_in\$ = input voltage
\$I_a\$ = armature current
\$R_t\$ = total circuit resistance
\$K_m\$ = motor magnetic constant.
The above method would at least be able to get a rough estimate of the motor speed, which under drastic fault condition would most likely change. It can also all be done from the static side of the connection. The one thing that it doesn't capture is if there is anything dynamic about the connection while the motor is running (the mobile structure hopping)

A: Assumptions:

*

*The device under test is expected to vibrate within a given range of amplitudes and frequencies

*The device has some reflective surface visible on the assembly line, while it is on the powered copper plates.

While the method of measuring current consumption by the DUT, mentioned in other posts, is perhaps the least complicated solution, here is an alternative proposal for a non-contact method.

*

*Fix a low intensity laser to be incident upon any reflective surface of the device when the device moves into position on the copper plates on the assembly line. Angle the laser to strike the surface at an incline. A 1 mW laser diode will be more than sufficient, any visible laser color will do.

*Fix a PIN photodiode, phototransistor or other photosensor on the reflection path of the laser, aligning it by sight.

*Sense the incident laser beam via the photodiode, and capture both frequency and amplitude variation.

Basically, as the DUT vibrates, so will the reflected laser beam. This will cause its intensity as sensed by the PIN diode / other photosensor to vary with the intensity of vibration, and at the frequency of vibration.
This method has the advantage of being easily set up, causes and requires no change to the electrical behavior of the DUT, and does not add either physical weight or power load to the DUT. Hence it will measure the behavior of the vibrating motor / device without actually modifying the vibration in any discernible way.
No contacts to get oxidized or require cleaning, which is an added benefit in a mass production environment.

A: The are lots of ways to provide data over a temporary electrical link, or over some other type of link. Some ideas:

*

*use a property of the current drawn by the motor, as user25093 suggests

*modulate some HF signal onto the motor power lines

*use an RF modue, RFM73 or NRF24L01 or similar

*use IR

*use ultrasound

*use extra connections for a data line

The last option would probably my least favorite choice, because it adds hardware and is likely to be very unreliable.

A: Here's my suggestion. Steal a little power from the 12V feed to the motor on the sled. This can be used to create a stable d.c. supply on the sled for electronics to process the accelerometer. I say accelerometer but if you change the sensor that detects/measures vibration, this method will be able to cope with changes.
Whatever the sensor is it should be digitized with an ADC. You are going to need a small microprocessor on board so that the "reading" is substantiated with enough bits to provide a highly secure and relaible data information package.
How much data do you need to transmit? Quite possibly, very little because the micro could decide if the vibrations are operating within reasonable limits and basically you are transmitting one very secure bit = "good" or "bad".
Frequency modulation should provide a decent means of getting data through the sled contacts and I believe that you should get at least one decent data packet transmission at least every tenth of a second and quite possibly hundreds a second should that be necessary.
So far, the sled steals some power from the contacts (it could even have a rechargeable battery should the "system" require set-up tests), an ADC connected to the vibration transducer feeds a micro, the micro decides if the data = good or bad and this single quality bit is made secure with a large error check code. This "packet" feeds a low power FM modulator and this signal is superimposed on the 12V that feeds the motor.
Additions. The motor shouldn't conduct the FM signal so a DC pass/ AC block circuit needs to be in series with the motor. A similar circuit is needed at the power feed circuit off the sled. Data can be collected and demodulated with a fairly simple circuit and this demodulated data checked for integrity and a relay would indicate "good vibrations" (anyone a fan of the Beach Boys?) or bad vibrations.
More additions. The raw data can also be transmitted as well as the "refined" good/bad data.
What are the chances of it working? I'm certain I could get it working and the OP has to decide whether it's worth investing in this development because it'll take at least 1 man month to design and probably cost £2k in bits and pieces. Is it worth it? Is there a wider requirement for taking information off the sled that can "reduce" the cost impact for just this one requirement?


text:
Q: User secrets not available to .net core app hosted in windows service I am attempting to access user secrets in a .Net Core Windows Service.  The service itself is running under a service account, and I have added a user secret for the service user.
When running the application as a straightforward console application, the user secret can be accessed.  However, when running the application as a windows service, the setting cannot be read.  There is no error - just the value is not obtained.  The service is running under the same user account as the logged in user - and the secret can be obtained when running the console application.
When I add the secrets.json file to the hosted executable's location and read it in using the AddJsonFile method then the value can be read.  Here is a code snippet:
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        builder.AddEnvironmentVariables();

        // does not work as a service
        builder.AddUserSecrets("TestUserSecrets");

        // works as a service when secrets.json is copied to exe directory
        // builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "Secrets.json"));

        Configuration = builder.Build();

        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();
    }

    public IConfigurationRoot Configuration { get; set; }

    public void Configure(IApplicationBuilder app, ILoggerFactory logFactory)
    {
        // attempt to obtain secret config value
        string secret = Configuration["Secret"];

Is there an issue with the windows service getting access to the user secret (in the secret.json file)?
Is the intention just to use user secrets for development, and therefore using user secrets in a windows service is just not going to work?

A:
Firstly, you should take a look at the documentation about Accessing user secrets via configuration
The documentation will help you to understand how to work with user secrets properly.

You noted that
builder.AddUserSecrets("TestUserSecrets");

does not work properly... take a look at the code block below to see how I have adapted your code to meet the documentation:
public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddUserSecrets<Startup>(); // <-- note here
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
    string testSecret = Configuration["Secret"];
}

How the Secret Manager tool works
The Secret Manager tool abstracts away the implementation details, such as where and how the values are stored. You can use the tool without knowing these implementation details. In the current version, the values are stored in a JSON configuration file in the user profile directory:

*

*Windows: %APPDATA%\microsoft\UserSecrets\<userSecretsId>\secrets.json

*Linux: ~/.microsoft/usersecrets/<userSecretsId>/secrets.json

*Mac: ~/.microsoft/usersecrets/<userSecretsId>/secrets.json

The value of userSecretsId comes from the value specified in .csproj file.
You should not write code that depends on the location or format of the data saved with the Secret Manager tool, as these implementation details might change. For example, the secret values are currently not encrypted today, but could be someday.

Alternative Solution
I do run into the same situation as you quite often trying to use the Secret Manager tool (is not for everyone, nor every situation).
My typical solution is to do what you already noted:
var builder = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
    .AddEnvironmentVariables();

try
{
    string secretsFile = Path.GetFullPath("../secrets.json");
    builder.AddJsonFile(secretsFile , optional: true, reloadOnChange: true);
}
catch (UnauthorizedAccessException) { } // this resolves an error from hosts trying to go
                                        // below the root.

As you can see, it will attempt to grab the secrets.json file from the provided path. However, you should note that in the event you host the application, you are most likely going to store them on to the environment variables, or otherwise in which case this case is already fine. Otherwise, just adapt the code to meet your specific environment.
Note:
string secretsFile = Path.GetFullPath("../secrets.json");

I intentionally popped out the secrets.json below the root directory here, since we don't want to accidentally put our secrets.json into the repository if you are using any source control.

A: My alternative workaround solution is to use an option which will have IConfiguration type property. In constructor call IOptions instead of Iconfiguration.

MyOptions.cs

public class MyOptions
{
    public IConfiguration Configuration { get; set; }
}

Startup.cs

public class Startup
        {
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

                if (env.IsDevelopment())
                {
                    builder.AddUserSecrets<Startup>();
                }
                else
                {
                    builder.AddEnvironmentVariables();
                }

                Configuration = builder.Build();
            }

            public IConfiguration Configuration { get; }

            public void ConfigureServices(IServiceCollection services)
            {
                services.Configure<MyOptions>(opt =>
                {
                    opt.Configuration = Configuration;
                });

                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            }
        }

And access it like

using Microsoft.Extensions.Options;
public class MyController
    {
        readonly IConfiguration _configuration;
        public MyController(IOptions<MyOptions> options)
        {
            _configuration = options.Value.Configuration;
        }

        public void Test()
        {
            Console.Log(_configuration["Section:Value"]);
        }
    }


text:
Q: What is the parameter 'k' in multiple feedback filter design? In this tutorial from Analog devices, what is 'k'?  The unit seems to be 1/ohm. Is it some arbitrary number to help with finding the R and C values?

A:
In this tutorial from Analog devices, what is 'k'?

The 24th instance of k is: -
$$k = 2 π F_0 C5$$
On page 2. Also on page 2 is suggests k is: -
$$k = 2 π F_0 C1$$
But this is for a different circuit.
CTRL-F for "find" then enter "k"


text:
Q: how to notmapped or ignore propery of inherited class? So I have a brand poco class as below.
 [Table("Brand")]
public partial class Brand
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

    public int BrandId { get; set; }

    [StringLength(100)]
    public string Name { get; set; }

}
I need to extended with baseEntity as shown below. I created a partial class in order to prevent re-creating the class shouldnt override it.
public partial class Brand : BaseEntity
{

}

BaseEntity class has some static methods and a Id property as shown below.
When I debug my application it complains that Id is not a valid column.
   public abstract partial class BaseEntity
    {
        public int Id { get; set; }
}

It is clear that I need to ignore or sign as NotMapped but I dont want to change BaseEntity and I dont want to change my DbContext class (re-creating can override)
I can create a partial class of Dbcontext as shown below and use ignore. But It wont allow me to use OnModelCreating 2 times.
How can I achieve this task without making any change in the BaseEntity Class?
public partial class MyDBContext : DbContext
{

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Brand>().Ignore(t => t.Id);

    }
}


text:
Q: Foreign keys not "working"? I am trying to create a system for a newspaper for a school project, and this is part of that code. For some reason i am getting "Error Code: 1215. Cannot add foreign key constraint"
-- MySQL Workbench Forward Engineering

SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

-- -----------------------------------------------------
-- Schema nyheterhiof
-- -----------------------------------------------------

-- -----------------------------------------------------
-- Schema nyheterhiof
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS nyheterhiof DEFAULT CHARACTER SET utf8 ;
USE nyheterhiof ;

-- -----------------------------------------------------
-- Table nyheterhiof.newspapers
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS nyheterhiof.newspapers (
  newspaper_id INT(11) NOT NULL,
  newspaper_name VARCHAR(45) NULL,
  newspaper_city VARCHAR(45) NULL,
  PRIMARY KEY (newspaper_id),
  UNIQUE INDEX newspaper_id_UNIQUE (newspaper_id ASC))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table nyheterhiof.newspaper_Issues
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS nyheterhiof.newspaper_issues (
  newspaper_issiue_id INT(11) NOT NULL,
  newspaper_id VARCHAR(45) NOT NULL,
  publication_date DATE NOT NULL,
  comment VARCHAR(200) NULL,
  PRIMARY KEY (newspaper_issiue_id),
  UNIQUE INDEX newspaper_issiue_id_UNIQUE (newspaper_issiue_id ASC),
  INDEX fk_newspaper_Issues_newspapers1_idx (newspaper_id ASC),
  CONSTRAINT fk_newspaper_Issues_newspapers1
    FOREIGN KEY (newspaper_id)
    REFERENCES newspapers (newspaper_id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

I have tried moving the FK to a alter table statment, I have tried adding indexes to newspaper_id in "newspaper_issiues".

A: You've specified
CREATE TABLE IF NOT EXISTS nyheterhiof.newspapers (
  newspaper_id INT(11) NOT NULL,

and
CREATE TABLE IF NOT EXISTS nyheterhiof.newspaper_issues (
  ...
  newspaper_id VARCHAR(45) NOT NULL,

This is the problem. The columns at both ends of a foreign key constraint MUST match in type and width.
Redefine newspaper_issues.newspaper_id as INT and you'll be good to go.


text:
Q: a simple mysql example of importing a file + can't get to work I am having trouuble importing a file into a mysql db as it appears in the file. So I thought I'd ask a question here with a very basic example. Can anyone help me to get this to work?
I have the following file:
$cat NIS.txt
00000,1284
00001,2081

Now I go into mysql with mysql - username -p and I create a table(note this has to be created before you can add the rows with the LOAD DATA INFILE command)
CREATE TABLE IF NOT EXISTS nisC (
  id int(11) NOT NULL AUTO_INCREMENT COMMENT 'primary key',
  field1 int NOT NULL COMMENT 'field1',
  field2 int NOT NULL COMMENT 'field2',
  PRIMARY KEY (id)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;

Then I can add the rows with LOAD DATA LOCAL INFILE
(note LOCAL is important as the file resides in the LOCAL directory?)
LOAD DATA LOCAL INFILE 'NIS.txt' INTO TABLE nisC (field1, field2);
this however gives me warnings
mysql> LOAD DATA LOCAL INFILE 'NIS.txt' INTO TABLE nisC (field1, field2);
Query OK, 2 rows affected, 4 warnings (0.00 sec)
Records: 2  Deleted: 0  Skipped: 0  Warnings: 4

And the table does not look right when I do a select:
mysql> select * from nisC;
+----+--------+--------+
| id | field1 | field2 |
+----+--------+--------+
|  1 |      0 |      0 |
|  2 |      1 |      0 |
+----+--------+--------+
2 rows in set (0.00 sec)

Can someone explain what I am doing wrong? Why are the values in the table not the same as they are in the file?
EDIT1 - Complete Solution/Output
NOTE: I have to login to mysql like this mysql -u username -p --local-infile=1 for the LOAD DATA command to work.
mysql> CREATE TABLE IF NOT EXISTS nisC (
    ->   id int(11) AUTO_INCREMENT COMMENT 'primary key',
    ->   field1 int NOT NULL COMMENT 'field1',
    ->   field2 int NOT NULL COMMENT 'field2',
    ->   PRIMARY KEY (id)
    -> ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 COMMENT='datatable demo table' AUTO_INCREMENT=64 ;
Query OK, 0 rows affected (0.01 sec)

mysql>
mysql>
mysql>
mysql> LOAD DATA LOCAL INFILE 'NIS.txt' INTO TABLE nisC
    -> FIELDS TERMINATED BY ','
    -> LINES TERMINATED BY '\n'
    -> (field1, field2)
    -> SET id = NULL;
Query OK, 2 rows affected (0.01 sec)
Records: 2  Deleted: 0  Skipped: 0  Warnings: 0

mysql>
mysql>
mysql> select * from nisC;
+----+--------+--------+
| id | field1 | field2 |
+----+--------+--------+
| 64 |      0 |   1284 |
| 65 |      1 |   2081 |
+----+--------+--------+
2 rows in set (0.00 sec)

A: You need to set the delimeter in LOAD DATA so that MySQL knows it is reading CSV:
LOAD DATA LOCAL INFILE 'NIS.txt' INTO TABLE nisC
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, field2)
SET id = NULL;

By specifying field1 and field2 in the LOAD DATA command, MySQL will populate these two columns using the two columns of data in your CSV.  However, your table actually has a third id column.  In order to populate this you can instruct LOAD DATA to set it to NULL.  This will coax MySQL into assigning an auto incremented value.
You should change your column definition for id to make it nullable.  Then MySQL will automatically assign this id when you read in the file.
id int(11) AUTO_INCREMENT COMMENT 'primary key',


text:
Q: Mapping the "lower diagonal" of a tensor to a matrix, as a generalization of the extraction of the lower triangular part of a matrix into a vector Given a rank-4 tensor (each rank with dimension K), for example T(p,q,r,s), we can 1-to-1 map all the tensor elements into a matrix of dimension K^2 x K^2, for example M(i,j) in which the two first tensor indices p,q and the last two indices r,s are combined in a column major way:
i = p + K * q
j = r + K * s

Exploiting some (anti-)symmetries of the given tensor, for example T(p,q,r,s) = -T(q,p,r,s) = -T(p,q,s,r) = T(q,p,s,r) and T(p,q,r,s) = T(r,s,p,q), we would like to be able to construct a matrix H(m,n) that only contains the unique elements (i.e. those not related by the previously defined symmetries), such that p>q and r>s into the matrix H(m,n), which would then be of dimension K(K-1)/2 x K(K-1)/2.
How could we find an algorithm (or even better: how can we use the C++ library Eigen) to accomplish these index transformations? Furthermore, can we write down m and n algebraically in terms of p,q and r,s, like we can do in the case where we would want to extract the strict lower triangular matrix (no diagonal) into a vector?

A: For reference, given a square matrix Eigen::MatrixXd M (K,K), here is an algorithm that extracts the strict lower triangle of a given square matrix M into a vector m of size, using the C++ Eigen library:
    Eigen::VectorXd strictLowerTriangle(const Eigen::MatrixXd& M) {

    auto K = static_cast<size_t>(M.cols());  // the dimension of the matrix
    Eigen::VectorXd m = Eigen::VectorXd::Zero((K*(K-1)/2));  // strictly lower triangle has K(K-1)/2 parameters

    size_t vector_index = 0;
    for (size_t q = 0; q < K; q++) {  // "column major" ordering for, so we do p first, then q
        for (size_t p = q+1; p < K; p++) {
            m(vector_index) = M(p,q);
            vector_index++;
        }
    }

    return m;
}

We are able to extend this algorithm to the requested general case:
Eigen::MatrixXd strictLowerTriangle(const Eigen::Tensor<double, 4>& T) {

    auto K = static_cast<size_t> (dims[0]);

    Eigen::MatrixXd M (K*(K-1)/2, K*(K-1)/2);

    size_t row_index = 0;
    for (size_t j = 0; j < K; j++) {  // "column major" ordering for row_index<-i,j so we do j first, then i
        for (size_t i = j+1; i < K; i++) {  // in column major indices, columns are contiguous, so the first of two indices changes more rapidly
                                                  // require i > j

            size_t column_index = 0;
            for (size_t l = 0; l < K; l++) {  // "column major" ordering for column_index<-k,l so we do l first, then k
                for (size_t k = l+1; k < K; k++) {  // in column major indices, columns are contiguous, so the first of two indices changes more rapidly
                                                          // require l > k

                    M(row_index,column_index) = T(i,j,k,l);

                    column_index++;
                }
            }

            row_index++;
        }
    }

    return M;
}


text:
Q: How many CPUs are there in a dedicated m4.16xlarge instance I'm confused about the physical configurations I get from dedicated hosts. According to the instance type matrix, an m4.16xlarge instance is powered by (not sure how many) Intel Xeon E5-2686 v4 CPUs, so I imagine if I launch one of the dedicated instances, I'll get to use the entire E5-2686 CPUs, however many are there. Right?
But I'm confused now. The instance type matrix says that an m4.16xlarge instance has 64 vCPU's. But as according to Intel, an E5-2686 v4 has only 18 cores / 36 threads. What does this mean? Do they put two CPUs in an m4.16xlarge machine? Couldn't find any reference for this.

A: m4 are dual socket, see the table on this page (seems not updated to reflect the new size yet): https://aws.amazon.com/ec2/dedicated-hosts/pricing/
So the host should have 36 physical cores, 72 threads of which 64 threads can be used for ec2 instances.


text:
Q: As a prove and $f$ a differentiable function of two variables
As a prove and $f$ a differentiable function of two variables $u$ and $v$ and $u = x-y$ and $v = y-x$, then $z = f (x-y, y-x)$ satisfies the equation $$\frac{\partial z}{\partial x}+\frac{\partial z}{\partial y}=0$$

I thought of using the chain rule and my teacher said it would work well, but could not.

A: Let $f$ a differentiable function of two variables $u$ and $v$ and $u = x-y$ and $v = y-x$.
Suppose $z = f (x-y, y-x)$ then to show that the equation satisfies $$\frac{\partial z}{\partial x}+\frac{\partial z}{\partial y}=0$$.
Hint :
$$\frac{\partial z}{\partial x} = \frac{\partial f}{\partial u}. \frac{\partial u}{\partial x} + \frac{\partial f}{\partial v}. \frac{\partial v}{\partial x}$$
Work similarly for $$\frac{\partial z}{\partial y}$$.


text:
Q: Content-Disposition - an invalid character was found in the mail header: '[' I want to get filename from the url below. When parsing Content-Disposition header to extract the filename it throws an error System.FormatException: An invalid character was found in the mail header: '['. .The value of the header is like below. I don't want to replace these characters because the filename will be changed if I do. How can I fix it?
Content-Disposition: attachment; filename*=UTF-8''[Saglamindir.net] Internet Download Manager.rar
Url: https://www17.zippyshare.com/d/qS76ZdES/29289/%5bSaglamindir.net%5d%20Internet%20Download%20Manager.rar

My Code:
var cdHeader = response.Headers["Content-Disposition"];
if (!string.IsNullOrEmpty(cdHeader))
{
    var properFormat = Encoding.UTF8.GetString(Encoding.GetEncoding(1252).GetBytes(cdHeader));
    properFormat = HttpUtility.UrlDecode(properFormat);
    var disp = new ContentDisposition(properFormat);
    var temp = disp.FileName;
    return temp.ReplaceInvalidChars();
}

A: You can't use unescaped "[" or "]" here (they need percent-encoding). The relevant specs are RFC 6266 (Content-Disposition) and RFC 8187.


text:
Q: How to return DateTime in different timezone from Django Rest Framework serializer What is the pythonic way to return DateTimeField of some Django model using an arbitrary timezone in Django Rest Framework?
At the moment my view returns DateTime in UTC, because as far as I know Django stores timezone-aware datetimes as datetimes in UTC timezone.
Models:
class TimezoneMixin(models.Model):
    TIMEZONES = [(i, i) for i in country_timezones['ru']]

    timezone = models.CharField(choices=TIMEZONES, ...)

    class Meta:
        abstract = True

    def get_timezone(self):
        if self.timezone:
            return timezone(self.timezone)
        return get_current_timezone()

class Organization(TimezoneMixin, models.Model):
    ...

class Event(models.Model):
    organization = models.ForeignKey(Organization, ...)
    date_created = models.DateTimeField(auto_now_add=True, ...)
    ...

Serializer:
class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = Event
        fields = ('organization', 'date_created', ...)

In the ViewSet I populate data as follows
organization_id = ...  # Some logic to get required organization_id

data = {
    'date_created': timezone.now(), # django.utils.timezone
    'organization': organization_id,
    ...
}

serializer = EventSerializer(data=data)
if serializer.is_valid():
    serializer.save()
    response_data = serializer.data.copy()
    # Some logic to rename one of the keys in response data
    ...
    return Response(response_data, ...)  # rest_framework.response.Response

Even if I replace timezone.now() with something like timezone.now().astimezone(organization.get_timezone()) I still receive UTC DateTime in response.
Am I correct that it is not a good idea to parse date_created string from response_data, create a DateTime object from it, convert to different timezone and format as string again in the end of the view? What are the other ways?

A: You need localtime() to get the time in the current time zone since now() will always return times in UTC regardless of the value of TIME_ZONE.
You can pass an arbitrary timezone to localtime:
localtime(timezone='SOMETHING')

A: serializer uses default TIME_ZONE, which you set in settings.py file
If you want to set TIMEZONE for one field.
import pytz
class WeatherReportSerializer(serializers.ModelSerializer):
    DatetimeValue = serializers.DateTimeField(default_timezone=pytz.timezone('Asia/Kolkata'))

    class Meta:
        model = ...
        fields = [..., ..., ...]

A: I was able to get timestamp in arbitrary timezone without parsing datetime string because serializer provides access to saved instance. So below is my solution
response_data = serializer.data.copy()
# Some logic to rename one of the keys in response data
...
event_date_created_utc = serializer.instance.date_created
# Basically calls get_timezone on Organization instance and returns the result
organization_timezone = get_timezone_by_organization_id(organization_id)
response_data['date_created'] = timezone.localtime(event_date_created_utc,
                                                   timezone=organization_timezone).isoformat()
return Response(response_data, ...)  # rest_framework.response.Response

Thanks to Edgar R. Mondragón for mentioning localtime() and its usage.


text:
Q: Does a React.js app get entirely shipped to the browser on request? This is going to sound like a really dumb question but does the entire React app get shipped to the browser on first page load? Or is it shipped to the browser as-needed? If it is shipped as-needed then who decides what is needed when?
Let's say its a 3-pager. (e.g. /login, /users, /users/:userId).
I can probably just inspect the network calls or curl my server... but I consider that anecdotal and would like to get a more comprehensive idea.

A: This is not a problem specific to React, and is called choosing a bundling strategy, which translates to how you ship to the browser the resource files (js, css etc). In demand vs full preload vs a mix of the former ... It really depends on how you structured your app. For example, there are many apps which load the different parts of the application route based. This would be doing it in demand. There are pros / cons to the different approaches, and you should generally consider your bundle size, caching strategies etc.
I suggest you look at webpack, which is kind of today's standard for achieving this.


text:
Q: Block Element like  with `display: inline` inside  block correct? As specified here and debated here it is invalid to put a DIV tag inside a LABEL. What if, however, you make the element an inline element with the CSS rule display: inline?
My guess is that this won't change anything, because the spec does not mention CSS at all. I don't see however how this should go together with Web Components that allow me to build my very own form control just from DIVs with CSS styling and proper ARIA a11y declarations.

A: Correct, CSS is independent and have no influence on document validity. So that construct will be still invalid ( according to specification and according to w3c validator ).