text:
Q: Read PNG image from stream with 4 channels I'm working on a discord bot that accepts all kind of images for OCR purposes. When a user upload a PNG with 4 channels it goes wrong. By that I mean it read the image as almost 100% white, while the actual image is full of colours.
I've tried to convert it with cv2.COLOR_BGRA2BGR but this doesn't work. However in my pytest it does work. This is probably because I'm using cv2.imread in my pytest which is a bit different from my actual code.
Code (broken)

for a in supported_attachments:
  async with aiohttp.ClientSession() as session:
    async with session.get(a) as res:
      if res.status == 200:
        buffer = io.BytesIO(await res.read())
        arr = np.asarray(bytearray(buffer.read()), dtype=np.uint8)
        img = cv2.imdecode(arr, -1)
        if len(img.shape) > 2 and img.shape[2] == 4:
          print('convert')
          img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
          plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
          plt.show()
        images.append(img)

pytest (works)

image = cv2.imread('../tests/images/stats/english/kills_png.png',
cv2.COLOR_BGRA2BGR)

Any suggestions or idea's?

A: The flag cv2.COLOR_BGRA2BGR is for cv2.cvtColor() not for cv2.imread().
All the manifest constants for cv2.imread() start with cv2.IMREADxxx and are defined here.


text:
Q: MS Chart how to remove these unwanted circles when type is spine
I am using MSChart and type is spine. I generated a graph and its working.But there is some issue happens and graph marked as white. How can i fix that extra items. Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use or instantiate Sqlite Database Helper class instance inside a custom dapter class in Android? I am absolute beginner to Android. Now I am creating a tutorial project. In my project I am using ListView with custom adapter. But I created the custom adapter as a different and standalone file to make my activity clean. But when I create it in a different file, I cannot use my database helper class inside the custom adapter.
The problem is I  cannot pass the Activity context to the database helper class instance. In fragment, I can pass by calling this method.getActivity(). Then pass it to the constructor of my database helper class. How can I do the same thing in my custom adapter class?
This is my database helper class:
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "todo.db";
    private static final String TABLE_NAME = "task";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_DESCRIPTION = "description";
    private static final String COLUMN_DATE ="date";
    private static final String COLUMN_DONE = "done";
    private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+COLUMN_ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+COLUMN_DESCRIPTION+" TEXT,"+
    COLUMN_DATE+" DATE,"+COLUMN_DONE+" BOOLEAN)";
    SQLiteDatabase db;

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        this.db = db;
        db.execSQL(CREATE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
        db.execSQL(query);
        this.onCreate(db);
    }

    public  void insertTask(Task task)
    {
        db = getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_DESCRIPTION,task.getDescription());
        values.put(COLUMN_DATE,task.getDate());
        values.put(COLUMN_DONE, Boolean.FALSE.toString());
        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public ArrayList<Task> getAllTasks()
    {
        ArrayList<Task> items = new ArrayList<Task>();
        db = getReadableDatabase();
        String query = "SELECT * FROM "+TABLE_NAME;
        Cursor cursor = db.rawQuery(query,null);
        if(cursor.moveToFirst())
        {
            do{
                Task item = new Task();
                item.setId(cursor.getInt(0));
                item.setDescription(cursor.getString(1));
                item.setDate(cursor.getString(2));
                item.setDone(Boolean.valueOf(cursor.getString(3)));
                items.add(item);
            }
            while (cursor.moveToNext());
        }
        return items;
    }

    public void markAsDone(int id){
        db = getWritableDatabase();
        ContentValues updatedData = new ContentValues();
        updatedData.put(COLUMN_DONE, String.valueOf(Boolean.TRUE));
        String where = COLUMN_ID+" = "+String.valueOf(id);
        db.update(TABLE_NAME,updatedData,where,null);
    }
}

This is my custom adapter class for listView (TaskListAdapter.java):
public class TaskListAdapter extends ArrayAdapter<Task> {
    private final Context context;
    private final ArrayList<Task> values;
    private DatabaseHelper dbHelper;
    public TaskListAdapter(Context context,ArrayList<Task> values)
    {
        super(context,-1,values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView  = inflater.inflate(R.layout.task_list_row,parent, false);
        rowView.setTag(values.get(position).getId());
        TextView rowDescription = (TextView)rowView.findViewById(R.id.task_row_description);
        rowDescription.setText(values.get(position).getDescription());
        ImageView rowStatusIcon = (ImageView)rowView.findViewById(R.id.task_row_status_icon);

        Long currentDateMillSec= System.currentTimeMillis();
        Long dateMillSec = CommonHelper.convertStrDateToMilSec(values.get(position).getDate());//(date==null)?0:date.getTime();
        if(values.get(position).getDone()==Boolean.TRUE)
        {
           rowStatusIcon.setImageResource(R.drawable.done_icon);
        }
        else if(dateMillSec>0 && dateMillSec<currentDateMillSec)
        {
           rowStatusIcon.setImageResource(R.drawable.failed_icon);
        }
        else{
            rowStatusIcon.setImageResource(R.drawable.todo_icon);
        }

        TextView dateTf = (TextView)rowView.findViewById(R.id.task_row_date);
        dateTf.setText(values.get(position).getDate());

        Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
        doneBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //how can I instantiate the dbHelper class
                //Then use the merkAsDone method here
            }
        });
        return rowView;
    }

}

How can I instantiate the dbHelper property in my custom adapter and then call the markAsDone method in the done button click event. How can I achieve it whereas the adapter is not created within Activity?

A: Does not look like a big problem, instantiate it in your constructor:
public TaskListAdapter(Context context,ArrayList<Task> values)
{
    super(context,-1,values);
    this.dbHelper = new DatabaseHelper(context.getApplicationContext());
    this.context = context;
    this.values = values;
}

Then use it in your OnClickListener:
Button doneBtn = (Button)rowView.findViewById(R.id.task_row_done_btn);
doneBtn.setTag(values.get(position).getId());
doneBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        dbHelper.markAsDone(v.getTag());
    }
});

Don't forget to close your Database in DatabaseHelper.markAsDone

A: Firstly if you want to use the db inside the adapter , you can use CursorAdapter not ArrayAdapter ,
if you want to stay on arrayAdapter , then you can pass th db Object in the construcor

A: You should make the DatabaseHelper class as thread-safe Singleton and then get that instance from the adapter.
public class DatabaseHelper extends SQLiteOpenHelper{
     private static DatabaseHelper dbHelper;

    public static DatabaseHelper getInstance() {
        if(dbHelper == null)
        {
            synchronized (DatabaseHelper.class)
            {
                if(dbHelper == null)
                {
                    dbHelper = new DatabaseHelper(MyApplicationInstance.getAppContext());
                }
            }
        }

        return dbHelper;
    }

    private DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}

And then in the CustomAdapter just execute your commands as DatabaseHelper.getInstance().insert()
Hope this helps.


text:
Q: Spring Boot - Replace Redis with MapSessionRepositiry in non persistance storage on clustered environment Requirement - I need to store high-volume user session data in spring boot. I tried Redis as an option but unfortunately, it got failed in a clustered environment.
I want to store the non-persistence session in a clustered environment in spring boot.
Highly appreciated it if someone can share the git repo sample code. please help
private FindByIndexNameSessionRepository sessionRepository;
how we can implement the FindByIndexNameSessionRepository in spring boot 2.6.3. i tried but got below error.

Description:

Field sessions in com.teknospire.switch_transaction.controller.login.Login required a bean of type 'org.springframework.session.FindByIndexNameSessionRepository' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'org.springframework.session.FindByIndexNameSessionRepository' in your configuration.

@EnableSpringHttpSession
@Configuration
public class SpringHttpSessionConfig {

    @Bean
    public <S extends ExpiringSession> SessionRepositoryFilter<? extends ExpiringSession> springSessionRepositoryFilter(
            SessionRepository<S> sessionRepository, ServletContext servletContext) {
        SessionRepositoryFilter<S> sessionRepositoryFilter = new SessionRepositoryFilter<S>(sessionRepository);
        sessionRepositoryFilter.setServletContext(servletContext);
        return sessionRepositoryFilter;
    }

    @Bean
    public MapSessionRepository sessionRepository() {
        return new MapSessionRepository(new ConcurrentHashMap<>());
    }
}


text:
Q: Admin On Rest "Element Not Found" when doing an Edit View, no error in console I am trying to open an edit view on an object retrieved from a REST call from a list view. So for example I am retrieving a single user at the url
http://localhost:3000/#/admin/user/5978cf585a65b51ab5463252
And it display all the credentials in the form for a split second and it should(and as in the examples). And then it takes me back to the list view and says "Element not found". Is there a reason for this? I have created my own rest client to deal with my API as well so I don't see why there should be a compatibility thing?
Edit:
I found a workaround where if I change the rest endpoint to return some random garbage, the data correctly displays and is updated appropriately but this feels hacky, so I assume this is some sort of error?
Edit2:

{
  "_id": "59b6e30fb55e9d7bdfbdc477",
  "__v": 0,
  "created_at": "2017-09-11T19:25:03.169Z",
  "email": "test@gmail.com",
  "info": {
    "first": "Thomas",
    "last": "Test",
    "phone": "778-893-8835"
  },
  "login_type": "facebook",
  "updated_at": "2017-09-11T19:25:03.169Z",
  "verified": false
}


text:
Q: How to set focus to date portion of DateTimePicker that has a checkbox? I am using a regular vanilla DateTimePicker (DTP) in Windows Forms. The user has requested that when the window opens, the DTP is selected so they can immediately edit the date with the keyboard.
It is a DTP with a checkbox enabled, and so when I use the standard
DTP.Select()

it selects the checkbox, not the date-part of the control, which achieves nothing useful for the user.
I am sensing there is no way around this beyond hacks like SendKeys, which I will resort to if nobody has a good solution.
Thought I'd check with the boffins!

A: You must select the portion after it has the focus
For example :
SwitchToThisWindow(DTP.Handle, true);
SendKeys.Send("{RIGHT}");

with declaration :
    [DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool SwitchToThisWindow(IntPtr hWnd, Boolean fAltTab);


text:
Q: How to disable EMR Spark runtime eager executor loading AWS introduced Spark runtime and it provides lots of optimization out of the box. One of the optimization it does to eager executor allocation, which allocated max executors as mentioned in spark.dynamicAllocation.maxExecutors, which has a default value at app level. It is causing the problem as it also allocating executors for all small jobs as well, where it is not required.
I am looking for the configurations in AWS-EMR 5.3 to disable this eager executor allocation and fallback to the default executor allocation strategy.


text:
Q: SVN Authentication using Active Directory Is it possible to use Active Directory (Server 2008 R2) to manage users for a subversion repo that's hosted on Debian (Wheezy)?
I've tried linking the SVN hosted on Apache on a Debian server to the Active Directory on the windows server. I'm able to check out the repository however when I go to commit my changes I get a commit failed authorization failed (using tortoisesvn on a windows client, it never even asks for credentials when committing)
I'm using apache2 | 2.2.22-13+deb7u1
dav_svn.conf below:
<Location /svn>
DAV svn
SVNParentPath /srv/repos/svn
SVNListParentPath on
AuthName "helloworld"
AuthType basic
AuthzLDAPAuthoritative off
AuthBasicProvider ldap
AuthLDAPURL ldap://192.168.1.10/dc=example,dc=com?sAMAccountName" NONE
AuthLDAPBindDN "CN=subversion,OU=Users,DC=example,DC=com"
AuthLDAPBindPassword "secret"
Require ldap-group CN=svn,OU=groups,dc=example,dc=com
</Location>

A: Your config is just terrible bad (I can see a few correct string). Use config from here as good starting point (it miss only Require valid-user from my POV)

A: I needed to specify the global catalog port in the AuthLDAPURL.  I got it to work using the config below:
<Location /svn>
    DAV svn
    AuthType basic
    SVNParentPath /srv/repos/svn
    AuthName "helloworld"
    AuthBasicProvider ldap
    AuthLDAPURL "ldap://192.168.1.10:3268/dc=example,dc=com?sAMAccountName" NONE
    AuthLDAPBindDN "CN=subversion,CN=users,DC=example,DC=com"
    AuthLDAPBindPassword "secret"
    Require ldap-group CN=svn,OU=groups,DC=example,DC=com
</Location>


text:
Q: return regex result from cmd output to variable I'm looking forward to get a string from an cmd output (ID of tmutil destinationinfo).
I have tested this regex with https://regex101.com/r/aI3yH2/1:
/^.*?Name.+?backup02\nKind.+?\nID?\s+:\s([A-Z0-9\-]+)/s
Looks like it's working, I'm searching for backup01, backup02, ...
But how can I grab the ID to a variable within a shell script?
Output is like this:
====================================================
Name          : backup02
Kind          : Local
Mount Point   : /Volumes/ext_backup01_02
ID            : BC51C9FA-DE8A-4BA3-B23E-AEC10E9E9F69
> ==================================================
Name          : backup01
Kind          : Network
URL           : afp://username@server02.local/backup01
Mount Point   : /Volumes/backup01
ID            : 009B3736-61C5-4996-B9BC-A5230BED7961
====================================================
Name          : backup03
Kind          : Network
URL           : afp://username@server67.local/backup03
Mount Point   : /Volumes/backup01
ID            : 1E9A3734-33D6-1316-C9B4-B143DA35D9F2

I really don't know how to handle this. Sample code 100% not working:
#!/bin/bash
ID=$(tmutil destinationinfo | sed -E '/^.*?Name.+?backup02\nKind.+?\nID?\s+:\s([A-Z0-9\-]+)/s')
echo $ID

Thanks!

A: sed (and grep, which would be the other popular regex matcher) are line-oriented; they process one line at a time. So multiline patterns won't work.
You can get sed to accumulate lines, but it's not very pretty. If you did that, you would find that the regex dialect recognized by sed is quite different from the one you are using in the online tool. In particular, sed doesn't implement non-greedy match.
You can probably do better with awk:
awk -F '[[:space:]]*:[[:space:]]*' \
    '$1 == "Name" && $2 == "backup02" { this_one = 1 }
     this_one && $1 == "ID" { print $2; exit }'


text:
Q: RS232 serial output: confusion with wiring Brace with me as I am new to electronics, but am also eager to learn. I have a sensor which has 4 un-terminated wires:
1) 12V to 24V
2) RS-232 TxD
3) RS-232 RxD
4) Ground(and serial connector return)
I'm trying to get the sensor and my computer to talk but have faced nothing but failure. I have an RS-232 to TTL converter followed by an RS-232 to USB adapter. Here's where my real question starts. I understand that TTL has VCC, Tx, Rx and GND pins. Can my sensor talk to my computer using only the Tx and Rx wires? From my understanding, the two other wires need to be connected to an external battery since it draws so much power...but that leaves VCC and GND empty on my converter.
I've come to realize this morning that my RS-232 to USB adapter was out of date and not supported on my current version of windows. I have a new one on its way but still feel something is not quite right with my setup. Any help is greatly appreciated.
Thank you!
EDIT: Some extra information about my sensor: Digital output is RS-232 as ASCII chars, runs on 12-24 VDC(30mA@12V), configuration is 115200,8,N,1. I've also come to realize I probably don't need my TTL converter. How then would I communicate with only Rx and Tx? (Also, I know that Tx must go to Rx and vice-versa)

A: There are ways of "stealing" power from an RS232 port, but 30mA is pushing it, and you may not even get 12V.  So it's likely you'll need a battery or other power supply between 12V and Ground to power the sensor.
You can make an RS232 connection with just 3 wires - Rx Tx and Ground.  You need a cable with the Rx and Tx swapped, and the Ground wire connected at each end.
If the two ends are reluctant to talk, Google "rs232 three wire handshake looping".  You need to loop back some output pins of the RS232 port to fool the port into thinking that it is fully connected to something at the other end.

A:
simulate this circuit – Schematic created using CircuitLab
Figure 1. Wiring diagram.
It sounds as though you have an industrial sensor as 24 V is standard for these. You need to supply 24 V DC between the Vcc and GND terminals. You also need to use screened data cable back to your RS232 port.
If your sensor sends out a continuous stream of data then you can monitor this with a serial terminal emulator such as PuTTY to see if you can make any sense of the data.


text:
Q: map over list columns and extract the first list item I have the following data which looks like:
# A tibble: 6 × 2
  `Total_ Española_Porcentaje` `Total_ Extranjero_Porcentaje`
  <list>                       <list>
1 <dbl [3]>                    <dbl [3]>
2 <dbl [3]>                    <dbl [3]>
3 <dbl [3]>                    <dbl [3]>
4 <dbl [3]>                    <dbl [3]>
5 <dbl [3]>                    <dbl [3]>
6 <dbl [3]>                    <dbl [3]>

I am trying to map over the columns using map and extract the first dbl.
I have tried
df %>%
  map_dbl(., ~if(length(.x)) .x[1] else NA)

and
df %>%
  imap_dfc(., function(x, y)
    tibble(!!y := map_dbl(x, ~if(length(.x)) .x[1] else NA)))

But I can't get it to work.
Data <- structure(list(`Total_ Española_Porcentaje` = list(c(5.9, 5.9,
5.9), c(5.9, 5.9, 5.9), c(5.9, 5.9, 5.9), c(5.9, 5.9, 5.9), c(5.9,
5.9, 5.9), c(5.9, 5.9, 5.9)), `Total_ Extranjero_Porcentaje` = list(
    c(5.9, 5.9, 5.9), c(5.9, 5.9, 5.9), c(5.9, 5.9, 5.9), c(5.9,
    5.9, 5.9), c(5.9, 5.9, 5.9), c(5.9, 5.9, 5.9))), row.names = c(NA,
-6L), class = c("tbl_df", "tbl", "data.frame"))

A: We can use across to loop over the list columns, then map over the elements of the list, if the length is greater than 0, select the first element or else returns NA
library(dplyr)
library(purrr)
Data %>%
      mutate(across(everything(),
       ~ map_dbl(., ~ if(length(.x) ) first(.x) else NA)))
# A tibble: 6 x 2
  `Total_ Española_Porcentaje` `Total_ Extranjero_Porcentaje`
                         <dbl>                          <dbl>
1                          5.9                            5.9
2                          5.9                            5.9
3                          5.9                            5.9
4                          5.9                            5.9
5                          5.9                            5.9
6                          5.9                            5.9

Or as inspired from @ThomasIsCoding
map_dfr(Data, map_dbl, first)
# A tibble: 6 x 2
  `Total_ Española_Porcentaje` `Total_ Extranjero_Porcentaje`
                         <dbl>                          <dbl>
1                          5.9                            5.9
2                          5.9                            5.9
3                          5.9                            5.9
4                          5.9                            5.9
5                          5.9                            5.9
6                          5.9                            5.9

A: A base R trick
> Data[] <- lapply(Data, sapply, `[`, 1)
> Data
# A tibble: 6 x 2
  `Total_ Espa±ola_Porcentaje` `Total_ Extranjero_Porcentaje`
                         <dbl>                          <dbl>
1                          5.9                            5.9
2                          5.9                            5.9
3                          5.9                            5.9
4                          5.9                            5.9
5                          5.9                            5.9
6                          5.9                            5.9

A: Maybe we can use pluck from purrr package:
pluck() implement a generalised form of [[ that allow you to index deeply and flexibly into data structures. https://purrr.tidyverse.org/reference/pluck.html
library(purrr)
pluck(Data, 1)

Output:
 pluck(2,2)
[1] 5.9 5.9 5.9
> pluck(Data,1)
[[1]]
[1] 5.9 5.9 5.9

[[2]]
[1] 5.9 5.9 5.9

[[3]]
[1] 5.9 5.9 5.9

[[4]]
[1] 5.9 5.9 5.9

[[5]]
[1] 5.9 5.9 5.9

[[6]]
[1] 5.9 5.9 5.9


text:
Q: UART noise on audio lines I have a fairly simple circuit with an Arduino and a SA818 RF module, I'm providing 3v3 power to the SA818 via two series diodes (dirty I know) and am communicating using software serial, of which the TX line from the Arduino runs to the RX of the SA818 using a resistor divider to drop it to 3v3, I have a small speaker connected between the SA818 AF output and ground. everything works but the noise (pulses) when the TX line is transmitting completely swamps out the audio from the SA818. I have placed a capacitor between the AF out and the speaker but it has not helped. I know this is a bare minimum circuit but does anyone have ideas of how to isolate the UART from the audio?

A:
the TX line from the Arduino runs to the RX of the SA818

If you look closely at the block diagram for the SA818 (below)...

... you will see that the RX line is an output and this therefore means that you are connecting your UART output to the SA818 RX output. Even though you are doing this via resistor it doesn't make any sense at all.
Of course, I can't vouch for the datasheet being correct as it does appear to contradict itself later on when it says: -
 | 16 | RXD | RXD of the module and connect to external TXD |


text:
Q: Check if Array.toJSON has been overridden in JavaScript Is there a way to check whether the JavaScript/Browser's own Array.toJSON was overridden by any framework or script? My script is injected inside the websites and I have an issue where in some cases Prototype framework is overriding native Array.toJSON function which is buggy and causes issues.
Edit: There is no toJSON function by default. I was confused a bit as it seems Prototype framework prototypes it to an Array, and JSON.stringify is using it to convert array to JSON which was causing an issue...

A: While this doesn't answer your exact question, it seems, a way to deal with Prototype's broken implementation of Array.toJSON  is to check if it's broken, rather than checking if it was overwridden:
var arr = [1,2,3], corrupted;

if (typeof arr.toJSON === "function") {
  arr = arr.toJSON();
  corrupted = !(arr && arr.length == 3 && arr[2] == 3);
}

More details here http://anton.kovalyov.net/p/tojson/
Hope this helps.


text:
Q: Why is my database field 'not updateable'? I am developing a program which allows the user to take tests and receive a score, percentage and grade for this. These will be stored in a data table, named 'tblStudentScores'. The SQL code below aims to update the relevant record when a user completes a test, so that their latest score for that test is stored.
UPDATE tblStudentScores
SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True
WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;

When testing this SQL in MS Access, it works perfectly. However, when I attempt to use the same query as an OleDBCommand in VB.NET, nothing happens. There is no error message, but the code does not update the table either.
I thought this may be due to parameters so I explicitly declared these at the top of the query:
PARAMETERS @SpecID Number, @StudID Number, @Score Number, @Perc Number, @Grade Text;

Now, rather than nothing happening, I receive the following error message:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Cannot update 'Score'; field not updateable.

As I have previously said, the query succeeded in MS Access's query designer, so the field must be updateable. What could be going wrong here?
EDIT: After further testing, I have found that the query does work in VB when using fixed inputs, rather than parameters. The problem is clearly therefore with the parameters, but what could the problem be?
EDIT: The entire piece of code in which I create and use the query is below:
 Dim cmd As New OleDbCommand("PARAMETERS @Score Number, @Perc Number, @Grade Text, @SpecID Number, @StudID Number; UPDATE tblStudentScores " & _
                                    "SET Score = @Score, Percentage = @Perc, Grade = @Grade, CompletedTask = True " & _
                                    "WHERE SpecificTaskID = @SpecID AND StudentID = @StudID;", connection)

        With cmd.Parameters
            .AddWithValue("@Score", score)
            .AddWithValue("@Perc", percentage)
            .AddWithValue("@Grade", grade)
            .AddWithValue("@SpecID", specificIDorder(cbxCurrentTasks.SelectedIndex))
            .AddWithValue("@StudID", id)
        End With

        connection.Open()
        cmd.ExecuteReader()
        connection.Close()

A: Keep your data objects local so you can be sure they closed and disposed. The Using...End Using blocks do this for you even if there is an error.
Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/  and https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/#comment-8442  to see the reason why. You will have to check the database for the datatypes of the fields. I just guessed.
In Access the names of parameters do not matter. The order that they appear in the sql statement must match the order that they are added to the Parameters collection.
.ExecuteReader is used to retrieve records. You want to execute an Update statement so use .ExecuteNonQuery.
I am not sure what you are doing with specificIDorder(cbxCurrentTasks.SelectedIndex
Is specificIDorder a Function that returns some value based on the index that is selected in the combo box? If not you need to rethink the value for that parameter.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Using cn As New OleDbConnection("Your connection string")
        Using cmd As New OleDbCommand("Update tblStudentScores
                                Set Score = @Score,
                                Percentage = @Perc,
                                Grade = @Grade,
                                CompletedTask = True
                                WHERE
                                SpecificTaskID = @SpecID
                                And
                                StudentID = @StudID;", cn)
            With cmd.Parameters
                .Add("@Score", OleDbType.Integer).Value = score
                .Add("@Perc", OleDbType.Integer).Value = percentage
                .Add("@Grade", OleDbType.VarChar).Value = grade
                .Add("@SpecID", OleDbType.Integer).Value = CInt(specificIDorder(cbxCurrentTasks.SelectedIndex))
                .Add("@StudID", OleDbType.Integer).Value = id
            End With
            cn.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Using
End Sub


text:
Q: How prove this $F'(x_{0})=f(x_{0})$ if $F(x)=\int_{a}^{x}f(t)dt,x\in[a,b]$ Question:
let $f$ be Riemann integrable on $[a,b]$,Assmue that $x_{0}\in [a,b]$,and let $f(x)$ is continuous on point $x=x_{0}$,and define
$$F(x)=\int_{a}^{x}f(t)dt,x\in[a,b]$$
show that
$$F'(x_{0})=f(x_{0})$$
This problem is my friend (He is a teacher) ask me,and I post my answer,maybe have some wrong,

since
  $$F'(x_{0})=\lim_{x\to x_{0}}\dfrac{F(x)-F(x_{0})}{x-x_{0}}=\lim_{x\to x_{0}}\dfrac{\int_{x_{0}}^{x}f(t)dt}{x-x_{0}}$$
  and other hand,

case1: $x>x_{0}$ we have

$$I=\left|\dfrac{\int_{x_{0}}^{x}f(t)dt}{x-x_{0}}-f(x_{0})\right|=\dfrac{\left|\int_{x_{0}}^{x}f(t)dt-f(x_{0})(x-x_{0})\right|}{x-x_{0}}\le\dfrac{\int_{x_{0}}^{x}|f(t)-f(x_{0})|dt}{x-x_{0}}$$
  since
  $f(x)$ is continous on point $x=x_{0}$
  so
  $$I\le\dfrac{\int_{x_{0}}^{x}\varepsilon dt}{x-x_{0}}=\varepsilon$$
  so
  $$F'(x_{0})=f(x_{0})$$

case2:$x<x_{0}$

$$I=\left|\dfrac{\int_{x_{0}}^{x}f(t)dt}{x-x_{0}}-f(x_{0})\right|=\dfrac{\left|\int_{x_{0}}^{x}f(t)dt-f(x_{0})(x-x_{0})\right|}{|x-x_{0}|}\le\dfrac{\int_{x}^{x_{0}}|f(t)-f(x_{0})|dt}{x_{0}-x}$$
  since
  $f(x)$ is continous on point $x=x_{0}$
  so
  $$I\le\dfrac{\int_{x}^{x_{0}}\varepsilon dt}{x_{0}-x}=\varepsilon$$

My question:  someone  have other methods? Thank you  very much!

A: Wikipedia
We can use Leibniz integral rule for variable limit
$$\frac{d}{dx}\int_{h(x)}^{g(x)}f(t)dt$$ =
$$f(g(x)).h'(x)-f(h(x)).g'(x)$$
We have
$$F(x)=\int_{a}^{x}f(t)dt,x\in[a,b]$$
Therefore  $$\frac{d}{dx}F(x) =f(x) $$
and $$ F'(x)=f(x) $$
so
$$F'(x_0)=f(x_0)$$

A: I don't know that this amounts to a different approach, but:
Building on the fact that if $f:[c,d]\to\mathbb{R}$ is integrable (this is actually important; one must know that $f$ is integrable on $[a,b]$ to define $F$ as above) and non-negative (i.e., $f(x)\geq 0$) then $\int_c^d f(x)dx\geq 0$ as well, we note that for sufficiently small $\epsilon>0$
$$\inf_{|t-x_0|<\epsilon} f(t)\leq\frac{1}{\epsilon}\int_{x_0}^{x_0+\epsilon} f(t)dt\leq\sup_{|t-x_0|<\epsilon} f(t),$$
and similarly
$$\inf_{|t-x_0|<\epsilon} f(t)\leq\frac{1}{\epsilon}\int_{x_0-\epsilon}^{x_0} f(t)dt\leq\sup_{|t-x_0|<\epsilon} f(t).$$
Since $f$ is continuous at $x_0$, we know that
$$\lim_{\epsilon\to 0}\inf_{|t-x_0|<\epsilon} f(t) = f(x_0) = \lim_{\epsilon\to 0}\sup_{|t-x_0|<\epsilon} f(t),$$
implying that
$$\exists\lim_{\epsilon\to 0}\frac{F(x_0+\epsilon)-F(x_0)}{\epsilon} = f(x_0).$$

A: That's correct but assumes $a$ and $f$ are fixed.
Just to challenge your friend, you can prove with the same argument that if
$$F(x)=\int_x^b f(t)dt,x∈[a,b]$$
then
$$F'(x_0)=-f(x_0), x \in [a,b].$$


text:
Q: Java Sorting Map of  So I want to be able to sort this map into a TreeMap or LinkedHashmap by comparing by a value in the CustomObject i.e compare via object.getSomeValue().
So the object with the highest value will be obviously first in the LinkedHashmap

A: You can't do it in reasonable manner, but if you really want it what you can do is:
List<EntrySet<UUID, CustomObject>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (e1, e2) -> /*comparision here*/);
Map<UUID, CustomObject> sortedMap = new LinkedHashMap<>();
for(Entry<UUID, CustomObject> entry: list){
   sortedMap.put(entry.getKey(), entry.getValue());
}


text:
Q: Java Installations and switch java versions I have installed intelliJ and java. Without even setting up any paths or zshrc profile.  When I run a simple java program in intelliJ (by clicking the handy green play button). It picks it up and executes the program. However the same done via terminal with javac filename.java returns

javac: file not found: first.java
Usage: javac <options> <source files>

Upon executing java -version; I dont have an established on.
When i setup the java_Home in .zshrc file however, java -version returns the expected Java version and I am able to execute now my java program via terminal.
Is the later setup system wide and the initial one only for the intelliJ specific project?
I am confused why intelliJ works without addition java_home setup.


text:
Q: Compute $\lim_{n\to \infty} \sum_{k=1}^{n} \arctan \frac{x} {1+k(k+1)x^2}$, $x>0$ I tried using the squeeze theorem, but I had no luck. Then I thought that maybe the sum is telescoping, but also I couldn't see any pattern.

A: You can simplify the given expression as follows:
$\lim_{n\to\infty}$ $\sum_{k=1}^n$ $\tan^{-1} (\frac{x}{1+k(k+1)x^2})$
$=\lim_{n\to\infty}$ $\sum_{k=1}^n$ $ \tan^{-1}( \frac{(k+1)x - kx}{1+k(k+1)x^2})$
$=\lim_{n\to\infty}$ $\sum_{k=1}^n$ $(\tan^{-1} ((k+1)x) - \tan^{-1}(kx))$
Applying the limit and by telescopic sum,
$\lim_{n\to\infty}$ $\sum_{k=1}^n$ $(\tan^{-1} ((k+1)x) - \tan^{-1}(kx))$
$=\tan^{-1}\infty - \tan^{-1} x$
$= \frac{\pi}{2} - \tan^{-1}x$

A: You can use the following formula
\begin{equation}
\arctan{u}+\arctan{v}=\arctan{\frac{u+v}{1-u v}}
\end{equation}
which is valid for $u v <1$. Now consider the sum. For $k=1$ you have
\begin{equation}
\arctan{\frac{x}{1+2 x^2}}
\end{equation}
and for $k=2$
\begin{equation}
\arctan{\frac{x}{1+6 x^2}}
\end{equation}
If you apply the formula above to the first two term you get:
\begin{equation}
\arctan{\frac{x}{1+2 x^2}}+\arctan{\frac{x}{1+6 x^2}}=\arctan{\frac{2x}{1+3 x²}}
\end{equation}
 You can repeat the same computation for the term obtained using $k=3$ and $k=4$ and so on and find the expression:
\begin{equation}
\arctan{\frac{2x}{1+x²(2 m+1)(2m-1)}}
\end{equation}
where the index $m$ runs from 1 to N/2. This procedure can be repeated again and again. For instance the $\arctan{\frac{2x}{1+3 x²}}$ can be added to the sum of the terms obtained by using $k=3$ and $k=4$ and the sum can be written as
\begin{equation}
\arctan{\frac{4x}{1+x²(4w-31)(4w+1)}}
\end{equation}
where the index $w$ runs from 1 to N/4. By applying the formula of the sum of the two arctan it is possible to compute:
\begin{equation}
\sum_{k=1}^{n} \arctan \frac{x} {1+k(k+1)x^2}=\frac{2 x n}{1+x²(2 n +1)}
\end{equation}
So that
\begin{equation}
\lim_{n\to \infty} \sum_{k=1}^{n} \arctan \frac{x} {1+k(k+1)x^2}=arccot(x)
\end{equation}
please note that $arccot(x)=\frac{\pi}{2}-\arctan{x}$.


text: Q: Receiving a speech signal input from Bluetooth to Android We're looking at creating an Android app that takes a speech signal from a Bluetooth headset. We'd like to apply some digital signal processing to the signal and output it through the Android phone speakers themselves, I'm having a hard time finding info on sending Bluetooth data into an app. After the device has been located and paired, how can I work with input?


text:
Q: ASP.NET PreInit() and IsPostBack property What does PreInit() do   by   checking  IsPostBack  property?
Genererally while explaining PreInit()  lot webpages  say   it   checks IsPostBack  property.
But   they  don't tell   what will PreInit do if IsPostBack is true or IsPostBack is false?

A: It's explained here ( http://msdn.microsoft.com/en-us/library/ms178472.aspx ) that you can use the value of IsPostBack to determine if it's a postback or not.  If it is a postback the values of the controls on the page will not be set yet.

A: If page is posted, role of preinit to load the data existed on page before post.


text:
Q: kubectl patch returning service not found I have deployed pihole on my k3s cluster using this helm chart https://github.com/MoJo2600/pihole-kubernetes.
(I used this tutorial)
I now have my services but they dont have external IPs:
NAME             TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE
pihole-web       ClusterIP   10.43.58.197    <none>        80/TCP,443/TCP   11h
pihole-dns-udp   NodePort    10.43.248.252   <none>        53:30451/UDP     11h
pihole-dns-tcp   NodePort    10.43.248.144   <none>        53:32260/TCP     11h
pihole-dhcp      NodePort    10.43.96.49     <none>        67:30979/UDP     11h

I have tried to assing the IPs manually with this command:
kubectl patch svc pihole-dns-tcp -p '{"spec":{"externalIPs":["192.168.178.210"]}}'

But when executing the command i'm getting this error:
Error from server (NotFound): services "pihole-dns-tcp" not found

Any Ideas for a fix?
Thank you in advance :)

A: *

*Looks Like "pihole-dns-tcp" is in a different namespace to the namespace where patch command is being ran.

*As per the article you have shared , it seems like service pihole-dns-tcp is in pihole . So the command should be
kubectl patch svc pihole-dns-tcp -n pihole -p '{"spec":{"externalIPs":["192.168.178.210"]}}'


text:
Q: Is this code correct to add a background image using css? body{
background:url("?../img/by.jpg") no-repeat;
background-size:cover;

}
Will this code work in all browsers
Or I can do it without the question mark???

A: Use this to background image to an element also this will work in all browsers

element {
  background-image: url('your_Source');
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
}

A: Try this and it will work on all the browsers.

body{
/*
background: color-name url("image-source") repeat-property attachment-property position-property;
Shorthand Example :- */
background: #D0E4F5 url("https://picsum.photos/200") no-repeat scroll 0px 0px;
/*
Long Example :-
#demo {
background-color: #D0E4F5;
background-image: url("/images/smiley.png");
background-repeat: no-repeat;
background-attachment: scroll;
background-position: 0px 0px;
}
*/

}
<html>
<head></head>
<body>
Some Example Text
</body>
</html>


text:
Q: Problem with partitions I am using Ubuntu 14.04. Whenever I open GParted, I get a libparted bug found error:
Error informing the kernel about modifications to partition /dev/sda2 -- Device or resource busy.
This means Linux won't know about any changes you made to /dev/sda2 until you reboot -- so you shouldn't mount it or use it in any way before rebooting.

When I press Ignore button, the following window opens:

But when I press Cancel, I get:
Failed to add partition 2 (Device or resource busy)

I also tried fdisk -l and got an problem there:
prateek@prateek-Lenovo-G500:~$ sudo fdisk -l
Disk /dev/sda: 500.1 GB, 500107862016 bytes
255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disk identifier: 0xd9fa2484
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048     2050047     1024000    b  W95 FAT32
/dev/sda2         2050055   976773119   487361532+   f  W95 Ext'd (LBA)

Partition 2 does not start on physical sector boundary.
/dev/sda5         2050056   415619071   206784508    7  HPFS/NTFS/exFAT
/dev/sda6       415621120   498724863    41551872   83  Linux
/dev/sda7       498726912   968169471   234721280    7  HPFS/NTFS/exFAT
/dev/sda8       968171520   976773119     4300800   82  Linux swap / Solaris

I am stuck here and I have no idea how to solve this problem. Can anybody help me?


text:
Q: Target-Dependent Code & Portability Question is: What is target-dependent code and how does it effect portability of a software?

Motivation to ask this question
In a CS class, I'm told that the more  target-dependent code software has, the more portable it will be.But it feels wrong to me, actually I think the opposite.
Justification was that target-dependent code means an implementation that is specific  to a target and more target you cover means you can run software on more targets. (Target is defined as an hardware& software environment) As you can run the software on more targets, it makes the software more portable.

A: When we call software "portable" it means that it is easy to make the software run on different targets. Usually that means it is possible to make the software run on different targets with very little target dependent code. Software that is less portable needs more target dependent code to make it run on different targets.
Of course if you make the software run on ten targets, you will have more target dependent code than for two targets. But that doesn't mean the software is "portable". It means the software has been ported.

A:
Justification was that target-dependent code means an implementation that is specific to a target and more target you cover means you can run software on more targets.  ...  As you can run the software on more targets, it makes the software more portable.

There's a very important difference between programs that can be made to run correctly on multiple targets and programs written with portable code.
Absent a standard, the way you make code run correctly on multiple targets is to write one implementation per target or group of targets that behave the same way.  This sort of development was at its worst in code developed to run on Unix systems during the 1980s and early 1990s as competing vendors tried to capture as much of the market as possible and become "the" standard.  It was not unusual for a program to make extensive use of conditional compilation or execution to make it work on the raft of vendor-specific flavors of System V and BSD.  The implementations may be conveniently bound together into a single file and selected based on outside factors, but that doesn't change the fact that there are multiple implementations.  Programs like this are not, by definition, portable because what runs on each target is different (i.e., it's target-specific code).  They are, as gnasher729 points out in his answer, ported.
Portability comes from the adoption of standards that offer a well-defined API for programs to use that handles a target's idiosyncrasies behind the scenes.  For example, I can be confident that this bit of C will compile and run as expected on Windows, Linux, Solaris or OS X:
int file = open("somefile", O_RDONLY);
lseek(file, 12345, SEEK_SET);
char buffer[1024];
read(file, buffer, 1024);
/* Do something with buffer */
close(file);

This is portable code because all of the targets listed above have ISO C compilers and libraries that conform to POSIX, where the P stands for portable.
The litmus test for portability is not having to make changes for it to run on a new target.  What your prof is saying boils down to "a program can be run on any target where you can beat the source code into submission."  In my book, that's the polar opposite of portability and makes him dead wrong.

A: I googled the same thing after hearing the said argument from the same professor and ended up here, hoping stating what I understood would be beneficial:
Imagine you're building a car that can run on different environments. You would add some gear for deserts, some for tundras, etc etc. The specialized gears for different cases are the target dependent code. If you have specialized gears for different conditions, you can use the car in different conditions, thus making it more portable. If the car has no specific gear and only fit for use in cities, than the car would not be portable to deserts, or tundras of Siberia.
But of course adding specialized gear for every situation would not be the optimal approach to portability, making regular gears that can generalize to multiple situations is a way better approach.


text:
Q: Justifing letters html5 canvas - Js fiddle example Here is a JSFiddle. - The larger the string in length the more space is added to the right.
I am trying to create some code that justifies text on canvas:
var ctx = this.ctx; // Is now canvas context

var str = 'A random string';

var width = 500; // The size that the string should fit to

var strWidth = this.ctx.measureText(str); // The width in pixels of the string when it's put on canvas

var chars = str.split(''); // Make an array of string

var space = (width - strWidth.width) / (chars.length - 1);

var xpos = 1; // Start of text X position

this.ctx.clearRect(0,0,750,750);

    var ctx = this.ctx;

Array.each(chars, function(char) {
    ctx.fillText(char, xpos, 1);
    xpos += space.toInt();
});

I don't want the words to be justified, instead I would like the letters to be justified.
Basically this iterates over the string's characters and draws them onto the canvas with added spacing between each character to FILL a certain width. This code seems to add too much spacing to the right. The larger the string in character length the more space is added  to the right.
I think it may be something to do with the space variable  calculation. I am trying to fit a random length string into a specific space by lengthening the space between each character.
Any help is appreciated!

A: You are very close but you are only adding width of the space and forget to add the width of the char as well:
Try this and it should work:
xpos += space + ctx.measureText(char).width;

MODIFIED FIDDLE HERE
Also for more accuracy you should not round your spacing to integer value. Canvas can handle sub-pixeling and it will give a better result (I modified this in the fiddle as well in canvas to demonstrate).


text:
Q: How to show Image with http url in asp.net In sql server database, I have column name Image which has urls like http://www.xyz.com/1009/image1.jpg
Now I want to display it on my datalist. But it is not showing any image. It is might be the case because it is expecting the Image URL to be ~/Folder/abc.jpg
Then how to show the image on the asp.net page when I have image URL, which control I need to use and how?

A: If you are getting the image from the database in for the form xzy.com/1009/image1.jpg but want to add the http:// then your code should be
<asp:Image ID="imgmain" runat="server" ImageUrl='<%#String.Format("http://{0}", Eval("Image"))%>' Width="80" Height="80" />

A: Do you see little red X instead of an image?
If so, right click it --> Properties (IE) to see the URL it's referring to.
Might give us hint on what's going on. :)


text:
Q: Clojure using let variable declaration within its own instantiation? In the language of Clojure I am trying to pass a variable that I am defining within a let as a parameter to a function within the same let. The variable itself represents a list of vectors representing edges in a graph. The function I want to pass it to uses the list to make sure that it does not generate the same value within the list.
The function in whole
(defn random-WS
  ([n k] (random-WS (- n 1) k (reg-ring-lattice n k)))
  ([n k graph]
   (cond (= n -1) graph
         :else
         (let [rem-list (for [j (range (count (graph n))) :when (< (rand) 0.5)]
                          [n (nth (seq (graph n)) j)])
               add-list (for [j (range (count rem-list))]
                          (random-WSE graph n add-list))
               new-graph (reduce add-edge (reduce rem-edge graph rem-list) add-list)]
           (random-WS (- n 1) k new-graph)))))

The actual problem statement is seen here
add-list (for [j (range (count rem-list))]
    (random-WSE graph n add-list))

Again for clarity, the function random-WSE generates a random edge for my graph based on some rules. Given the current graph, current node n, and current list of edges to add add-list it will generate one more edge to add to the list based on some rules.
The only real idea I have is to first let add-list () to first define it before then redefining it. Though this still has somewhat the same issue, though add-list is now defined, it will be () through out the for statement. Thus the function random-WSE will not take into account the edges already in the list.
Is there a way to "evaluate" add-list at some defined point within its own definition so that it can be used, within its definition? So I would first "evaluate" it to () before the for and then "evaluate" after each iteration of the for.
If you're interested the function is used to create a random Watts-Stogatz graph.

A: From what I get of your description of this algorithm, add-list grows (accumulates) during the problematic for loop. Accumulation (for a very broad acceptation of accumulation) is a strong sign you should use reduce:
(reduce (fn [add-list j] (conj add-list (random-WSE graph n add-list))) [] (range (count rem-list))

A: Basically you're chaining results in your let, in the sense that the result of the first computation (resulting in rem-list) is the sole input for your second computation (your trouble point) which again is the sole input for your third computation, which is finally the sole input to your final computation step (your recursion step). If this chaining sounds familiar, that's because it is: think about reformulating your let construction in terms of the threading macro ->.
I.e. something along the lines of
(defn- rem-list [graph n]
   ...)
(defn- add-list [remlist n]
   ...)
(defn- new-graph [addlist]
   ...)

(defn random-ws
   ([n k] ...)
   ([graph n k] ;; <- note the moved parameter
     (cond (= n -1) graph
           :else
           (-> graph
               (rem-list n)
               (add-list n)
               (new-graph)
               (random-ws (dec n) k))))

You can then formulate add-list as a simple recursive function (maybe introduce an accumulator variable) or use the reduce variant that cgrand explained.


text:
Q: How TabNavigator Implement in React Native I want to implement tab navigator in react native.The link from which i get the code is
     https://reactnavigation.org/docs/navigators/tab
The Problem is that when i run the code i get the error 500 type i also at the end attach the picture of the error.Plz resolve the issue if any one know about it the code is....
import React from 'react';
import {
  AppRegistry,
  Text,
} from 'react-native';
import { StackNavigator } from 'react-navigation';
class MyHomeScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
    // Note: By default the icon is only shown on iOS. Search the showIcon option below.
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./chats-icon.png')}
        style={[styles.icon, {tintColor: tintColor}]}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    );
  }
}

class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Notifications',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./notif-icon.png')}
        style={[styles.icon, {tintColor: tintColor}]}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

const styles = StyleSheet.create({
  icon: {
    width: 26,
    height: 26,
  },
});

const MyApp = TabNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
}, {
  tabBarOptions: {
    activeTintColor: '#e91e63',
  },
});
AppRegistry.registerComponent('TabNavigator', () => MyApp);

when i run this code i get the error

Even i use the simple stack navigator on that time i also get the same error
the code of stack navigator i get from this link
https://reactnavigation.org/docs/intro/

A: The error tells you that a local image can not be found.
There are  two options:

*

*Create a chats-icon.png and a notif-icon.png and place them both in the directory where the file you copied the content from is at.

*Replace source={require('./chats-icon.png')} and source={require('./chats-icon.png')} with source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}} to use an example remote image.
This should eliminate the 500 error and let you continue working.


text:
Q: How to insert the correct response data into Jest? Based on the excellent answers I am attempting to implement JestJS on a similar function.
Question
The problem seams to be how I am inserting the mocked response data in jest.mock(). Below have I described and included all the files I have used.
Can anyone figure out what I am doing wrong?
Here is a live version to try out. https://repl.it/@SandraSchlichti/jest-playground-1#getStatusCode.js
Background
First I dump the correct response data by
const getStatusCode = require('./getStatusCode');

getStatusCode({
  url: 'https://google.com',
  statusCode: 200,
  timeout: 1000,
  maxRedirects: 0
});

getStatusCode.js
const axios = require('axios');
const qs = require('qs');

module.exports = async (options) => {
  options              = options || {};
  options.url          = options.url || {};
  options.statusCode   = options.statusCode || 0;
  options.timeout      = options.timeout || 1000;
  options.maxRedirects = options.maxRedirects || 0;

  try {
    const response = await axios.get(options.url, {
      timeout: options.timeout,
      maxRedirects: options.maxRedirects,
      // make all http status codes a success
      validateStatus: function (status) {
        return true;
      }
  });

    console.log(response); // here just to get the response data for Jest

    return (response.status === options.statusCode) ? 1 : 0;
  } catch (error) {
    return -1;
  }
};

which gives a very large output:
{
  status: 301,
  statusText: 'Moved Permanently',
  headers: {
    location: 'https://www.google.com/',
    'content-type': 'text/html; charset=UTF-8',
    date: 'Thu, 12 Nov 2020 10:48:21 GMT',
    expires: 'Sat, 12 Dec 2020 10:48:21 GMT',
    'cache-control': 'public, max-age=2592000',
    server: 'gws',
    'content-length': '220',
    'x-xss-protection': '0',
    'x-frame-options': 'SAMEORIGIN',
    'alt-svc': 'h3-Q050=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
    connection: 'close'
  },
  config: {
...

Since I am only interested in the value of status, I just copy/paste the first section into data of my getStatusCode.test.js file.
getStatusCode.test.js
const axios = require('axios');
const getStatusCode = require('./getStatusCode');

// whenever Axios is called from getStatusCode() it won't make a network
// connection, but return the following instead
jest.mock("axios", () => {
  return {
    get: jest.fn().mockResolvedValue({
      data:
      {
        status: 301,
        statusText: 'Moved Permanently',
        headers: {
          location: 'https://www.google.com/',
          'content-type': 'text/html; charset=UTF-8',
          date: 'Thu, 12 Nov 2020 10:09:41 GMT',
          expires: 'Sat, 12 Dec 2020 10:09:41 GMT',
          'cache-control': 'public, max-age=2592000',
          server: 'gws',
          'content-length': '220',
          'x-xss-protection': '0',
          'x-frame-options': 'SAMEORIGIN',
          'alt-svc': 'h3-Q050=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
          connection: 'close'
        }
      }
    })
  };
});

describe("test getStatusCode ", () => {
  // pretend to get data from the network connection
  let response;
  beforeAll(async () => {
    response = await getStatusCode({
      url: 'https://google.com',
      statusCode: 200,
      timeout: 1000,
      maxRedirects: 0
    });
  });

  // compare returned data with expected
  it("fetches raw response but we are only interested in the statuscode", async () => {
    // ensure the mocked Axios function has been called
    expect(axios.get).toHaveBeenCalled();

    expect(response.status).toBeGreaterThan(0);
  });

});

Running npm run test gives me
 FAIL  ./getStatusCode.test.js
  ● Console

    console.log
      {
        data: {
          status: 301,
          statusText: 'Moved Permanently',
          headers: {
            location: 'https://www.google.com/',
            'content-type': 'text/html; charset=UTF-8',
            date: 'Thu, 12 Nov 2020 10:09:41 GMT',
            expires: 'Sat, 12 Dec 2020 10:09:41 GMT',
            'cache-control': 'public, max-age=2592000',
            server: 'gws',
            'content-length': '220',
            'x-xss-protection': '0',
            'x-frame-options': 'SAMEORIGIN',
            'alt-svc': 'h3-Q050=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
            connection: 'close'
          }
        }
      }

and later on
  ● test getStatusCode  › fetches raw response but we are only interested in the statuscode

    expect(received).toBeGreaterThan(expected)

    Matcher error: received value must be a number or bigint

    Received has value: undefined

So clearly I haven't reproduced the response from axios.get() correct.
What am I doing wrong?

A: Your function getStatusCode checks the response and returns -1 or 0.
So you can't expect it to have a property status
You can check if it is toBeGreaterThanOrEqual to zero
expect(response).toBeGreaterThanOrEqual(0)

working example
Edit: If you want to make an assertion that the mock function have returned a promise resolved with an object that has data.status you can use jest mock function's mock property like this:
expect(await axios.get.mock.results[0].value).toHaveProperty('data.status', 301)

// where axios.get.mock.results is an array with the result for each call
// and "[0].value" is the result for the first call
// which would be a reference to the promise object, hence the await

But generally you want to test your implementation, not the mocked functions


text:
Q: For duplicate questions, provide a direct link to the root duplicate Yesterday I posted a question detailing my walk down a lengthy linked list of duplicates to finally find my Russian doll of an answer.
It would have been so convenient to have had a Table of Duplicates, so I could have easily seen at a glance what different variations might be. A summary of top-voted ones would be especially useful considering there's no limit to how many there could be in a linked chain. I upvoted that feature-request, but since it's from 2010 it's probably just not worth it to implement. It was even stirred up again in 2013 with the Duplicate Questions sidebar, on which Shog9 said:

Duplicates should be a subset of "linked" questions. This isn't entirely true at the moment, but will be shortly.

Shortly can take a while in my experience, and I'm sure this is implemented to some extent already. But neither Shog's comment nor Jeff Atwood's answer were fully satisfying the feature request. At any rate, I think that everyone agrees it's a good idea.
So I propose a small deliverable starting point that will likely only be progress toward both of these proposals. And that is to just provide a direct link to the root duplicate question (the question that is not marked as a duplicate) on a closed duplicate question. It doesn't even have to muddle the sidebar, just a link below the closed message.


text:
Q: Configure Jenkins to take Artifact and Deploy Server Information I have configured Frontend and Backend of a project in Jenkins. Frontend using npm and Backend using maven as build tools. For repository management nexus has been configured. Now I want to do the deploy part of this project. For that I need to take artifact list and deploy server list into Jenkins UI. How can I do this? Output should be like below.

A: For this I used "Maven Metadata Plugin for Jenkins CI server". I got the answer for "Select Snapshot Version and Select Release Version".


text:
Q: How to do navigation between two views using JS view in openui5 for desktop application? As I am a newbie to openui5, I can't navigate from one view to another view using a button click.
How do I do that? I searched a lot and I got frustrated. While searching mostly I got the data related to sap.m(mobile) but I need code sample for sap.ui.commons(desktop) or any other link would be helpful.
Can anyone share some sample code for sap.ui.commons (Routing or tab navigation) not for sap.m?

A: Use Router of the SAPUI5 Application:
Sample code snippet :
var oRouter = sap.ui.core.routing.Router.getRouter("appRouter");
//can also use directly this.oRouter.navTo if you're extending scaffloding OR base controllers of SAP UI5.
oRouter.navTo("samplePattern",oContext,false);

A: There are different options for this:
1.Option:
is to use the sap.ui.ux3.Shell see here
2.Option:
using a Router
3.Option:
or by hiding a view and showing it like this:
sap.ui.getCore().byId('View1').setVisible(false);
sap.ui.getCore().byId('View2').setVisible(true);


text:
Q: WPF Caliburn Micro Conductors with Menu I'm currently using Caliburn Micro 2.0.2 trying to use Menu at the top of my ShellView for Conductor navigation. The first level of MenuItem works fine but the second level throws "No target found for method Select." exception.
ShellView code:
<Grid  xmlns:cal="http://www.caliburnproject.org"
    xmlns:cal2="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Menu VerticalAlignment="Top" ItemsSource="{Binding Items}">
      <Menu.Resources>
        <Style TargetType="MenuItem">
          <Setter Property="cal:Message.Attach"
                  Value="[Event Click] = [Action Select($DataContext)]" />
          <Setter Property="cal:Action.TargetWithoutContext"
                  Value="{Binding DataContext, RelativeSource={RelativeSource Self}}}"/>
        </Style>
        <HierarchicalDataTemplate ItemsSource="{Binding Items}"
                                   DataType="{x:Type cal2:Screen}">
          <TextBlock Text="{Binding DisplayName}"/>
         </HierarchicalDataTemplate>
      </Menu.Resources>
    </Menu>
    <ContentControl Grid.Row="1" cal:View.Model="{Binding ActiveItem}"/>
  </Grid>

ShellViewModel code:
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive
{
  public ShellViewModel(IEnumerable<IScreen> viewmodels)
  {
  //omitted for brevity.
  }
  public void Select(object datacontext)
  {
      var vm = datacontext as IScreen;
      if (vm != null && Items.Contains(vm))
      {
        ActivateItem(vm);
      }
   }
 }

The inner Conductors that have more view models have the same select method with the corresponding interface type. I can't figure out how to get the event to hookup. Please help.

A: I got it working. The binding to RelativeSource Self was the problem. I have now have the binding to the Element by Name. This also allows me to just have the one method on the shell.
ShellView code:
<Grid  xmlns:cal="http://www.caliburnproject.org"
    xmlns:cal2="clr-namespace:Caliburn.Micro;assembly=Caliburn.Micro">
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Menu x:Name="menu" VerticalAlignment="Top" ItemsSource="{Binding Items}">
  <Menu.Resources>
    <Style TargetType="MenuItem">
      <Setter Property="cal:Message.Attach"
              Value="[Event Click] = [Action Select($DataContext)]" />
      <Setter Property="cal:Action.TargetWithoutContext"
              Value="{Binding DataContext, ElementName=menu}"/>
    </Style>
    <HierarchicalDataTemplate ItemsSource="{Binding Items}"
                               DataType="{x:Type cal2:Screen}">
      <TextBlock Text="{Binding DisplayName}"/>
    </HierarchicalDataTemplate>
  </Menu.Resources>
 </Menu>
 <ContentControl Grid.Row="1" cal:View.Model="{Binding ActiveItem}"/>
</Grid>

ShellViewModel code:
public class ShellViewModel : Conductor<IScreen>.Collection.OneActive
{
  public ShellViewModel(IEnumerable<IScreen> viewmodels)
  {
  //omitted for brevity.
  }
  public void Select(object datacontext)
  {
      var vm = datacontext as IScreen;
      if (vm != null && Items.Contains(vm))
      {
         if (vm.IsActive)
           return;
         ActivateItem(vm);
         vm.Refresh();
      }
      else
      {
         var vm2 = datacontext as Screen;
         if (vm2 != null)
         {
           (vm2.Parent as IConductActiveItem)?.ActivateItem(vm2);
            vm2.Refresh();
         }
      }
   }
 }


text:
Q: I am using ffmpeg to stream a h264 encoded avi file to a player and the player supports only packetization mode 0 I am using ffmpeg to stream a h264 encoded avi file to a player and
the player supports only packetization mode 0 ( single NAL unit mode
). But ffmpeg always uses packetization mode 1 and sends FU-A nal unit
type, the player does not play the video on receiving a fu-a nal type
payload. It just displays a blank screen. I understand non-interleaved
mode supports both single NAL unit types (1-23) and fua, but how to
can I force ffmpeg to use only single nal unit type mode? Can some one
help me?

A: I'm assuming you mean H264 over RTP here. FFmpeg's RTP muxer can be forced to use mode 0 by using flag -rtpflags h264_mode0; though if you are seeing FU-A type (28) then chances are some NAL units can't fit single RTP packet and mode0 won't work.


text:
Q: hctreemap to hctreemap2 --> Could not find function "hctreemap2" I have tried to reproduce the one mentioned in the link  https://rpubs.com/jbkunst/hctreemap2. But getting error message as
"Error in hctreemap2(data = GNI2014, group_vars = "continent", size_var = "population") :    could not find function "hctreemap2". Also verified the dependencies but not sure what is missing. Please help!!!

A: The current version of highcharter, version 0.5.0, was published 2017-01-17 08:36:29,  as you can see from the documentation. hctreemap2 was proposed since then and is in development. It is not in highcharter as it is released on CRAN.  You could theoretically pull the code from github  if you wanted, it's in the dev repo under treemap5.R, and looks to be something they'll include in the 0.6.0 release.


text:
Q: NUnit Assert.Equals vs. Assert.AreEqual What is the difference between:

*

*Assert.Equals and Assert.AreEqual

*Assert.NotNull and Assert.IsNotNull

*...

?

A: Just read the documentation:
NUnit - ConditionAsserts

Two forms are provided for the True,
  False, Null and NotNull conditions.
  The "Is" forms are compatible with
  earlier versions of the NUnit
  framework, while those without "Is"
  are provided for compatibility with
  NUnitLite.

A: Assert.Equals is an object comparison
Assert.AreEquals is overloaded to compare (int,double, object) etc
Assert.NotNull and Assert.IsNotNul appear to be identical.
http://www.nunit.org/index.php?p=conditionAsserts&r=2.5.5


text:
Q: Expected value of number of tiles needed to fill up a given area I randomly thought of this question in the car: Given that you have a $100ft$ $*$ $150ft$ field and that $1.5ft$ $*$ $1.5ft$ tiles are randomly placed within the perimeter of the field with overlaps allowed, what is the expected value of the number of tiles needed to fill the area.
I thought it would be simple enough, but I tried everything and was not able to make any headway. Any thoughts?

A: The simple answer is that if the tiles are required to be placed entirely within the field, it will take an infinite number of tiles to cover the whole field.  The corners can only be covered if the tile is placed precisely over one point, which occurs with probability zero.
A harder question is if you allow the centers of the tiles to be anywhere within the field.  Then the corners are still four times less likely to be covered than center points by any given tile.  You can get a rough idea by covering the field with a $1.5 \times 1.5$ foot grid, which is about $67 \times 101$ locations.  Each location has a chance of about $1/(67\cdot 101)$ of being covered by a given tile.  We can now use a Poisson distribution to say the expected number of tiles covering a spot when we have placed $n$ tiles is $\frac n{6767}$ so each spot has a $e^{-\frac n{6767}}$ chance of being uncovered.  The chance that no spot is uncovered (ignoring correlations) is $(1-e^{-\frac n{6767}})^{6767}$.  If you want a chance of $p$ that no spot is uncovered, we do
$$(1-e^{-\frac n{6767}})^{6767}=p\\
6767 \log(1-e^{-\frac n{6767}})=\log p\\
e^{-\frac n{6767}}\approx -\frac {\log p}{6767}\\
-\frac n{6767}\approx \log\left(-\frac {\log p}{6767}\right)\\
n\approx -6767\log\left(-\frac {\log p}{6767}\right)$$
For $p=0.5$ you need $n\approx 62163$ and for $p=0.9$ you need $n \approx 74912$  Basically you need to cover the field about $10-12$ times deep to cover it all.

A: Here is an approach via Monte Carlo simulation.  It seems hard to write a program that keeps track of exactly what parts of the field that are covered, so we discretize (if that's a word) the problem by covering the field with a grid of points at 0.1 ft intervals, and we consider the field covered if all the grid points are covered.  So what we end up with is an approximate solution to an approximate version of the original problem.
With all those caveats in mind, here is the algorithm.  Cover the field with a grid of points at 0.1 ft intervals, from (0,0) to (100,150).  All the points are originally "uncovered". Generate a random X from 0 to 100 and a random Y from 0 to 150.  Mark all the grid points within the 1.5 ft square centered at (X,Y) as covered.  Repeat until all the grid points are covered.  Code in Python 2.7 follows:

    # 1 unit of measurement = 0.1 foot

import math
import random

def ndraws():
    "return the number of draws required to cover 1000 X 1500 grid"
    covered = [[False for j in range(1501)] for i in range(1001)]
    ncovered = 0
    ntrials = 0
    while ncovered < 1501 * 1001:
        ntrials += 1
        x = random.uniform(0, 1000)
        y = random.uniform(0, 1500)
        ilo = max(0, math.trunc(x-6.5))
        ihi = min(1001, math.trunc(x+7.5))
        jlo = max(0, math.trunc(y-6.5))
        jhi = min(1501, math.trunc(y+7.5))
        for i in range(ilo, ihi):
            for j in range(jlo, jhi):
                if not covered[i][j]:
                    covered[i][j] = True
                    ncovered += 1
    return ntrials

# set the random number seed, for reproducibility
random.seed(1234)
# run 100 trials and report the number of draws required in each trial
for i in range(100):
    print ndraws()

In 100 repetitions, the average number of 1.5 by 1.5 squares required was 127,220.  A 95% confidence interval is 123,435 to 131,006.

A: Maybe consider square regions $1.5 \times 1.5$ whose centers make grid with spacing $0.75$ apart. Then consider the probability of picking point inside, $\frac{9}{240000}$ then the repeated probabilities to fill the rectangle. Consider now as the $.75$ sides are generalized to any size.


text:
Q: Xamarin.Forms Asset Catalogue disappeared I have a Xamarin Forms project that had an Asset Catalogue full of images for my app.
I built the app this morning fine and ran on my test device.
I then changed the LaunchScreen.Storyboard file in my Resources folder (confirmed by source control that this is the only file that changed) and my asset catalogue has disappeared.
I tried adding a new one (in the hope I could re-add the images) but even the new one doesn't show under the dropdown (although it exists in the folder).
I reverted the change via source control and the app still won't build, and I can't figure out how to re-add my asset catalogue.

A: I have found the answer. I unloaded my iOS project from the Solution Explorer and opened the .csproj file and commented out "Assets.xcassets/Images.imageset/Contents.json" and reloaded the project


text:
Q: what join is caused by "and"? I have a localDB database that includes the following tables:
UserProfile, which contains:
UserId  UserName
1           Adam

webpages_Roles, which contains:
RoleID RoleName
1      user
2      admin

webpages_UsersInRoles, which has two columns (UserId, RoleId), and is blank.
I want a query to add a user by name into a role by name.
to figure out what to insert, if I run:
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles
WHERE UserProfile.UserName = 'Adam'
   OR webpages_roles.RoleName = 'admin';

I get this:
UserId  RoleId
1       2
1       1

which makes sense; it's a cross join.  But I basically just want to run two separate selects at once and stick them together.  I tried this:
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles
WHERE UserProfile.UserName = 'Adam'
  AND webpages_roles.RoleName = 'admin';

and it worked; I got UserId 1 and RoleId 2. but I don't understand that "and"; isn't it like comparing apples to oranges? shouldn't it be a syntax error? Is localDB actually running two selects and joining the results, perhaps by line number?

A: When you do this query:
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles
WHERE UserProfile.UserName = 'Adam' AND webpages_roles.RoleName = 'admin';

You are doing a cross join.  You should get in the habit of being specific about the cross join, and use cross join rather than ,.  In any case, this is equivalent to:
SELECT UserId, RoleID
FROM (select u.*
      from UserProfile u
      where u.UserName = 'Adam'
     ) cross join
     (select w.*
      from webpages_Roles w
      WHERE w.RoleName = 'admin'
     ) w

When doing a cross join you are creating a cartesian product -- each row from the first table is matched to all the rows in the other table.  The where clause then is a filter on this result set.
If you want to align data, that is harder.  Here is one method using SQL Server syntax:
SELECT UserId, RoleID
FROM (select u.*, row_number() over (order by (select NULL)) as seqnum
      from UserProfile u
      where u.UserName = 'Adam'
     ) u join
     (select w.*, row_number() over (order by (select NULL)) as seqnum
      from webpages_Roles w
      WHERE w.RoleName = 'admin'
     ) w
     on u.seqnum = w.seqnum

A: Whenever you select from multiple tables, you are actually implicitly joining the tables.
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles;

The above query would return something like:
UserId  UserName  RoleID RoleName
1           Adam  1      user
1           Adam  2      admin

So when you add the where clause:
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles
WHERE UserProfile.UserName = 'Adam' AND webpages_roles.RoleName = 'admin';

It only returns the rows where the UserProfile.Username is 'Adam' and webpages_roles.RoleName is 'admin'.

A: the reason that this is correct and not an error of any kind is the following.
When yo do
SELECT UserId, RoleID
FROM UserProfile, webpages_Roles

without a WHERE clause, what you get in standard SQL is the cartesian product of the relations, ie, UserProfile x webpages_Roles
which is in turn a realtion, in your case (as shown in DiscoInfiltrator's answer),
UserId  UserName  RoleID RoleName
1           Adam  1      user
1           Adam  2      admin

That means that this part of the query WHERE UserProfile.UserName = 'Adam'
  AND webpages_roles.RoleName = 'admin'; acts on a relation containing both the UserName and the RoleName attributes,
Hope this clarifies, cheers


text:
Q: Error while doing sort operation in python x=['Hello', 90, 8.9999, 4.6, 'DOG', 'CAT', 1]
x.reverse()

x
Out[109]: ['Hello', 90, 8.9999, 4.6, 'DOG', 'CAT', 1]

x.sort()

Error
Traceback (most recent call last):

  File "<ipython-input-110-42dad5a67ac3>", line 1, in <module>
  x.sort()

TypeError: '<' not supported between instances of 'int' and 'str'

why I am getting this error?

A: As you can see in the error, you can compare only things of the same type. You could go and try to modify the int/float/str types to be able to do such comparison, but messing with internal properties of built in types is a very bad idea.
What you can do, is to cast numbers to strings and then do sort. This will perform a lexicographically sort.
a = ['Hello', 90, 8.9999, 4.6, 'DOG', 'CAT', 1]
a_str = [str(e) for e in a]
a_str.sort()
a_str

will produce ['1', '4.6', '8.9999', '90', 'CAT', 'DOG', 'Hello']


text:
Q: Extracting comma separated values from String coming from HTTP post I would like extract comma separated values which I am getting from HTML post request.
Example:
****"file"; filename="TEST.csv"
Content-Type: application/vnd.ms-excel
RECEIVERID,RECEIVERSITE,SENDERID,EMAIL_TO
1000003884,PEPSICO LTD.,1005,ZZZ@company.com
1000003884,PEPSICO LTD.,1010,ABC@company.com
------WebKitFormBoundary5ADzaHQgUvmKoZPI
Content-Disposition: form-data; name="submit"
Submit
------WebKitFormBoundary5ADzaHQgUvmKoZPI--****

I want to extract only data starting from RECEIVERID,RECEIVERSITE.... to ,ABC@company.com by using regex.
Could you kindly help me with this?
Thanks in advance !!
Tanveer

A: Use String.split(delimiter) which will return you an array containing all String delimited by the specified delimiter.
See the doc about String for more informations:
Note that the first and last splitted String will contains text that you don't want so you may want to remove the part which is not formatted as VALUE,VALUE,VALUE before using the split method.

If you really want to use regex, you can do it this way (once again after removing the extra data):
String regex = "[\\n|^|,]*(.*?)[,|$|\\n]";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher("RECEIVERID,RECEIVERSITE,SENDERID,EMAIL_TO\n" +
                                  "1000003884,PEPSICO LTD.,1005,ZZZ@company.com\n" +
                                  "1000003884,PEPSICO LTD.,1010,ABC@company.com");

while (matcher.find())
    System.out.println(matcher.group(1));

A: ^[^,]*?(?=\b\w+,)|(.*,[^\n]*)

Try this.Grab the capture.Do not forget to add flags g and s.
See demo.
http://regex101.com/r/lS5tT3/84

A: If you use the anchors ^, $ in your regex then you need to enable  (?m) Multiline modifier.
String text = "****\"file\"; filename=\"TEST.csv\"\n" +
        "Content-Type: application/vnd.ms-excel\n" +
        "RECEIVERID,RECEIVERSITE,SENDERID,EMAIL_TO\n" +
        "1000003884,PEPSICO LTD.,1005,ZZZ@company.com\n" +
        "1000003884,PEPSICO LTD.,1010,ABC@company.com\n" +
        "------WebKitFormBoundary5ADzaHQgUvmKoZPI\n" +
        "Content-Disposition: form-data; name=\"submit\"\n" +
        "Submit\n" +
        "------WebKitFormBoundary5ADzaHQgUvmKoZPI--****";
final Pattern p = Pattern.compile("(?m)^[^,\\n]*(?:,[^,]*?)+?$");
final Matcher m = p.matcher(text);
while(m.find()){
    System.out.println(m.group(0));
}

Output:
RECEIVERID,RECEIVERSITE,SENDERID,EMAIL_TO
1000003884,PEPSICO LTD.,1005,ZZZ@company.com
1000003884,PEPSICO LTD.,1010,ABC@company.com

DEMO


text:
Q: Как конвертировать содержимое файла.txt для отображения внутри компонента Подскажите как обычно решается следующая проблема:
есть содержимое текстового файла, как нужно эти данные конвертировать, чтобы они корректно отобразились внутри компонента ?
fetch(fileNameOnServer)  //  http://localhost:3000/filedata12.txt
        .then(response => response.text())    // res.json()
        .then(
          (result) => {
              content = result // <-- Тут нужно выполнить конвертацию ???
          })
// -----------------------------------------------------
return (
      <div className='FilesRightContent'>
        {content}
      </div>
    );

Дело в том, что браузер этот файл отображает корректно. А у меня внутри компонента - каша (не соблюдается перевод строки ...

A: Положи текст в тег <pre> или примени соответсвующий css
white-space: pre;


text:
Q: jsPDF is not rendering img with url on the first page I have a html div with some img src url inside it. The img part looks like this:

I'm using jsPDF to generate the pdf:
new jsPDF('p', 'pt', 'a4', true).html(
      document.getElementById('printDiv'),
      {
        filename: 'print.pdf',
        image: { quality: 10, type: 'png' },
        html2canvas: {
          /*
          scale: 2,
          */
        },
        callback: function (doc) {
          doc.save();
        },
      }

However, it looks like the img only on the first page is not be showing. I guess img loading takes some time and happened after first page render done, I detected it by using html2canvas scale 2 so that the image pushed into 2nd page.

How can I fix the code to let the image on the first page being generated before pdf is rendered?

A: Wait with the jsPDF call until the image has loaded.


text:
Q: How do I access the Help on Exact Online functions for Excel functions when using Invantive Control? I am creating a number of reports using Invantive Control for Excel and I would like to have an overview of the available Excel functions for Exact Online (those starting with I_EOL_...)
Especially I am looking for an Excel function to retrieve the balance of a specific account per fiscal year such as they appear on the balance sheet.
Neither F1 nor Help menu does me provides me with the available Excel functions for Exact Online.
How can I access Help on the Exact Online functions?

A: The integrated Help of Invantive Control does not include the included Excel functions for Exact Online. However, you can determine the possibilities in several ways.
The easiest way after learning the function is to just type ahead and let Excel complete it for Invantive Control. For instance, enter I_EOL_DIV_NAME and then press CTRL+SHIFT+A to have Excel autocomplete the arguments:

The second way is to type ahead such as I_EOL_DIV_NAME and then press the function wizard and you get a list of parameters:

The most easy way is to first log on to Exact Online:
And then go to the Modeler ribbon and choose Building Blocks:

The formulas are scalar formulas, the reports are array formulas which use SQL.
Depending on which platform you are connected to, you will see different building blocks. So on Salesforce or Freshdesk there will be no Exact Online, unless you have a connection to both Salesforce and Exact Online.
All formulas on Exact Online start of with the division code which is the Belgium 'dossier' or Dutch 'administratie'. When not specified, it defaults to the last chosen division in the web frontend of Exact Online.
When you are connected to multiple Exact Online countries / data centers, you can add the alias to enable cross-country reporting, such as: =I_EOL_DIV_NAME("NUMBER@fr") for data from the French data center.
PS. The formula you are looking for is probably I_EOL_BAL_YEAR_CLOSE:


text:
Q: How to replicate a sheet using VBA Macro (not copy) replicate How would I replicate a sheet using VBA Macro but not use the VBA copy method?
So I want Sheet2 to look exactly like Sheet1 after.
I am new to VBA Macros so please guide me.

A: Here are couple of ways
WAY 1 Best way to do it
ThisWorkbook.Sheets("Sheet1").Copy _
After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)

Way 2
Sub Sample()
    Dim wsToCopy As Worksheet, wsNew As Worksheet

    On Error GoTo Whoa:

    Set wsToCopy = ThisWorkbook.Sheets("Sheet1")
    Set wsNew = ThisWorkbook.Sheets.Add

    wsNew.Name = "Copy of " & wsToCopy.Name

    wsToCopy.Cells.Copy wsNew.Cells

    Exit Sub
Whoa:
    MsgBox Err.Description
End Sub

NOTE:
In case you are using Excel 2003, then WAY 2 might be the best way depending on the data. Please SEE THIS


text:
Q: How to write unit test case to test secure attribute of session cookie I recently added a piece of code in a servlet which basically adds a 'secure' attribute to the session cookie.
   String encryptedSessionId = encryptionProxy.strongEncrypt(request.getSession().getId());
    response.setHeader("SET-COOKIE", "JSESSIONID=" + encryptedSessionId + "; secure");

And I want to write a Junit test case to check whether "secure" attribute is being added to session cookie or not.
I was trying to mock session, request and response object to write a test case but its not working as expected and throwing an NullPointerException
my test case,
    @Test
public void testMethod() {
    MockHttpServletRequest request = Mockito.mock(MockHttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    HttpSession session = new MockHttpSession(null, (String) request.getSession().getAttribute("secure"));

    //VcfoWelcomeOptInEnrollmentServlet vcfoWelcomeOptInEnrollmentServlet = Mockito.mock(VcfoWelcomeOptInEnrollmentServlet.class);

    //when(session.getAttribute("secure")).thenReturn("secure");

    //System.out.println(response.getHeader("SET-COOKIE"));

    when(response.getHeader("SET-COOKIE")).thenReturn("secure");
  }

I kept the test case as it is so that you can get an idea about the things that I tried so far.
I would like to know whats wrong with my approach? Also, What is the correct approach to write a successful unit test case.
Any help would be appreciated!
I am using Junit 4 and Mockito 2
error stack
java.lang.NullPointerException
at com.xxx.accountLink.vcfo.client.servlet.ServletTest.testMethod(ServletTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:316)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:97)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:300)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.evaluateStatement(PowerMockJUnit47RunnerDelegateImpl.java:107)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:288)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:87)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:50)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:208)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:147)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:121)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:123)
at org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:121)
at org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:59)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)


text:
Q: Dynamically accounting for dependencies I am having difficulty developing an algorithm for my application. The application needs to be very flexible in order to account for multiple devices and multiple styles.
Here is one of the rules for ONE of the devices:
Only for styles 1,2,3,8,9,10
If slope = I2t
  Range: 2-24
  Step 0.5
If slope = I4t
  Range: 1-5
  Step 0.5
If slope = Mod Inv
  Range: 0.1-5.0
  Step 0.1
If slope = Very Inv or Ext Inv
    Range 0.2-5.0
    Step 0.1

Ony for Styles 4,5,6,7
If slope = I2t
    Range: 2-24
    Step 0.5
If slope = I4t
    Range: 1-5
    Step 0.5
If slope = IEC-A
    Range: 0.05 - 1.00
    Step 0.05
If slope = IEC-B
    Range: 0.10 - 1.00
    Step 0.05
If slope = IEC-C
    Range: 0.20-1.00
    Step 0.05

Now I could code this up for this specific device, but there are multiple devices with a different set of statements. Currently I am reading in these values from a file. This allows me to update the number of devices the program supports without changing code and therefore reduces the maintence.
Any suggestions?

A: You can use table-way to save the input values and corresponding config settings and then just look in dictionary.
Something like this:
struct ConfigKey
{
     public readonly int Style;
     public readonly string Slope;
     public ConfigKey(int style, string slope)
     {
        this.Style = style;
        this.Slope= slope;
     }
     public override bool Equals(object obj)
     {
         if (!(obj is ConfigKey))
         {
             return false;
         }
         ConfigKey other = (ConfigKey)obj;
         return this.Style == other.Style && this.Slope == other.Slope;
     }

     public override int GetHashCode()
     {
         return Style.GetHashCode() ^ Slope.GetHashCode();
     }
}
struct Config
{
    String  Range {get; set;}
    Double Step { get; set; }
}
Dictionary<ConfigKey, Config> conf = new Dictionary<ConfigKey, Config>();

public Config GetConfig(int style, string slope)
{
    return conf[new ConfigKey(style, slope)];
}


text:
Q: Crop nan rows and columns of a matrix, but keep it square I have a square matrix with > 1,000 rows & columns. In many fields at the "border" there is nan, for example:
grid = [[nan, nan, nan, nan, nan],
        [nan, nan, nan, nan, nan],
        [nan, nan,   1, nan, nan],
        [nan,   2,   3,   2, nan],
        [  1,   2,   2,   1, nan]]

Now I want to eliminate all rows and columns where I only have nan. This would be the 1. and 2. row and the last column. But I also want to receive a square matrix, so the number of the eliminated rows must be equal to the number of eliminated columns. In this example, I want to get this:
grid = [[nan, nan, nan, nan],
        [nan, nan,   1, nan],
        [nan,   2,   3,   2],
        [  1,   2,   2,   1]]

I'm sure I could solve this with a loop: check every column & row if there is only nan inside and in the end I use numpy.delete to delete the rows & columns I found (but only the minimal number, because of getting a square).
But I hope anyone can help me with a better solution or a good library.

A: import numpy as np
nan = np.nan
grid = [[nan, nan, nan, nan, nan],
        [nan, nan, nan, nan, nan],
        [nan, nan,   1, nan, nan],
        [nan,   2,   3,   2, nan],
        [  1,   2,   2,   1, nan]]
g = np.array(grid)
cols = np.isnan(g).all(axis=0)
rows = np.isnan(g).all(axis=1)
first_col = np.where(cols==False)[0][0]
last_col = len(cols) - np.where(cols[::-1]==False)[0][0] -1
first_row = np.where(rows==False)[0][0]
last_row = len(rows) - np.where(rows[::-1]==False)[0][0] -1
row_len = last_row - first_row
col_len = last_col - first_col
delta_len = row_len - col_len
if delta_len == 0:
    pass
elif delta_len < 0:
    first_row = first_row - abs(delta_len)
    if first_row < 0:
        delta_len = first_row
        first_row = 0
        last_row += abs(delta_len)
elif delta_len > 0:
    first_col -= abs(delta_len)
    if first_col < 0:
        delta_len = first_col
        first_col = 0
        last_col += abs(delta_len)
print g[first_row:last_row+1, first_col:last_col+1]

Output:
[[ nan  nan  nan  nan]
 [ nan  nan   1.  nan]
 [ nan   2.   3.   2.]
 [  1.   2.   2.   1.]]

A: This works, zipping the indices of rows\cols is key so they always have the same length, hence preserving the squareness of the matrix.
nans_in_grid = np.isnan(grid)
nan_rows = np.all(nans_in_grid, axis=0)
nan_cols = np.all(nans_in_grid, axis=1)

indicies_to_remove = zip(np.nonzero(nan_rows)[0], np.nonzero(nan_cols)[0])
y_indice_to_remove, x_indice_to_remove = zip(*indicies_to_remove)

tmp = grid[[x for x in range(grid.shape[0]) if x not in x_indice_to_remove], :]
grid = tmp[:, [y for y in range(grid.shape[1]) if y not in y_indice_to_remove]]

Continuing on Mr E, solution, and then padding the results works also.
def pad_to_square(a, pad_value=np.nan):
    m = a.reshape((a.shape[0], -1))
    padded = pad_value * np.ones(2 * [max(m.shape)], dtype=m.dtype)
    padded[0:m.shape[0], 0:m.shape[1]] = m
    return padded

g = np.isnan(grid)
grid = pad_to_square(grid[:, ~np.all(g, axis=0)][~np.all(g, axis=1)])

Another solution, building on the other answer here. Significantly faster for larger matrixes.
shape = grid.shape[0]

first_col  = (i for i,col in enumerate(grid.T) if np.isfinite(col).any() == True).next()
last_col  = (shape-i-1 for i,col in enumerate(grid.T[::-1]) if np.isfinite(col).any() == True).next()
first_row = (i for i,row in enumerate(grid) if np.isfinite(row).any() == True).next()
last_row  = (shape-i-1 for i,row in enumerate(grid[::-1]) if np.isfinite(row).any() == True).next()

row_len = last_row - first_row
col_len = last_col - first_col
delta_len = row_len - col_len
if delta_len == 0:
    pass
elif delta_len < 0:
    first_row = first_row - abs(delta_len)
    if first_row < 0:
        delta_len = first_row
        first_row = 0
        last_row += abs(delta_len)
elif delta_len > 0:
    first_col -= abs(delta_len)
    if first_col < 0:
        delta_len = first_col
        first_col = 0
        last_col += abs(delta_len)

grid =  grid[first_row:last_row+1, first_col:last_col+1]

A: Here is a shorter way. It works by scanning the main diagonal, removing row+column which are all nan, and then doing the same for the secondary diagonal:
import numpy as np
nan = np.nan
grid = [[nan, nan, nan, nan, nan],
        [nan, nan, nan, nan, nan],
        [nan, nan,   1, nan, nan],
        [nan,   2,   3,   2, nan],
        [  1,   2,   2,   1, nan]]
g = np.array(grid)
for i in [1, 2]:
    cols = np.isnan(g).all(axis=0)
    rows = np.isnan(g).all(axis=1)
    main_diagonal = np.logical_not(cols & rows)
    ind = np.nonzero(main_diagonal)[0]
    main_diagonal[ind[0]:ind[-1]+1] = True  # do not remove inner row/col
    removed_main_diag = g[main_diagonal][:, main_diagonal]
    g = removed_main_diag[:][::-1]
print g

Output:
[[ nan  nan  nan  nan]
 [ nan  nan   1.  nan]
 [ nan   2.   3.   2.]
 [  1.   2.   2.   1.]]


text:
Q: Find a function $ f : R^2 → R $ such that $ f(λv) = λf(v) $, $\forall \lambda \in R, v ∈ R^2$, yet $f$ is not linear.
Find a function $ f : R^2 → R $ such that $ f(λv) = λf(v) $, $\forall v ∈ R^2$, yet $f$ is not linear.

I've been at this for ages, and can't seem to find a single function. I've tried using all general functions such as trigonometric, exponents, etc. Any ideas?

A: Hint The condition just means that $f$ is linear on each $1$-dimensional subspace of $\mathbb{R}^2$, but imposes no further conditions, so its behavior on one subspace need not have any connection with its behavior on another.

 For example, we can define $f(x, y)$ to be $x$ on lines of positive slope, (equivalently, in the open first and fourth quadrants, that is, where $x y > 0$) to be and $0$ elsewhere.

A: This function is determined by its values on the unit circle,  it grows linearly on each ray emanating from $(0,0)$, and we have to take care that $f(-{\bf v})=-f({\bf v})$. Therefore we may start with an arbitrary $2\pi$-periodic function $g:\>\phi\mapsto g(\phi)$ satisfying $g(\phi+\pi)=-g(\phi)$. The (complex) Fourier series of such a function contains only terms of odd frequency:
$$g(\phi)=\sum_k c_{2k+1}e^{(2k+1)i\phi}\ .$$
A simple nontrivial example would be $g(\phi):=\sin(3\phi)$. Given such a $g$ we can define
$$f({\bf v}):=|{\bf v}|\> g\bigl(\arg{\bf v}\bigr)\quad({\bf v}\ne{\bf 0}),\qquad f({\bf 0}):=0\ .$$


text:
Q: Sql Server Cursor with exec xp_create_subdir I'm trying to loop through all existing accounts on a SQL Server DB and create individual account folders using xp_create_subdir. However, I know what I have is not working because I'm trying to pass a variable as part of the parameter. This is my code:
declare @id int

declare crsr cursor LOCAL FAST_FORWARD for

select  Id
from AccountModels
where Active = 1
and Id in (select Account_Id from AccountPhotoModels)
order by Id

open crsr
fetch crsr into @id

While (@@fetch_status = 0)
begin

   exec master.dbo.xp_create_subdir 'C:\inetpub\wwwroot\media\images\accounts\' + @id

fetch crsr into @id
end
close crsr
deallocate crsr

Does anyone have an idea how to call that system SP within a cursor as I'm trying to do above?

A: Just assemble the value you want to pass as a separate step:
...
declare @path varchar(max)
open crsr
fetch crsr into @id

While (@@fetch_status = 0)
begin
   set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + @id
   exec master.dbo.xp_create_subdir @path

fetch crsr into @id
end
close crsr
deallocate crsr

For each parameter, you can pass a variable or a value - but you can't compute an expression to obtain that value.

A: As long as @id is not varchar (but an int) you must also do this change:
FROM:
set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + @id

TO:
set @path = 'C:\inetpub\wwwroot\media\images\accounts\' + Cast(@id as varchar)