text:
Q: What does -cp mean in the terminal when running a .jar file? I have to get some kinks out of a shell script for work, and one of the line looks like this:

A: -cp: this is the classpath
This is the set of classes that are used when running a specific class.
In your example; OrganT.Tune.Mix OrganT must be a class in the classpath (in this case, inside the OrganT.jar

A: Read the documentation, can be found here

A: Just a hint - under linux and mac you can use the
man <command goes here>
comman in the terminal/shell to display all parameters and usage information available for the specific command.

A: -cp stands for classpath. The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes.
java -classpath .;YourJarFile.jar

I think you want to run a script for including the class path and execute the jar.

*

*To do this in any text editor type java -jar YourJarFile.jar and save it, with extention (anyName.sh) assuming you have got linux flavour. Make it executable using the command chmod 775 anyName.sh

*For windows type java -jar YourJarFile.jar, and save it with extention (anyName.bat)


text:
Q: Office Open XML - Freeze panes in Excel I use datatables and generate an Excel file, with customizations of the output. See fiddle here:
https://jsfiddle.net/uo867xbm/
in the row 19 I append the  part to freeze the header and the first column :
var freezePanes = '<sheetViews><sheetView tabSelected="1" workbookViewId="0"><pane xSplit="1" ySplit="1" topLeftCell="B2" activePane="bottomRight" state="frozen"/></sheetView></sheetViews>';
This works great when opening the file in LibreOffice but Excel says that the file is damaged. The  part seems conform to the OpenXML standard.

A: Excel is fussy about the order of elements in the XML. In your file you have cols and sheetData before sheetViews but according to the ECMA spec sheetViews should be before the other two:
<xsd:complexType name="CT_Worksheet">
    <xsd:sequence>
    <xsd:element name="sheetPr" type="CT_SheetPr" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="dimension" type="CT_SheetDimension" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="sheetViews" type="CT_SheetViews" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="sheetFormatPr" type="CT_SheetFormatPr" minOccurs="0" maxOccurs="1"/>
    <xsd:element name="cols" type="CT_Cols" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element name="sheetData" type="CT_SheetData" minOccurs="1" maxOccurs="1"/>

It looks like you have a similar issue with your fonts. The expected order there (for the elements you have) is name, color then sz but you have sz, name then color.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing the default SQL developer icon [Applications] Note below solution
The following answer is a way of changing the default sqldeveloper icon into something more exciting and less out of place within the sharpness and sleekness of the Ubuntu interface.

A: This process assumes you have installed SQL developer already and have created the desktop shortcut to expose SQL dev onto the applications menu.
cd /usr/share/applications/

The below was added to the sqldeveloper.desktop file etcetera.
[Desktop Entry]
Exec=sqldeveloper
Terminal=false
StartupNotify=true
Categories=GNOME;Oracle;
Type=Application
Icon=/opt/sqldeveloper/icon.png
Name=Oracle SQL Developer

Below is the default icon which comes with the SQL package is blurry and unappealing.

Step 1: Download a new icon of your choice, preferably one with an alpha background or in other words set to transparent.
Step 2: Locate the position of the original icon using the following terminal commands:
cd /opt/sqldeveloper/ && ls -l

Step 3: Either remove the original icon named icon.png or copy the new downloaded png file to the sqldeveloper directory using:
sudo cp Pictures/icon_2.png /opt/sqldeveloper/

[change the new icon name to avoid confusion]
Step 4: Remove the file named icon.png if you kept it using:
sudo rm icon.png

then rename the new file to icon.png
mv icon_2.png icon.png

Finally check the application menu after restarting Ubuntu


text:
Q: ImageIO does not save screenshots I am trying to get a screenshot of my desktop and save it in specific folder, for this purpose, I wrote following method:
class Test(){
     public static String screenshot(String outDir){
            try {
                Robot robot = new Robot();
                String format = ".png";
                String fileName = String.valueOf(System.currentTimeMillis()) + format;
                Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
                BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
                ImageIO.write(screenFullImage, format, new File(outDir + fileName));
                System.out.println("Success");
                return outDir + fileName;
            } catch (AWTException | IOException e) {
                e.printStackTrace();
            }

            return null;
        }
}

I was planning to use the code like so:
Test.screenshot("C:\\temp\\");

So the magic is it does not write the screenshot file in the specific folder, but if I remove file extension and explicitly hardcode the name of the file it writes the result.
However, this code works:
public static String screenshot(){
        try {
            Robot robot = new Robot();
            String format = "jpg";
            String fileName = "XXX." + format;
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
            ImageIO.write(screenFullImage, format, new File("C:\\temp\\" + fileName));
            System.out.println("Success");
            return outDir + fileName;
        } catch (AWTException | IOException e) {
            e.printStackTrace();
        }

        return null;
    }

What am I doing wrong here?

A: I have seen the javadoc. The problem is about the formatName, as doc say: formatName - a String containg the informal name of the format. => means that your format should only contain name, not include the dot (.). So that's why your hardcode run because your hardcode using the correct formatName


text:
Q: UICollectionView How to find the row that a cell ends up in So, I have a tvOS app where I have a UICollectionView. I'm able to use the
following delegate callback to the the IndexPath of the next focused cell.
override func collectionView(didUpdateFocusIn context: ...)

The CollectionView has one Section and n number of cells that fall into it. So, when I get an IndexPath of [0,8] all that tells me is that it's the 9th item from the left. But, the first row only has 8 cells, so in reality its the first item on the left side of the second row.
How do I determine what row it's actually rendered on?

A: Can you show your code, the behavior, and the desired behavior?
Also a screen shot will help.
If I understand your question correctly...
What determines the row the cell appears up on are these factors:
 1. The size of the view
 2. The size of the cell
 3. collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt
 4. The space between each cell
An example is, if you have a portrait orientation, with a view width of 800, and 8 cells width 100 each, and space between each cell is 10, your 8th cell will be on the second row.
One solution is to account for the width of the cell based on the (view.frame.width / numOfCells on each row) and account for the space between each cell.


text:
Q: Drools insertLogical on Java LinkedList I have a LinkedList created (instantiated) in Java, which have several nodes (items).
This list is also used in Drools, and to be exactly, modified by Drools. I need to insert a new item in the list, but this insertion must be only temporary. I do not know when the removal of this item could occur, so I'm obliged to use insertLogical statement (right?).
This is my code, i add three "Nodo" item in the list called "lista". Nodo is the class that follow, which has the constructor and the set/get method:
package com.sample;

public class Nodo {

    private int valore;

    public Nodo(){}

    public Nodo(int valore){
        this.valore=valore;
    }

    public int getValore() {
        return valore;
    }

    public void setValore(int valore) {
        this.valore = valore;
    }

}

this is java Main class instead, which call fireAllRules():
package com.sample;

/**
* This is a sample class to launch a rule.
*/

import java.util.LinkedList;
import java.util.List;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class DroolsTest {

public static final void main(String[] args) {
    try {
       // load up the knowledge base
       KieServices ks = KieServices.Factory.get();
       KieContainer kContainer = ks.getKieClasspathContainer();
       KieSession kSession = kContainer.newKieSession("ksession-rules");

       List<Nodo> lista = new LinkedList();
       Nodo n1 = new Nodo(11);
       Nodo n2 = new Nodo(12);
       Nodo n3 = new Nodo(13);

       lista.add(n1);
       lista.add(n2);
       lista.add(n3);

       kSession.insert(lista);
       kSession.fireAllRules();

       for(Nodo nodo : lista){
           System.out.println( nodo.getValore());
       }

       System.out.println( "End");

    } catch (Throwable t) {
        t.printStackTrace();
    }
}
}

The output of Main class is

11
  12
  13
  50

but what i really wanted was only

11
  12
  13

because the "50" value is inserted logically in Drools and then immediately removed. The "hello" message is not printed, because the 50 item isn't in the list anymore. (correctly, because the list items was removed).
The Drools rule file is that which follows:
rule "Rule 1"
no-loop true
when
    $l : LinkedList(get(0).getValore() == 11)
then
    Nodo a = new Nodo(50);
    $l.add(0,a);
    insertLogical($l);
end

rule "Rule 2"
no-loop true
when
    $l : LinkedList(get(0).getValore() == 50)
then
    modify($l){remove(0)};
end

rule "Rule 3"
when
    $p: Nodo(valore==50)
then
   System.out.println("hello");
end

I tried this way, and I established the list item is correctly retracted from Drools working memory but the item on the list on Java side still continues to exists.
I would like to know why the list item remains, how to remove it (without explicitly destroying).
Is this a Drools problem with LinkedList or I have not correctly understood insertLogical usage?
I also tried to use LinkedList items defined not n the java.util package, but in the drools one "org.drools.core.util.LinkedList" with some error compilation.
What is the correct solutions ? Thanks

A: There is Java: with objects of all kinds. They have their methods, and with collections (like LinkedList) you can call methods to change the their composition, adding or removing elements.
There is Drools: it has a big pool of Facts (Working Memory, WM), each of which is a Java object. Promotion to a Fact is done by an insert operation, and a Fact can be demoted to its nothing-but-POJO existence by a retract: automatically or explicitly.
No add to a collection has any effect on the added object being or not being a Fact. Reciprocally, neither insertion into or removal from working memory changes anything in the Java-ish existence of the object.
Moreover, a list is one object, and its elements are other objects. Each object is jealously safeguarding its own status as a Fact, and a collection doesn't care two hoots about any of its elements becoming promoted or demoted - and you can bet that a list element couldn't care less about its container being in the WM or not.
Later
Rule 1 is weird: its right hand side destroys the truth of the left hand side, due to the addition of a Nodo(50) at index 0. There is no modify or update on the list object, and therefore the logically inserted fact isn't retracted right away. Even weirder: the RHS inserts the list object that is already in WM.
Rule 2 is never executed, because the add in Rule 1 is not signalled to the Engine.
Rule 3 is never executed, because the Nodo(50) is never inserted as a Fact anyway.


text:
Q: How to disable auto-backup for a library project distributed as a third-party SDK? I'm currently working on an android library project (aar) that is meant to be used by third-parties as an SDK.  Internally, I use SharedPreferences to store some data specific to my library:
SharedPreferences prefs = context.getSharedPreferences("my.library.prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("my.library.data", "test_data");
editor.apply();

On Android Marshmallow and up devices, I notice that even after uninstalling and re-installing the host application (that uses my library), some data that I had previously saved are restored automatically.  Digging through stackoverflow, I find out that on newer devices, the automatic backup restores pretty much everything stored in the private sandbox including SharedPreference files.
What is the most appropriate way to exclude my library's files from the automatic backup behavior, keeping in mind that users of my library may have their own files that they want to be backed up?

A: Unfortunately, there's not a good answer for this.
You can add android:fullBackupContent="@xml/backup_rules" to the <application> tag of your library, just like for an application (as defined here), which will work on its own. However, if the consumer of your library defines their own backup rules, yours will get overwritten during manifest merging.
The way I'd hoped you could do this was to define a string for the path in your library (<string name="sharedprefs_name">my.library.prefs.xml</string>), and then tell your consuming application to reference that in their backup rules. Unfortunately, it appears that you can't use a string reference in that file. <exclude domain="sharedpref" path="@string/sharedprefs_name"/> doesn't resolve correctly.
The best you can do is hardcode the path in your readme and ask your consumer to exclude it.


text:
Q: Derby.log output file does not get populated correctly I'm trying to look at the query plan generated by my database, but derby.log is not getting populated with query info. It contains things like:

*

*os.name=Windows 8.1

*derby.system.home=null

*derby.database.classpath=''

I'm using the following to attempt to populate it:
CallableStatement queryPlan = conn.prepareCall
    ("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(?,?)");
queryPlan.setString(1,"derby.language.logQueryPlan");
queryPlan.setString(2,"true");
queryPlan.execute();
queryPlan.close();

A: The Derby Reference manual says about derby.language.logQueryPlan:

This property is static; if you change it while Derby is running, the
  change does not take effect until you reboot.

So it is really intended that you set this it the derby.properties or the command line when you start Derby.


text:
Q: How can I re-order my percent stacked barchart in R based on descending stack segment height? I'm trying to order the bars of my percent stacked barchart in R based on descending stack segment height.
R automatically sorts my categorical data in alphabetical order (in both the barchart and its legend) but I'd like the data to be ordered so to have the biggest bars (the ones with the greatest stack segment height) on top of the barchart and the smallest at the bottom, in a descending manner.
I don't know how to do this because I cannot manually set a specific order with a vector prior to using ggplot2: my dataset is quite big and I need it to be ordered based on total field area (a quantitative variable that changes for every single city I'm considering).
Does anyone know hot to help me?

A: You need to set your categorical variable as an ordered factor. For example, using the iris data, the default is for an alphabetical x-axis:
iris%>%
  ggplot(aes(Species,Petal.Length))+
  geom_col()

Using fct_reorder (from forecats, included in the tidyverse), you can change a character variable to a factor and give it an order in one step. Here I change the order of the x-axis such that is order by the average sepal width of the petal.
iris%>%
  mutate(Species=fct_reorder(Species,Sepal.Width,mean))%>%
  ggplot(aes(Species,Petal.Length))+
  geom_col()

A: st_des_as %>%
  mutate(COLTURA=fct_reorder(COLTURA,tot_area),.desc=F) %>%

  ggplot(aes(x=" ", y=tot_area, fill=COLTURA)) +
  geom_bar(position= "fill", stat="identity") +
  facet_grid(~ZONA) +
  labs(x=NULL, y="landcover (%)") +
  scale_y_continuous(labels=function(x) paste0(x*100)) +
  scale_fill_manual(name="CROP TYPE",values=colours_as) +
  theme_classic() +
  theme(legend.key.size = unit (10, "pt")) +
  theme(legend.title = element_text(face="bold"))
  geom_col()

here are some of my data, as you can see they are numerical values divided by region (ZONA) and crop type (COLTURA)

and here are the first graphs: the first one from the left is correctly sorted while the other three ones are sorted not following their bars' height but rather following the same sorting of the first graph, no matter the dimension of their own bars


text:
Q: The Parse current user is not deleted after app reinstalled Users reported to us that they uninstalled the app, then reinstalled it and they were immediately transferred to the Home screen, instead of the Login screen. The thing is, since they don't login they don't have a Session token and hence, they can't call cloud functions!
Here's my check:
if (ParseUser.getCurrentUser()==null) {
    // show login screen
}
else {
    // show home screen
}

Here's an email we just got

I have managed to fix the problem. I had to clear all my temporary data for the application and reinstall it. After that it worked like it should. So the problem was with some temporary saved data in my device.

Any idea what's going on?

A: In AndroidManifest under the application tag, there is an android:allowBackup
flag that was responsible for this. as the documentation said:

android:allowBackup Whether to allow the application to participate in
  the backup and restore infrastructure. If this attribute is set to
  false, no backup or restore of the application will ever be performed,
  even by a full-system backup that would otherwise cause all
  application data to be saved via adb. The default value of this
  attribute is true.

For your problem, you must make this false.


text:
Q: Problem with adduser over SSH script depending on OS distro Hi this script is saying there is an issue at:
bash: -c: line 0: syntax error near unexpected token `then'
bash: -c: line 0: `sudo -i if sudo cat /etc/*-release | grep Ubuntu; then echo "Ubuntu Server";'

But I cant see whats wrong with the syntax
#!/bin/bash -x

echo Enter server IP:
read server

scp /home/Zenoss/.ssh/authorized_keys ******@$server:/home/******

sshpass -p ********  ssh -t ******@$server sudo -i 'if sudo cat /etc/*-release | grep Ubuntu; then echo "Ubuntu Server";
sudo groupadd --gid 7000 zenoss;
sudo adduser --uid 7000 --gid 7000 --disabled-password --gecos "" zenoss;
sudo mkdir /home/zenoss/.ssh;
sudo mv /home/******/authorized_keys /home/zenoss/.ssh/;
sudo chmod 700 /home/zenoss/.ssh;
sudo chmod 600 /home/zenoss/.ssh/authorized_keys;
sudo chown -R zenoss /home/zenoss/.ssh;
sudo chgrp -R zenoss /home/zenoss/.ssh;
fi;

if sudo cat /etc/*-release | grep CENTOS; then echo "Centos Server";
sudo groupadd --gid 7000 zenoss;
sudo useradd -u 7000 -g 7000 zenoss;
sudo mkdir /home/zenoss/.ssh;
sudo mv /home/******/authorized_keys /home/zenoss/.ssh/;
sudo chmod 700 /home/zenoss/.ssh;
sudo chmod 600 /home/zenoss/.ssh/authorized_keys;
sudo chown -R zenoss /home/zenoss/.ssh;
sudo chgrp -R zenoss /home/zenoss/.ssh;
fi;

if sudo getenforce | grep Enforcing; then echo "SElinux is enforcing"; else echo "Selinux is not enforcing"; fi;
if sudo getenforce | grep Enforcing; then sudo restorecon -R -v /home/zenoss/.ssh; fi;
exit'

Any help will be massively appreciated.

A: I managed to get it working by changing the script to 'sudo -i; rest of script' rather than sudo -i 'rest of script'


text:
Q: Angularjs && Google maps Привет!
Есть такой контроллер, он добавляет маркеры на Google карту
angular.module('frontApp')
 .controller('GoogleMapController', function ($scope) {
   $scope.cities = [];

 var mapOptions = {
   zoom: 6,
   center: new google.maps.LatLng(48.379433, 31.16558)
 };

 $scope.map = new google.maps.Map(document.getElementById('map'), mapOptions);
 $scope.markers = [];
 var infoWindow = new google.maps.InfoWindow();

 var createMarker = function (info) {
   $scope.marker = new google.maps.Marker({
     map: $scope.map,
     position: new google.maps.LatLng(info.lat, info.long),
     title: info.place
   });

   $scope.marker.content = '
' + info.desc + '
' + info.lat + 'E,' + info.long + ' N,
';

   google.maps.event.addListener($scope.marker, 'click', function () {
    infoWindow.setContent('
' + $scope.marker.title + '
' +
      marker.content);
     infoWindow.open($scope.map, $scope.marker);
   });

   $scope.markers.push($scope.marker);
 };

 $scope.openInfoWindow = function (e, seletedMarker) {
   e.preventDefault();
   google.maps.event.trigger(seletedMarker, 'click');
 };

 $scope.autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocompete'));
 $scope.autocomplete.bindTo('bounds', $scope.map);

 google.maps.event.addListener($scope.autocomplete, 'place_changed',
   function () {
     var place = $scope.autocomplete.getPlace().address_components[0].long_name;
     var desc = $scope.autocomplete.getPlace().formatted_address;
     var lat = $scope.autocomplete.getPlace().geometry.location.lat();
     var long = $scope.autocomplete.getPlace().geometry.location.lng();

     var newCity = {
       place: place,
       desc: desc,
       lat: lat,
       long: long
     };

     $scope.cities.push(newCity);

     for (var i = 0; i < $scope.cities.length; i++) {
       createMarker($scope.cities[i]);
     }

   });

});
В моем коде массив $scope.cities обновляется только внутри функции google.maps.event.addListener($scope.autocomplete, 'place_changed'... А снаружи он пустой.
Отсюда вопрос: "Как добавлять города, введенные через автокомплит, в массив cities?"


text:
Q: ACS712 Low Current Sensor Before I begin, just to let you know that I'm new to electrical engineering, in case that my question sound weird to you, but here's my problem.
I bought few days ago ACS712 Low Current Sensor and hooked up everything on my Arduino board, but the values that I'm getting are weird.
From my understanding, the Vout from that sensor without any load should be 2.5v, right? And if there's any load, it should change.
However, I'm getting different values on Vout while I read them in my code (from 505 to 520) (as raw input without any analog to digital conversion). Is that normal? I thought I will get stable (constant) input value if there's no load?
How can I tweak that and how to convert it properly from that number into milliamps?

A: You would use a set of formulas like this:
$${ADC\_Value \over ADC\_MAX} \times ADC\_Volt\_Scale = ADC\_Voltage$$
You can see that this makes a ratio out of the read ADC value and the maximum value, then scales it by the maximum voltage that the ADC can read (this works for ADCs that start at 0V and go to some max voltage only!)
Now that you have the output voltage, you can offset it to zero, and divide the mV/mA conversion value:
$$(ADC\_Voltage - 2.5V) \div mV\_per\_mA\_CONST = Curent\_in\_mA$$
That should work in your case. If you have divider circuitry or other voltages in play, you might have to modify the formula to get what you want.


text:
Q: Get string from another class and set it to TextView I have LoginActivity and I declared into this class string String currentName. I have a WelcomeActivity class and I would like to set this currentName in a TextView. How to do it? Now that I have the in WelcomeActivity class declare LoginActivity loginActivity and set it this way, but that doesn't work:
TextView welcome;
welcome = (TextView) findViewById (R.id.tvWelcome);
welcome.setText (loginActivity.currentName);
Thanks for help ;)

A: Instead of keeping currentName as global variable you can send data though intent and get it in welcome activity
Create intent in the loginActivity and send the current name.
Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
intent.putExtra("currentNameId", currentName);
startActivity(intent);

In the oncreate of welcome activity get the data that was sent.
String currentName = getIntent().getStringExtra("currentNameId");

And then set it to the textview
TextView welcome;
welcome = (TextView) findViewById (R.id.tvWelcome);
welcome.setText(currentName);

A: Create a Singleton class
public class MySingleton {

    private static MySingleton mySingleton;

    private String currentName;

    public static synchronized MySingleton getInstance() {
        if (mySingleton == null)
            mySingleton = new MySingleton();
        return mySingleton;
    }

    public String getCurrentName() {
        return currentName;
    }

    public void setCurrentName(String currentName) {
        this.currentName = currentName;
    }
}

From The LoginActivity set value to Singleton class
MySingleton singleton =  MySingleton.getInstance();
singleton .setCurrentName("<Name to Set>");

From the second WelcomeActivity access the value
MySingleton singleton =  MySingleton.getInstance();
singleton.getCurrentName();

A: In LoginActivity just create static String
   public static String currentName= "test";

And in WelcomeActivity do like this
   welcome.setText(currentName);

Note-: but better way to pass values one activity to another activity using Intent.
// LoginActivity
  public void sendDataToNextActivity(View view) {
    Intent intent = new Intent(this, WelcomeActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String strData= editText.getText().toString();
    intent.putExtra("data", strData);
///OR  intent.putExtra("data", "test");
    startActivity(intent);
}

// WelcomeActivity
Receive data in onCreate
 Bundle extras = getIntent().getExtras();
        String getDataFromFirstActivity;
        if (extras.containsKey("data") && extras != null) {
                getDataFromFirstActivity= extras.getString("data");
                welcome.setText(getDataFromFirstActivity);
            }

Start Intent-
https://developer.android.com/training/basics/firstapp/starting-activity.html
https://developer.android.com/reference/android/content/Intent.html

A: Instead of static variable ,
you can use Intent,
Intent intent = new Intent(LoginActivity.this, WelcomeActivity.class);
intent.putExtra("currentNameId", "here add your text which you want to display");
startActivity(intent);

than in welcomeActivity,
in onCreate method,
String currentName = getIntent().getStringExtra("currentNameId");

now set text in your textview,
welcome.setText(currentName);

A: Storing a static variable in your LoginActivity and try to access it from another acitivty is not a good idea. You have to consider the activity lifecycle and the fact that the activity could potentially be destroyed by the system, and also the memory leak it will cause etc.
You can read some more on lifecycles here, https://developer.android.com/guide/components/activities/activity-lifecycle.html
What you want to do is to pass the value as an extra in the intent, and then retrieve it from the intent in your second activity.
In your LoginActivity when your user have entered correct credentials and you're about to start your WelcomeActivity you want to create the intent for starting the second activity like this (adding the name as an extra):
Intent welcomeIntent= new Intent(context, WelcomeActivity.class);
intent.putExtra("extra_current_name", currentName);
startActivity(welcomeIntent);

and then in your WelcomeActivity you retrieve that in your onCreate() method.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String currentName = getIntent().getStringExtra("extra_current_name");
    TextView welcome = (TextView) findViewById (R.id.tvWelcome);
    welcome.setText(currentName);
}

Read up some about passing data between activities and building intents here, https://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent

A: //To send data to 2nd activity call this function or set it to button onclick.
public void onclick_next(View view) {
        Intent i = new Intent(this,2nd_activity_name.class);
        i.putExtra("username",username); //2nd username has the text that you want to send.
        startActivity(i);
    }

//When you are in second activity,  To get send data from 1st activity, use this codes inside the oncreate method.
Bundle logonData = getIntent().getExtras();
      String username = logonData.getString("username");
      final TextView usernameText = (TextView) findViewById(R.id.textViewUser);
      usernameText.setText(username);

A: You definitely should not store an instance of you activity, because it can and will be recreated at some point by OS.
The simplest solution is to declare currentName as static member.
public static String currentName;

Afterwards you can access it by classname:
welcome.setText(LoginActivity.currentName);

If you open WelcomeActivity from LoginActivity, you can also use extras.
intent.putExtra(SOME_TAG, currentName);
getIntent().getStringExtra(SOME_TAG);

I guess the best solution will be to store this string somewhere in the database, preferences or atleast some Singletone class.

A: I make my string to public static String currentName and its work. Thanks guys :)


text:
Q: await vs then - accessing returned values Trying to get my head around the subtle (sic) differences between await vs then. I've read most of the posts here, so I get that async functions return a promise.
Using await (with an async function) returns a var that can be used downstream, but using .then (with an async function) does not (at least for me) likewise return a var that can be accessed outside the then clause), since it is processed asynchronously and downstream references are processed synchronously - outside the .then clause, the var (in my example) is undefined.
I understand why my example is behaving the way it does, but my question is - is there a way to use .then with an async function, such that the result can be accessed downstream of the function execution?
let x, y, z;

async function foo ( num ) {
    return Promise.resolve ( num + 10 );
}

async function bar (num) {
    return num + 20;
}

async function baz (num) {
    return Promise.resolve ( num + 30 );
}

async function main (){
    x = await foo(10);
    console.log('foo returned (after await): '+ x); // no hay problema!

    y = await bar (10);
    console.log('bar returned (after await): '+ y); // no hay problema!

    baz (10)
        .then ( (result) =>{
            z = result;
        });
    console.log('baz returned: '+ z); // undefined...executes before .then completes...
}

main();

Update
I guess there were some questions about my objective in using x and y outside a set of chained then  clauses. Here is a (hopefully more) real-world example of what I'm trying to do:
In the code below, schemaValidation can be used in any of the routes within an express app (said routes are initialized in initAppRouter):
// main
    const schemaDB = await initAppDBSchema ();
    const schemaValidation = await initAppDataValidationSchema();
    const Author = mongoose.model ( 'Author', schemaDB );
    let author: any;
    let authors: any;
    await initAppDB ();
    await initAppRouter ();

    async function initAppDataValidationSchema () {
        return joi.object ( {
            authorName: joi.string ()
                .min ( 3 )
                .max ( 30 )
                .required (),
etc...
        } );
    }  ...

A:
is there a way to use .then with an async function, such that the
result can be accessed downstream of the function execution?

No. There's no reliable way to do that.
Moreover, you shouldn't need to do that in the first place. Whatever you want to do with the data after the promise chain can be done inside the callback function, once the data is available.

Using await (with an async function) returns a var that can be used
downstream

Right but that's only possible because of how async-await is transformed in the promise chain. That "downstream" code is actually wrapped in a callback function of then() method.

A: there is no way to make a promise behave synchronously like you desire. The only way is to move your code dependent of the promise inside the then block and continue there.
baz (10)
        .then ( (result) =>{
            z = result;
            console.log('baz returned: '+ z); // undefined...executes before .then completes...
        });

A: You have to either wait for every promise to resolve with await so code will behave in non async manner, or chain callback with then
await baz (10)
        .then ( (result) =>{
            z = result;
        });

    console.log('baz returned: '+ z)

so everything is done, or
baz (10)
        .then ( (result) =>{z = result;})
        .then ( () =>{console.log('baz returned: '+ z)})


text:
Q: Encrypting string in javascript and decryption in java I would like to know if someone know any library to do encryption in javascript and decryption in java. I have already tried many API, But getting not not getting same values in java. I want public-private key encryption and hence try to use RSA.
Few i have used are:

*

*http://www-cs-students.stanford.edu/~tjw/jsbn/

*http://ats.oka.nu/titaniumcore/js/crypto/readme.txt

*http://www.ohdave.com/rsa/
Few thing i checked, javascript breaks string into small chunks and then  encrypt them which make cipher text different in java and javascript. I edit javascript code to use string as a whole but didn't worked.
I also tried to set charset of html page to utf-8 but it also not worked.
I got success in encrypting single character string like 'K' to be encrypted and decrypted correctly which makes me think that there is problem in encrypting string in javascript by dividing it in small chunks (which i checked, but it fails with encrypting it as a whole).
my java implementation is:
BigInteger d = new BigInteger("1f3fac65c4ae222e3a3074dd4c38fbb72c0705c4bbac0385b867c12c25a44e01", 16);
BigInteger e = new BigInteger("65537");
BigInteger N = new BigInteger("b42e91fbca364cf2a125aec67ffbdab624fd401100c40ea05189ba34d1028b0d", 16);
String messageToEncrypt = "kishor";
byte [] messageByte = messageToEncrypt.getBytes();
BigInteger message = new BigInteger(messageByte);
//Encrypting and Decrypting messages
//Encrypt a message using N and e:
BigInteger ciphertext = message.modPow(e, N);
//Decrypt the message using N and d:
BigInteger plaintext = ciphertext.modPow(d, N);
byte[] plainTextByte = plaintext.toByteArray();
String decryptMessage = new String(plainTextByte);
/*System.out.println("p : " + p);
System.out.println("q : " + q);*/
System.out.println("N : " + N.toString(16));
System.out.println("e : " + e.toString(16));
System.out.println("d : " + d.toString(16));
/*System.out.println("PhiN : " + PhiN);*/
System.out.println("ciphertext : " + ciphertext.toString(16));
System.out.println("decryptMessage : " + decryptMessage);
}

Kindly let me know if it is possible as i have searched many question (in stackoverflow itself) but unable to find a solution.

A: Try Gibberish AES (JS Lib)
https://github.com/mdp/gibberish-aes/

A: RSA is a key transport mechanism. You use it to encrypt keys for symmetric algorithms. From what I've seen, people who are using it for anything else don't know what they are doing, and if they persist, end up building a worthless crypto system.
I've successfully inter-operated between Java and the Stanford Javascript Crypto Library. There are many other good JavaScript libraries for symmetric encryption algorithms.

A: Hey guys i figured out the solution. In javascript, first character was skiped from being encrypted causing the problem. fixed the loop. Thanks for all your replies.


text:
Q: Gson serializes with " instead of " (sometimes and randomly) I'm using Retrofit with Gson for communication with Backend APIs. I've an endpoint to refresh the access token and it needs the refresh token inside body like this (POST request):
{"refreshToken":"eyJhbGci...."}
Most of the time it works but sometimes the Gson acts very strange (or something else, I'm not sure about that). Sometimes It sends the body like this:
{"refreshToken":"eyJhbGci...."}
Last char of the serialized string is " instead of normal ". So because of this backend assumes that " is part of my refresh token and it returns an error that my refresh token is invalid.
I've checked my request if I mistakenly added " by myself but this is not the case. So what is the problem?


text:
Q: Does $a^2P(|X |\ge a )\le EX^2 $ hold when $a<0 $? That is, does Chebyshev's inequality hold for when $a $ is negative? I have seen some authors to require that $a $ be positive, but when Reading the proof by Rick Durrett, I cannot see that this is necessary or that it is implicitly assumed. Am I wrong?

Suppose $\phi : \mathbb R \mapsto \mathbb R $, $\phi \ge 0 $, Let $A \in\sigma (\mathbb R ) $ and $i _A = \{\inf \phi (y ): y \in A \} $
Then
$i _A 1 _{X \in A } \le \phi(X)1 _{X \in A }\le \phi (X) $ implies $i _A P(X \in A ) \le E \phi (X)$
Put $\phi (x)=x^2 $ and $A = \{x: |x |\ge a \} $ to get Chebyshev's inequality.
Thanks in advance!

A: Take $X$ to be Bernoulli with parameter $0$, i.e. $X=0$ a.s.; and $a = -1$. Then
$$
a^2\Pr[\lvert X\rvert \geq a] = 1, \qquad \mathbb{E}[X^2] = 0
$$


text:
Q: chunks interleaved in pipe for multiple writers? I foud the following statement, while going through pipes definition: A FIFO can have multiple readers or multiple writers. Bytes from each writer are written atomically up to a maximum size of PIPE_BUF (4KB on Linux). Chunks from simultaneous writers can be interleaved. Similar rules apply to simultaneous reads. I am not able to understand " Chunks from simultaneous writers can be interleaved". can someone explian?

A: You must have read this in Advanced Linux Programming. I'd say, this is mistakably worded and intended to be compared with the next paragraph, which says about Windows named pipes:

... Win32 allows multiple reader-writer connections on a named pipe
  without interleaving data...

But according to Windows Dev Center:

A named pipe is a named, one-way or duplex pipe for communication
  between the pipe server and one or more pipe clients. All instances of
  a named pipe share the same pipe name, but each instance has its own
  buffers and handles, and provides a separate conduit for client/server
  communication. The use of instances enables multiple pipe clients to
  use the same named pipe simultaneously.

So, there are actually multiple pipe connections (instances) involved, and comparing those to a single Unix pipe doesn't make much sense, in my opinion.
Nonetheless, The Open Group Base Specifications say:

Write requests to a pipe or FIFO shall be handled in the same way as a
  regular file with the following exceptions:
  ...
  Write requests of {PIPE_BUF} bytes or less shall not be interleaved
  with data from other processes doing writes on the same pipe. Writes
  of greater than {PIPE_BUF} bytes may have data interleaved, on
  arbitrary boundaries, with writes by other processes, whether or not
  the O_NONBLOCK flag of the file status flags is set.

So, the chunk of data of a single write request to a Linux (POSIX) pipe is not interleaved (disrupted) by data of another writer's request as long as the number of bytes to write is not greater than PIPE_BUF.

A: If process A attempts to write PIPE_BUF (or less) bytes at the same time that process B is attempting to write PIPE_BUF (or less) bytes, it is guaranteed that the writes are atomic and each block will remain intact (although the order in which they are written is unspecified.)  But if process A writes more than PIPE_BUF bytes, the data from process B may appear in the pipe interleaved with the data from process A, and the operating system provides no guarantees to prevent the data from being interleaved.  If you want to ensure that all of the data from process A remains contiguous, the processes must be synchronized with some other mechanism.

A: Assuming that you have two writers, A and B, that try to write a block of data simultaneously, the data that ends up in the pipe could look something like ABAAAABBAABB.


text:
Q: Dynamics AX 2012 R2 Enterprise Search on SharePoint Foundation 2013 Did anyone got those two working together yet?
I got AX 2012 Enterprise Portal (EP) and Help Server working with SharePoint (SP) Foundation 2013, but I cant get AX Enterprise Search (ES) to work.
When I tried to install ES, asked me to install SharePoint Search first.

SharePoint Search is not installed with Microsoft SharePoint
  Foundation. To install Microsoft Search Server Express, go to
  http://go.microsoft.com/fwlink/?LinkID=180385

However, as far as I know, Microsoft Search Server Express is included in SP 2013 by default.
So if it's already there, what path to the Search Server URL should I use instead of SP's 2010 default one (http://server_name/sites/DynamicsAXClientSearch/_vti_bin/search.asmx)? If I just use the root URL of EP I get this error:

The service returned the following error: The HTTP request is
  unauthorized with client authentication scheme 'Ntlm'. The
  authentication header received from the server was 'NTLM'.

According to Microsoft, I should be able to use Search functionality in AX 2012 with SP 2013.

All aspects of crawling, indexing, and retrieving Microsoft Dynamics
  AX data and metadata for Search are performed by one of the following
  products:

*

*Microsoft SharePoint Foundation 2010 or Microsoft SharePoint Server

*2010 Microsoft Search Server 2010 or Microsoft Search Server Express

*2010 Microsoft FAST Search Server 2010 Microsoft SharePoint

*Foundation 2013 or Microsoft SharePoint Server 2013

  One of these products must be available in the computing environment
  before you can install Enterprise Search.

But by following their installation documentation I still bump to the requirement of having Microsoft Search Server 2010 Express installed on my system, however its installation fails saying "Microsoft Search Server 2010 Express encountered an error during installation". UPDATE: For some reason installation worked on 3rd attempt and... seems like it ruined installation of SP 2013!
I feel like I'm really going in circles here.

SOLUTION: Got both versions (2010/2013) of SharePoint working with Dynamics AX 2012 R2. Please have a look at my AX notes if you are facing same issues.

A: You need to install SharePoint search as it says ,
It's not included in the standard SharePoint install , it's even a separte Download.


text:
Q: Is there runtime polymorphism in C# combined with generics? I have 2 classes that inherit from the same generic abstract class. Inheriting and implementing the methods with a type works fine, but I can't figure out how to do late binding with an instance of that abstract class.
 internal class NormalField : GenericClass<List<List<int>>>
    {
        protected override List<List<int>> doSomethingWithTheField(List<List<int>> field)
        {
            throw new NotImplementedException();
        }

        public override List<int> getFieldRow(int row)
        {
            throw new NotImplementedException();
        }
    }

internal class ComplexField : GenericClass<List<List<ComplexCell>>>
    {
        protected override List<List<ComplexCell>> doSomethingWithTheField(List<List<ComplexCell>> field)
        {
            throw new NotImplementedException();
        }

        public override List<int> getFieldRow(int row)
        {
            throw new NotImplementedException();
        }
    }

 public class ComplexCell
    {
        int field;
        int? secondField;
    }

public abstract class GenericClass<T>
    {
        public T Field;
        protected abstract T doSomethingWithTheField(T field); //class uses this internally
        public abstract List<int> getFieldRow(int row); //used by another object
    }

Unfortunately I have to declare the type before compiling so I cant dynamically assign another instance of the abstract class to a property.
 public class Program
        {
            public static void Main(string[] args)
            {
               // I have to specify the type for the interface here and can't assign a complexfield later
               GenericClass instance = new NormalField(); //not possible
                instance =  new ComplexField();
                instance.getFieldRow(2);
            }

        }

A possible solution I came up with would be to seperate the getFieldRow() method from the abstract class and create a new interface with only the getFieldRow() method. Since there are no generics involved this would work, but is there also a way to do this with a abstract class with generics?

A: GenericClass<List<List<int>>>

and
GenericClass<List<List<ComplexCell>>>

are not the same base class


text:
Q: What could go wrong with installing the DLCs for fallout new vegas on xbox 360 in the middle of the game I have the DLCs and I'm so tempted to install them for cool stuff and more weapons to complete my collection..but I've heard so many bugs and corruptions that have happened to other people's consoles due to other stuff..and this is something big I'm installing to the game and I'm really excited but mainly anxious...and in the middle of the game? Not at the very beginning or after the battle of the dam..but in the middle at a random point.

A: Nothing should be wrong with installing the DLC in the middle of the game. When DLC is being tested at Bethesda, some of the QA team uses pre-existing saves, while the rest start new games to test. In short, the developers expect you to install the DLC in the middle of a game. So the chance that you'll encounter issues installing it partway through a game is (theoretically) just as high as if you started a new game.
To clarify, if the game worked fine before installing the DLC (excluding known bugs), it should work fine after installing the DLC mid-game. If you encounter bugs after installing the DLC, it likely has nothing to do with the fact that it was installed mid-game -- they would be there no matter what.
Source: Former QA tester for Fallout: New Vegas and Old World Blues.


text:
Q: Which branch of combinatorics solves this problem? Suppose I have a 1024 × 1024 sudoku puzzle.To solve this puzzle it would take enormous amount of time even for a powerful desktop computer.
There are huge number of different ways to write numbers on 1024 × 1024 sudoku grid, but only one of them is correct.
Combinatorics gives us number of ways that one can write numbers on a 1024 × 1024 sudoku grid,but it doesn't tell how to solve it in few steps.
I am trying to come up with a technique to solve this 1024 × 1024 sudoku puzzle in few number of steps.
So which branch of combinatorics should I study to solve this problem?

A: The wikipedia page on the mathematics of Sudoku states that "The general problem of solving Sudoku puzzles on $n^2 \times n^2$ boards of $n \times n$ blocks is known to be NP-complete". The upshot of this is that unless P=NP (very unlikely), there is no efficient algorithm to solve Sudoku puzzles in general.


text:
Q: coffee script identation I get an identation error for these lines
Is there any online validator that can help me?
showAliveTests : (pageIndex, statusFilter) ->
    data=
            pageIndex:pageIndex
            status:statusFilter
        $.ajax
            url:'/ManageConfiguration/GetAliveConfigurations/' + location.search
            type:"post"
            data:data
            dataType:"json"
            success:(res)->
                if res.status == "failed"
                    alert res.body
                else
                    $('#viewConfigurationTable tr').remove()
                    newRow =    $ '
'
                    newRow.append('Id
                                    Name
                                    Status
                                    Ctids
                                    CreationDate	')
                    $('#viewConfigurationTable').append(newRow)
                    for obj in res.body
                        newRow =    $ '
'
                        newRow.append(''+obj.Id+'
                                        '+obj.Name+'
                                        '+obj.Status+'
                                        '+obj.Ctids+'
                                        '+obj.CreationDate+'	')
                    $('#viewConfigurationTable').append(newRow)
                    $(#paginator a).remove()
                    for i in [0..count] by 1
                        $(#paginator).append(''+i+'')

            error:(e)->
                alert 'An error has occured: ' + e

A: www.coffeescript.org -> click try me, paste your code inside and you will see which line throws the error.
in your case you can see it even with stackoverflow code highlighting:
$(#paginator a).remove() -> wrong
$('#paginator a').remove() -> correct

second error
$(#paginator).append(''+i+'')  -> wrong
$('#paginator').append(''+i+'')  -> correct

A: You forgot the quotes around #paginator a and paginator
#...
$("#paginator a").remove() # you had: $(#paginator a)
for i in [0..count] by 1
    $("#paginator").append(''+i+'') # you had: $(#paginator)
#...


text:
Q: Singular article usage I am baffled by a sentence that I came across in a book recently. "Americans are a very practical people". Why do we need the article "a" here?

A: Because, in this sense of the word, 'a people' is equivalent to 'a nation', that is, the inhabitants of a country taken as a whole.


text:
Q: Display a dataset of points, and a dataset of lines, on a single flot graph? How can I display two data series in the same flot graph, when one series is a set of points, and one is a line?
I've seen examples of line series like this, but the complicating factor is that I'd like to display data points and a data line on the same graph.
This seems like quite a common use case - basically I want to display a scatter graph along with its line of best fit.
Currently I have
    var options = {
        series: {
            lines: {
                show: false
            },
            points: {
                show: true
            },
            lines: {
                show: true
            }
        },
        grid: {
            hoverable: true,
        },
        yaxis: {
            min: 0,
            max: 1100000,
            font: 'Georgia'
        },
        xaxis: {
            min: 10,
            max: 480,
            font: 'Georgia'
        }
        };
    var plot = $.plot($("#placeholder"),
    [{
        data: scatterdata,
        color: 'dodgerblue',
    }], options);
    var line = $.plot($("#placeholder"),
    [{
        data: linedata,
        color: 'black',
    }], options );

But this only displays the second set of data, not both of them.

A: You want to do something like this (specify the data sets one at a time, with options):
$(function () {

    var points = [[1, 6], [2, 3], [3, 9], [4, 2], [5, 11]];

    var fitLine = [];
    for (var i = 0; i < 10; i += 0.5)
        fitLine.push([i, (0.9 * i) + 3.5]);

    $.plot($("#placeholder"), [
        {
            data: points,
            points: { show: true }
        },
        {
            data:fitLine,
            lines: { show: true }
        }
    ]);
});

Produces:


text:
Q: How to handle received push notification from parse ? | RSS Using Parse, my push notification working perfectly.
my app is an RSS news feed, and from time to time I'm sending Push notification, my problem is that I don't know how to handle the push notification when the user receive it.
I've got all my RSS sources listed in a plist file, for example how my plist file looks:
rss_sources
↓
01
  ↓
  url http://www.newyorkNews.com/rss.xml
  title: new york News
↓
02
  ↓
  url http://www.harlemNews.com/rss.xml
  title: harlem news

what i'm trying to do is, to check if the title is equal to the beginning of the push notification (since I'm the one who sending the push, i'll write the exact title), and if it does then it will go to some index.row that i set in code.
is it even possible what I've offered here?
if theres another way of doing it I will be glad to hear the solution, or some pattern of code that similar to my situation so I can get inspire from it.

A: All you have to do is set a generic key to your payload which in your case looks like title. So when you send a push (as data/payload/json), when user receives one you cross reference the valueForKey:
As always, I highly encourage you try things out yourself because that's how you learn. And I always direct Parse users to their documentation because they are extremely well-documented. Almost too documented if that's a thing. However if you get stuck here is a working example:
Construct a push with payload:
NSDictionary *data = @{
@"alert" : @"some generic message here",
@"badge" : @"Increment",
@"sounds" : @"default",
@"title" : @"NY Times" //this is whatever you want
};

//schedule the push with some options. This isn't a mandatory set up, just an example. You can do a lot with PFPushes

PFPush *push = [[PFPush alloc] init];
[push setChannels:@[ @"subscribed" ]];
[push setData:data];
[push sendPushInBackground];

Now all you have to is see if the value in the payload for the key title matches your needs :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  . . .
  // Extract the notification data from payload

 NSDictionary *notificationPayload = launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey];

 NSString *newsType = [notificationPayload valueForKey:@"title"];

  // perform segue or tab bar selectedIndex or whatever you want after checking if user is launching from notification :

if (notificationPayload) {
    //check it title has your string
    if ([newsType isEqualToString:@"NY Times"]) {
         //do whatever here
    } else {

    }
 }
}

references - please use these liberally, they've done great with providing this up-to-date resource to us
Parse iOS Push : https://parse.com/docs/push_guide#top/iOS
Parse SDK https://parse.com/docs/ios/api/

Push Notification from Parse console :
{
"aps" : {
    "alert" : "New NY Time Article",
    "badge" : 1,
    "sound" : "default",
    "title" : "NY Times"
        }
}

For reference this will get you started : https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html#//apple_ref/doc/uid/TP40008194-CH100-SW15


text:
Q: Page not found (404) jquery django python не загружается jquery - Page not found (404)
base.html
{% load static %}
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link href="{% static 'bootstrap-5.0.0/css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <!-- jQuery -->
    <script src="{% static 'jquery/jquery.js' %}"></script>
  </head>

setting.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ServiceCRM3/static'),]

*

*папка static создана

*скрипт лежит в пути static/jquery/jquery.js

*bootstrap подхватывает нормально в той же папке

*сервер перезапускал

что не так?

A: # urls.py (Главный)

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
...
...
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# После всех URL'оф добавляем путь к статике, иначе работать не будет

Подробнее можно почитать тут
https://djangodoc.ru/3.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development


text:
Q: Setup a clearkey server for shaka player didn't work? I've created a test html page for playing a MPEG-CENC protected MPEG-DASH video, and I can play if I specify kid: key pair in player.configure().
Then I want to setup a clearkey server. Refer to DRM Configuration section of Shaka Player documents, I changed the code to specify the url to get the license like below. But the page never get touched when I set a breakpoint in Page_Load event in Visual Studio. There is no error on console of browser.
The browser I use is Firefox 53.0.2 and Chrome 58.0.3029.96. Did I miss something?
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/shaka-player/2.1.0/shaka-player.compiled.js"></script>
    <title>MPEG-DASH Player Test</title>
    <script>
        //MPEG-DASH stream encrypted with MPEG-CENC:
        var manifestUri = '/dashtest_encrypted/stream.mpd';

        function initApp() {
            // Install built-in polyfills to patch browser incompatibilities.
            shaka.polyfill.installAll();

            // Check to see if the browser supports the basic APIs Shaka needs.
            if (shaka.Player.isBrowserSupported()) {
                // Everything looks good!
                initPlayer();
            } else {
                // This browser does not have the minimum set of APIs we need.
                console.error('Browser not supported!');
            }
        }

        function initPlayer() {
            // Create a Player instance.
            var video = document.getElementById('video');
            var player = new shaka.Player(video);

            // Configue
            player.configure({
                drm: {
                    servers: {
                        'org.w3.clearkey': '/clearkey/GetLic.aspx'
                    },
                    clearKeys: {
                        //'kid': 'key'
                    }
                }
            });

            // Attach player to the window to make it easy to access in the JS console.
            window.player = player;

            // Listen for error events.
            player.addEventListener('error', onErrorEvent);

            // Try to load a manifest.
            // This is an asynchronous process.
            player.load(manifestUri).then(function () {
                // This runs if the asynchronous load is successful.
                console.log('The video has now been loaded!');
            }).catch(onError);  // onError is executed if the asynchronous load fails.
        }

        function onErrorEvent(event) {
            // Extract the shaka.util.Error object from the event.
            onError(event.detail);
        }

        function onError(error) {
            // Log the error.
            console.error('Error code', error.code, 'object', error);

            alert(error.code);
        }

        document.addEventListener('DOMContentLoaded', initApp);
    </script>
</head>
<body>
    <video id="video" autoplay controls></video>
</body>
</html>

Here is the content of stream.MPD:
<?xml version="1.0" ?>
<MPD mediaPresentationDuration="PT12M3.022S" minBufferTime="PT15.48S" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="static" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:cenc="urn:mpeg:cenc:2013">
  <!-- Created with Bento4 mp4-dash.py, VERSION=1.7.0-614 -->
  <Period>
    <!-- Video -->
    <AdaptationSet maxHeight="720" maxWidth="1280" mimeType="video/mp4" minHeight="720" minWidth="1280" segmentAlignment="true" startWithSAP="1">
      <!-- MPEG Common Encryption -->
      <ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
      <SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
      <Representation bandwidth="1901600" codecs="avc1.64001F" frameRate="30000/1001" height="720" id="video/avc1" scanType="progressive" width="1280"/>
    </AdaptationSet>
    <!-- Audio -->
    <AdaptationSet mimeType="audio/mp4" segmentAlignment="true" startWithSAP="1">
      <!-- MPEG Common Encryption -->
      <ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
      <SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
      <Representation audioSamplingRate="44100" bandwidth="200442" codecs="mp4a.40.2" id="audio/und/mp4a">
        <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
      </Representation>
    </AdaptationSet>
  </Period>
</MPD>

A: After a very long time testing and comparison, I noticed that my .mpd file didn't have cenc:pssh tag, which resulted this problem. I recreated the .mpd and Shaka Player FINALLY asked the server.
The corrected .mpd is below:
<?xml version="1.0" ?>
<MPD mediaPresentationDuration="PT12M3.022S" minBufferTime="PT15.48S" profiles="urn:mpeg:dash:profile:isoff-live:2011" type="static" xmlns="urn:mpeg:dash:schema:mpd:2011" xmlns:cenc="urn:mpeg:cenc:2013">
  <!-- Created with Bento4 mp4-dash.py, VERSION=1.7.0-614 -->
  <Period>
    <!-- Video -->
    <AdaptationSet maxHeight="720" maxWidth="1280" mimeType="video/mp4" minHeight="720" minWidth="1280" segmentAlignment="true" startWithSAP="1">
      <!-- EME Common Encryption -->
      <ContentProtection schemeIdUri="urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b" value="cenc">
        <cenc:pssh>AAAANHBzc2gBAAAAEHfv7MCyTQKs4zweUuL7SwAAAAF6ThLxhhApHzhsesG5Qlq/AAAAAA==</cenc:pssh>
      </ContentProtection>
      <!-- MPEG Common Encryption -->
      <ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
      <SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
      <Representation bandwidth="1901627" codecs="avc1.64001F" frameRate="30000/1001" height="720" id="video/avc1" scanType="progressive" width="1280"/>
    </AdaptationSet>
    <!-- Audio -->
    <AdaptationSet mimeType="audio/mp4" segmentAlignment="true" startWithSAP="1">
      <!-- EME Common Encryption -->
      <ContentProtection schemeIdUri="urn:uuid:1077efec-c0b2-4d02-ace3-3c1e52e2fb4b" value="cenc">
        <cenc:pssh>AAAANHBzc2gBAAAAEHfv7MCyTQKs4zweUuL7SwAAAAF6ThLxhhApHzhsesG5Qlq/AAAAAA==</cenc:pssh>
      </ContentProtection>
      <!-- MPEG Common Encryption -->
      <ContentProtection cenc:default_KID="7a4e12f1-8610-291f-386c-7ac1b9425abf" schemeIdUri="urn:mpeg:dash:mp4protection:2011" value="cenc"/>
      <SegmentTemplate duration="15482" initialization="$RepresentationID$/init.mp4" media="$RepresentationID$/seg-$Number$.m4s" startNumber="1" timescale="1000"/>
      <Representation audioSamplingRate="44100" bandwidth="200442" codecs="mp4a.40.2" id="audio/und/mp4a">
        <AudioChannelConfiguration schemeIdUri="urn:mpeg:dash:23003:3:audio_channel_configuration:2011" value="2"/>
      </Representation>
    </AdaptationSet>
  </Period>
</MPD>


text:
Q: Extraction of each HSV value from an image using OpenCV and C++ I used the code below to extract each HSV value from any image and to print each value on the screen.
Mat image_HSV;
cvtColor(ori_image, image_HSV, CV_BGR2HSV);

Mat mask;
inRange(image_HSV, Scalar(100, 0, 0), Scalar(100, 255, 255), mask);

image_HSV.setTo(Scalar(0, 0, 0), mask);

int h = 0;
int s = 0;
int v = 0;

int col = image_HSV.cols;
int row = image_HSV.rows;

int corow = col * row;  // image's full pixel number

for (int i = 0; i < image_HSV.cols; i++) {      // image row pixel
    for (int j = 0; j < image_HSV.rows; j++) {  // image col pixel
        Vec3b hsv = image_HSV.at<Vec3b>(i,j);

        h += hsv.val[0];
        s += hsv.val[1];
        v += hsv.val[2];

        if (hsv[0] != 100) {
            hsv[0] = 0;
            hsv[1] = 0;
            hsv[2] = 0;
        }
    }
}

cout << "H: " << h / corow << "% \n";
cout << "S: " << s / corow << "% \n";
cout << "V: " << v / corow << "% \n";

waitKey(0);
return 0;

I used all red color image for this time, which RGB values were 255, 0, 0.
However, I have some strange results from this code.
As I know, each H,S,V value range is covered by 0-360, 0-100, and 0-100, respectively.
Further, I also followed the post linked below but I still have a trouble to get right values.
OpenCV (C++) - Set HSV values of a pixel
But, I still don't know how to fix it.
Any help would be greatly appreciated! Thanks!


text:
Q: Graphicspath and standalone I have a standalone setup with the following file structure
A
├── A.tex
└── sections
    ├── B
    │   ├── Bimages
    │   │   └── cat.png
    │   └── B.tex
    └── C
        ├── Cimages
        └── C.tex

I have a main tex file called A and two subfiles B and C, such that the content of A is a title page then B and C concatenated. B has its own images directory, which is referenced in B.tex using \graphicspath{ {./Bimages/} } and C similarly has ./Cimages/. B and C compile separately perfectly well, however, when I compile A, I get LaTeX Warning: File Bimages/cat.png not found on input line 89.
Is this expected behaviour with standalone? Will it not account for relative file paths in subdirectories? If so, is there a way to work around this such that I can organise my images into separate folders(preferably without having to do \graphicspath{ {./sections/B/Bimages} {./sections/C/Cimages} } in A.tex, as I may have many more similar directories in the future.

A: you might want to change the way you import your subfiles
\input just copies the text content of B.tex into A.tex before compiling.
That makes A look for the graphicspath in it's home directory (which is /A/)
\include (I think) creates aux files for every sub-file and therefore might be able to find the correct subpath (for example /A/B/Bimages/)
I DID NOT TEST THIS!
see this for reference

If that does not do the trick, then you could maybe switch to using global paths for your images
(like "~/foo/bar/A/B/Bimages/" instead of "./B/Bimages/").


text:
Q: Mocking a function in Jest not returns the expected value I got AWS lambda function which I want to unit test it using Jest.
As part of the code I got another file to make http calls, which currently I using as a mock.
During another unit test case I want to have another scenario to check by using a mock.
I tried several ways using Jest to do so, but nothing made my function to return the needed result from the mocked function:
First try:
const api_response_utils = require('api_response_utils').default;
const mock = jest.fn().mockReturnValue(["new return value"])
api_response_utils.get = mock;

Second try:
 jest.mock("api_response_utils", () => ({
      ...jest.requireActual("api_response_utils"),
      get: () => {
        return ["a", "b"]
      },
      sendResponse:() => {
        return ["a", "b"]
      },
    }));

Is there any other way to make it ?

A: You could try it like this (I am assuming api_response_utils is a local file)
const api_response_utils = require('./api_response_utils')

jest.mock("./api_response_utils", () => ({
      ...jest.requireActual("./api_response_utils"),
      get: jest.fn().mockReturnValue(["a", "b"]),
      sendResponse: jest.fn().mockReturnValue(["a", "b"]),
    }));


text:
Q: How correctly to save texture2d to MediaLibrary wp7 The problem is in method Texture2D.SaveAsPng. I recently found out memory leak in this method in similar problem but managed to solve it. But I can't fit that solution here. What I'm trying now is:
        MediaLibrary library = new MediaLibrary();
        MemoryStream ms = new MemoryStream();
        pic.SaveAsJpeg(ms, pic.Width, pic.Height);
        ms.Seek(0, SeekOrigin.Begin);
        library.SavePicture(path, ms);
        ms.Close();

And, every call I lose about 4mb of memory (texture dimension 800x620).
I have tried to create MemoryStream from byte array but it throws Value does not fall within the expected range exception.
        byte[] textureData = new byte[4 * picHeight * picWidth];
        pic.GetData(textureData);
        library.SavePicture(path, textureData); //exception on this line

So, I guess, I need to convert Texture2D in byte array so that library.SavePicture(path, ms) won't throw exception, but I have no clue how to do that. Any help would be appreciated.
Note: memory leak in Texture2D.SaveAsJpeg occurs only on windows phone 7.
Upd: Memory stream length created from byte array from Texture.GetData is 1984000, when length of memory stream from  Texture2D.SaveAsJpeg is 141520.

A: I don't understand why you copied texture pic data in textureData but you never use it.
Maybe you need to do:
byte[] textureData = new byte[4 * picHeight * picWidth];
pic.GetData(textureData);
library.SavePicture(path, textureData);

UPDATE
According to MSDN for MediaLibrary.SavePicture:

Image data that is passed in must be in a JPEG file format.
  Additionally, SavePicture always saves the image in a JPEG file
  format.

It seems that the byte[] that you get from Texture2D.GetData is not in that format, but I don't know how to convert it.


text:
Q: adb pull file in Arabic Language(UTF-8) encoding i tried to pull it using
adb pull /sdcard/جهات الإتصال.vcf D:/

but when i write it in CMD it's shows as non-understood language
any ideas please

A: This question has deleted answer by @sachin-das stating that adb.exe from andriod platform tools handles Japanese filenames properly.
I've rechecked that platform-tools-latest-windows.zip\platform-tools\adb.exe version 1.0.39 from Andriod Platform Tools handles Russian filenames correctly too.
My old adb.exe v1.0.32 was corrupting filenames. While adb.exe of the same v1.0.32 from @sachin-das's google drive didn't.
So I guess there are different builds of adb of the same version roaming in the wild.


text:
Q: Not getting the correct output for a file when using inheritance So the whole point of my program is to read input from a file and do some calculations and then output the results to the file.
There are a couple of files involved in this, but for simplicity I will just include the two implementation files for my program. The implementation file "employee" is the base class and the file "merit" is the derived class.
Now for the output I should be getting it in the format of: ID---Salary
I am getting the correct result for the salary, but I am getting the wrong numbers for ID. I know it has to do with the fact that in the merit::print() function, it is printing [merit::ID] and not [employee::ID].
Is there someway that I can make it print out employee::ID and not merit::ID?
The following is the base class file (employee file):
#include <iostream>
#include <fstream>
#include <iomanip>
#include "employee.h"
#include "merit.h"

using namespace std;

// The definition of the members functions of the class employee goes here.

void employee::readData(ifstream& inf)
{
    inf >> ID >> Job_class >> Years >> Ed;
}

void employee::print(ofstream& outf) const
{
    outf << ID << setw(15) << fixed << showpoint << setprecision(2) << "$ " << sal << endl;
}

The following file is the derived class file (merit file):
void merit::readData(ifstream& inf)
{
    employee::readData(inf);
    inf >> mer;

}

void merit::print(ofstream& outf) const
{
    outf << ID << setw(15) << fixed << showpoint << setprecision(2) << "$ " << salary << endl;
}

A: You haven't shown us your header files where you define the classes so this may not quite be right.  I'm assuming that both employee and merit both have a member called ID.
To access a base class member with the same name as a member in a derived class, just qualify the name.  In your case, use employee::ID instead of ID.
You've indicated in a comment that ID is private in employee, so you'll need to use a getter function.  Add something like int getEmployeeID() const; to your employee class (it can be either protected or public) that would return the ID.  Then call that from you merit class to get the employee ID.


text:
Q: How to implement horizontal & vertical chain type concept in recyclerview gridlayout? As always I have read through several posts on this topic across this site. If this truly is duplication I will delete this question. Majority of cases on here are dealing with orientation changes or looking to amend fixed values depending on the screensize. I am not worried about fixing width and height values.
What I want to achieve is a 6x10 grid which fills the screen no matter what size it is (orientation is fixed to portrait)
Here is my recyclerview item, I started with wrap content on the views and then tried match parent, neither makes any difference. On a small screen it fits fine and on a large screen it sits in the middle but is the same size.
I know I can't directly create a chain in my recyclerview item xml because I need to make a chain out of more than 1 view. I attempted to manually set the main layout with spread chain and a weight of 1 and then set the layout to 0dp, ran the code and obviously it didnt work
So, key question, is there a way to simply write the item xml so that it is dynamic or do we always have to create a subclass of sorts to generate different layouts per screensize?
<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="2dp">

    <LinearLayout
        android:id="@+id/layout_background"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="4dp"
        android:layout_marginEnd="4dp"
        android:layout_marginBottom="3dp"
        android:background="@drawable/level_background"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/TV_Level"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center|center_horizontal|center_vertical"
            android:textColor="@color/sub_level_button_text_color" />

        <RatingBar
            android:id="@+id/ratingBar"
            style="@style/Widget.AppCompat.RatingBar.Small"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="@color/StarOutline"
            android:isIndicator="true"
            android:numStars="3"
            android:progressTint="@color/StarOutline"
            android:stepSize="0.5" />
    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

To further assist with this here is my adapter
package com.maxcell.sumitup

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RatingBar
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView

class LevelsAdaptor(private val onClick:(id:Int,mainLevel:Int,subLevel:Int,stars:Float,bonusGame:Boolean,type:Int)->Unit) : ListAdapter<Levels, LevelsAdaptor.LevelsViewHolder>(LevelsComparator()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LevelsViewHolder {
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.rv_storymode_items, parent, false)
        return LevelsViewHolder(view)
    }

    override fun onBindViewHolder(holder: LevelsViewHolder, position: Int) {
        val current = getItem(position)
        holder.bind(
            current.id,
            current.mainLevel,
            current.subLevel,
            current.stars,
            current.unlocked,
                current.bonusround,
                current.questiontype
        )
    }

    inner class LevelsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val TVLEVEL: TextView = itemView.findViewById(R.id.TV_Level)
        private val rating: RatingBar = itemView.findViewById(R.id.ratingBar)
        private val layoutBackground: LinearLayout = itemView.findViewById(R.id.layout_background)
        private val myContext = itemView.context
        //private val myContext: Context = sumView.context
        fun bind(ID: Int, ML: Int, SL: Int, Stars: Float, Unlocked: Boolean,BonusRound:Boolean,QuestionType:Int) {
            TVLEVEL.text = ID.toString()
            rating.rating = Stars

            if (Unlocked){
                itemView.isEnabled=true;itemView.isClickable=true;layoutBackground.setBackgroundResource(R.drawable.level_background)
            }else{
                itemView.isEnabled=false;itemView.isClickable=false;layoutBackground.setBackgroundResource(R.drawable.standard_background_deactivated);TVLEVEL.setTextColor(myContext.getColor(R.color.ColorOnDeactivated))
            }
            itemView.setOnClickListener {
                //Set your codes about intent here
                onClick(ID,ML,SL,Stars,BonusRound,QuestionType)
            }
        }

        }
    }

    class LevelsComparator : DiffUtil.ItemCallback<Levels>() {
        override fun areItemsTheSame(oldItem: Levels, newItem: Levels): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Levels, newItem: Levels): Boolean {
            return oldItem == newItem
        }
    }

A: If you set the RecyclerView width to match_parent, your ConstraintLayout, LinearLayout, TextView and RatingBar widths to match_parent, the items will stretch to fill the entire width of the screen (assuming you're using GridLayoutManager)

However, you'll notice that they don't fit the screen vertically, you have to scroll to them all. Setting height to 'match_parent' won't help here, you'll have to calculate the height in your adapter if you want them to fit exact.
This might make it look a bit strange on certain devices though (such as phones with longer screens).

To give a better looking layout, you might want to set the following properties on the ConstraintLayout:
android:layout_height="0dp"
app:layout_constraintDimensionRatio="3:1"


text:
Q: Concatenate two columns only if both contains string value, not NA value, in R I googled and I found out the solution for Python and SQL but not for R coding.
I attach an example of a dataframe called df1 in order to be easy to understand.
Genus          Species       Genusspecie
Escherichia     coli       Escherichia coli
Campylobacter    NA        NA
Shigella        sonnei     Shigella sonnei

If exists NA in df1 is only in the variable column of Specie.
Then I desire that if NA exists in Specie the complete species name (new variable created called Genusspecie) appears NA. If Genus and Specie are both informed, I desire to obtain the completne specie name.
I tried the command paste but then I will need to transform the string cells of dataframe containing NA to a string cell only containing NA without genus information.

df1$Genusspecie <- paste(taxa2$Genus, taxa2$Species)

Thanks on advance for your help,

A: You can use ifelse. If Species is NA, return NA, otherwise paste the two columns together.
within(df1, GenusSpecies <- ifelse(is.na(Species), NA, paste(Genus, Species)))
#>           Genus Species     GenusSpecies
#> 1   Escherichia    coli Escherichia coli
#> 2 Campylobacter    <NA>             <NA>
#> 3      Shigella  sonnei  Shigella sonnei

Data from question in reproducible format
df1 <- data.frame(Genus   = c("Escherichia", "Campylobacter", "Shigella"),
                  Species = c("coli", NA, "sonnei"))

A: This is a perfect use case for str_c from stringr package:
Different to paste str_c returns a NA if there is one NA:
library(dplyr)
library(stringr)
df1 %>%
  mutate(GenuSpecies = str_c(Genus, Species, sep = " "))

         Genus Species      GenuSpecies
1   Escherichia    coli Escherichia coli
2 Campylobacter    <NA>             <NA>
3      Shigella  sonnei  Shigella sonnei


text:
Q: Python Request Post , i have made API's , one which has data and another which uses GET and POST to manipulate data . But am unable to do use POST I made an API using flask from which I can get and post data. I am able to get the data but am not able to post it.
Snippet of the code from which I am making a post request
import requests

from pprint import pprint

base_url = 'http://127.0.0.1:5000'

response = requests.get(base_url)

data = response.json()

#print(data)

print("Enter '1' If You Are Existing User")

print("Enter '2' If You Want To Make An Account")

key=int(input())

if(key==2):

    print("Enter Your Name For Your Account:")

    n1=input()
    print("Enter A Strong Password For Your Account")
    n2=input()
    for g in data:
        if(g['Name'].upper()== n1.upper() and g['Password'].upper()==n2.upper()):
           print("User Already Exist")
           break
        else:
            payload={'Name':n1,'Password':n2}
            r=requests.post(base_url,data=payload)
            pprint(r.json)
if(key==1):

    print("Enter Your Name")
    name = input()
    print("Enter Your Password")
    ent = input()

    print("\n")

    for i in data:
        if(i['Name'].upper()== name.upper() and i['Password'].upper()==ent.upper()):
            print("Login Succesfull")

Snippet of the API I made to store data
Running The API which stores the data only gives me this result , it does not shows the data which i uploaded through Requests.post

A: The error lies in calling requests.post with data=.... You should use json=... so it adds the header Content-Type: application/json automatically for you in the request.
Also, another error is that the request.post was inside the for-loop.
On the server-side, the error is the declaration of both GET and POST methods in the same function. A better way would be to use one function for each method.
Anyway, I've fixed the sources and the below code should work.

APP
import requests
from pprint import pprint

base_url = 'http://127.0.0.1:5000'
response = requests.get(base_url)
data = response.json()

#print(data)

print("Enter '1' If You Are Existing User")
print("Enter '2' If You Want To Make An Account")

key=int(input())

if(key==2):
    print("Enter Your Name For Your Account:")

    n1=input()
    print("Enter A Strong Password For Your Account")
    n2=input()
    for g in data:
        if(g['Name'].upper()== n1.upper() and g['Password'].upper()==n2.upper()):
           print("User Already Exist")
           break
    else:
        payload={'Name':n1,'Password':n2}
        r=requests.post(base_url,json=payload)
        pprint(r.text)

if(key==1):
    print("Enter Your Name")
    name = input()
    print("Enter Your Password")
    ent = input()

    print("\n")

    for i in data:
        if(i['Name'].upper()== name.upper() and i['Password'].upper()==ent.upper()):
            print("Login Succesfull")

API
from flask import Flask, jsonify, request

result = [
  {'Name': 'P1', 'Password': 'Youtube'},
  {'Name': 'R1', 'Password': 'hello'},
  {'Name': 'S1', 'Password': 'pubg'},
]

app = Flask(__name__)

@app.route('/', methods=['GET'])
def hello2():
  return jsonify(result)

@app.route('/', methods=['POST'])
def hello3():
  global result
  result += [request.json]
  return jsonify(result)

if __name__ == '__main__':
  app.run(debug=True)


text:
Q: How does C perform the % operation interally I am curious to understand the logic behind the mod operation since I understand that bit-shifting operations can be performed to do different things such as bit shifting to multiply.
One way I can see it being done is by a recursive algorithm that keeps dividing until you cannot divide anymore, but this does not seem efficient.
Any ideas will be helpful. Thanks in advance!

A: While most C implementations run on hardware that has a division instruction, the remainder operation can be performed roughly like this, for computing p%q, assuming unsigned values:
#define HI (-1U-(-1U/2))
unsigned i;
for (i=0; !(HI & (q<<i)); i++);
do { if (p >= (q<<i)) p -= (q<<i); } while (i--);

The resulting remainder is in p.

A: In addition to a hardware instruction and implementation using shifts, as R.. suggests, there's also reciprocal multiplication.
This technique can be used when the right-hand side of % is a constant, known at compile time.
Reciprocal multiplication is used to implement division, but using it for % is easy, based on the formula a%b == a-(a/b)*b.

A: The quick version is: Depends on hardware, the optimizer, if it's division by a constant or not (pdf), if there's exceptions to be checked for (e.g. modulo by 0), if and how negative numbers are handled (this is a scary question for C++), etc...
R gave a nice, concise answer for unsigned integers, but it's difficult to understand unless you're well versed with C.
The crux of the technique illuminated by R is to strip away multiples of q until there's no more multiples of q left. We could naively do this with a simple loop:
while (p >= q) p -= q; // One liner, woohoo!

The code may be short, but for large values of p and small values of q this might take a very long time.
Better than stripping away one q at a time would be to strip away many q's at a time. Note that we actually want to strip away as many q's as possible -- that is, floor(p/q) many q's... And indeed, that's a valid technique. For unsigned integers, one would expect that p % q == p - (p / q) * q. (Note that unsigned integer division rounds down.)
But this almost feels like cheating because division and remainder operations are so intimately related. (In fact, often if hardware natively supports division, it supports a divide-and-compute-remainder operation because they're so strongly related.)
Assuming we've no access to division, how shall we find a multiple of q greater than 1 to strip away? In hardware, fixed shift operations are cheap (if not practically free) and conceptually represent multiplication by a non-negative power of two. For example, shifting a bit string left by 3 is equivalent to multiplying by 8 (that is, 2^3), e.g. 5 decimal is equivalent to '101' binary. Shift '101' in binary by adding three zeroes on the right (giving '101000') and the result is 50 in decimal -- five times eight.
Likewise, shift operations are very cheap as software operations and you'll struggle to find a controller that doesn't support them and quickly. (Some architectures such as ARM can even combine shifts with other instructions to make them 'free' a good deal of the time.)
ARMed (couldn't resist) with these shift operations, we can proceed as follows:

*

*Find out the largest power of two we can multiply q by and still be less than p.

*Working from the largest power of two to the smallest, multiply q by each power of two and if it's less than what's left of p subtract it from what's left of p.

*Whatever you've got left is the remainder.

Why does this work? Because in the end you'll find that all the subtracted powers of two actually sum to floor(p / q)! Don't take my word for it, similar knowledge has been known for a very long time.
Breaking apart R's answer:
#define HI (-1U-(-1U/2))

This effectively gives you an unsigned integer with only the highest value bit set.
unsigned i;
for (i=0; !(HI & (q<<i)); i++);

This line actually finds the highest power of two q can be multiplied before overflowing an unsigned integer. This isn't strictly necessary, but it doesn't change the results other than increasing the amount of execution time required.
In case you're not familiar with the C-isms in this line:

*

*(q<<i) is a left bit shift by i. Recall this is equivalent to multiplying by 2^i.

*HI & (q<<i) performs a bitwise-AND. Since HI only has its top bit populated this will only result in a non-zero value when (q<<i) is large enough to cause the top bit to be non-zero. One more shift over to the left and there'd be an integer overflow.

*!(HI & (q<<i)) is 'true' when (HI & (q<<i)) is zero and 'false' otherwise.

do { if (p >= (q<<i)) p -= (q<<i); } while (i--);
This is a simple decreasing loop do { .... } while (i--);. Note that post-decrementing is used on i so the loop executes, then it checks to see if i is not zero, then it subtracts one from i, and then if its earlier check resulted in true it continues. This has the property that the loop executes its last time when i is 0. This is important because we may need to strip away an unmultiplied copy of q.
if (p >= (q<<i)) checks if the 2^i * q is less than or equal to p. If it is, p -= (q<<i) strips it away.
The remainder is left.

A: Depending on the smarts of the optimizer, there is a shortcut for modulo base 2. For example, a % 32 can be implemented as a & 31. In general, a % (2^N) == a & (2^N -1). This is lightning fast compared to division. Most dividers (ever hardware) require at least 1 cycle for each bit of the result to calculate, while logic AND is just a few cycle operation (in the pipeline).
EDIT: this only works if a is unsigned !


text:
Q: Are locks necessary to maintain thread safety when using memory cache in C# .NET? I've been researching how to implement basic memory caching in my class library. I came across this example and decided to implement something similar, but I've come across some problems:

*

*Is MemoryCache really thread-safe? Sifting through the comments, I've found people saying it is and some people saying it isn't. I've never used this class before, so I'm not certain which comments apply to my situation.

*If MemoryCache is not thread-safe, how does one make it thread-safe? Or should I be using something different for my situation?

In my case, consuming applications will have one instance of my class (DataProviderDecorator) used by 1-to-N threads. Will it be safe to use in that manner?:
public class DataProviderDecorator : IDataProvider
{
    private readonly IDataProvider Decoratee;
    private readonly MemoryCache Cache;                                         // System.Runtime.Caching.MemoryCache
    private ConcurrentDictionary<string, SemaphoreSlim> Locks { get; set; }     // System.Collections.Concurrent.ConcurrentDictionary and System.Threading.SemaphoreSlim

    public object GetItem(string key)
    {
        object result = null;

        if (Cache.Contains(key))
        {
            return Cache.Get(key);
        }

        SemaphoreSlim cacheLock = Locks.GetOrAdd(key, new SemaphoreSlim(1, 1));
        cacheLock.Wait();

        try
        {
            if (Cache.Contains(key))
            {
                return (QueryResult)Cache.Get(key);
            }

            result = Decoratee.GetItem(key);

            CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
            cacheItemPolicy.SlidingExpiration = new TimeSpan(0, 0, 30);
            if (!Cache.Add(key, result, cacheItemPolicy))
            {
                throw new Exception($"A record for the key [{key}] is already present in the cache.");
            }
        }
        finally
        {
            cacheLock.Release();
        }

        return result;
    }
}

Also, does anyone have any idea for how I should maintain the collection of locks? Presumably it would fill up indefinitely.


text:
Q: BibTeX encoding problem migrating from Windows to OSX I haven't used JabRef in a long time, basically ever since I moved from Microsoft OS to Mac. Now I am writing my dissertation in LaTeX, and whenever I refer to an entry in my old .bib bibliography, the format of German umlauts (ä, ü, ö etc.) is totally messed up. How do I change the encoding in my BibTeX file? I use
\usepackage[applemac]{inputenc}

in my preamble, and apart from the bibliography problem, everything works perfectly.
Here is my MWE:
\documentclass[11pt,twoside]{report}
\usepackage[natbib,style=authoryear-comp, url=false, doi=false,isbn=false,eprint=false]{biblatex}
\bibliography{[mypath]} %this works
\begin{document} Here I want to refer to \cite{Lueger1995}.
\end{document}

and here one of those problematic bib-items:
@Book{Lueger1995,
Title = {{Pressesprache}},
Author = {Heinz-Helmut Lüger},
Publisher = {Max Niemeyer Verlag, Tübingen},
Year = {1995}, }

A: You shouldn't   use applemac encoding for .tex files any more! All modern OS understand UTF8 and, with ascii, it is the only universal format. I have no idea why the default in TeXshop still is applemac, if I'm not mistaken.
You also can use UTF8-encoded .bib files if you make your bibliography with biblatex/biber, and JabRef is able to save your .bib files in UTF8 encoding (goto Preferences -> General menu).


text:
Q: Xamarin.Forms: Page with CSS transformations and JS swiping doesn't work in Android WebView custom renderer, when it does in Chrome What could be the cause of a HTML page loaded over HTTPS with CSS transformations and JavaScript that uses "swiping" to not work in a Xamarin.Forms Android WebView custom renderer?
The page works fine in: Chrome on Android, Xamarin.Android WebView, Xamarin.Forms WebView.
Only when using a WebView custom renderer on Android according to the official tutorial does the page stop working.
Specifically, it's pages like these that fail to work for some reason: https://www.irozhlas.cz/fotogalerie/7693434?fid=8301190
Found another type of pages that doesn't display correctly in an Android WebView custom renderer: https://www.irozhlas.cz/ekonomika/kalkulacka-socialni-davky-exekuce_1811280900_jab – this leads me to believe it's a CSS issue, not a JS one.
I understand this is quite a narrow scope, but I'm sure others must have run into similar problems.
I have tried:

*

*No relevant errors or warnings seem to appear in the log.

*Remote debugging on Chrome: there are no warnings or signs of why it wouldn't work. I wasn't able to find the cause in the page's JS or CSS.

*Updating the Xamarin.Forms package.

*Setting HttpClient implementation to Android (AndroidClientHandler).

*The following, gathered from other Stack Overflow answers and other places, but it doesn't make a difference:
webView.Settings.SetAppCacheEnabled(true);
webView.Settings.DomStorageEnabled = true;
webView.Settings.DatabaseEnabled = true;
webView.Settings.LoadWithOverviewMode = true;
webView.Settings.AllowFileAccess = true;
webView.Settings.AllowContentAccess = true;

webView.Settings.UseWideViewPort = true;
webView.Settings.BuiltInZoomControls = true;
webView.Settings.DisplayZoomControls = false;
webView.Settings.SetSupportZoom(true);
webView.Settings.DefaultTextEncodingName = "utf-8";

webView.SetWebViewClient(new WebViewClient());
webView.SetWebChromeClient(new WebChromeClient());

Using Xamarin.Forms with a custom renderer for the WebView should have been the equivalent of using Xamarin.Android, but upon further investigation, a Xamarin.Android project with a WebView works fine with the page, and so does the default Xamarin.Forms WebView, thus this seems to be a Xamarin.Forms WebView custom renderer specific problem.

A: One solution I've found is to create the Android WebView inside a custom page renderer for Android. In this example, the page with the WebView is called MyPage.
On other platforms, you can use the regular MyPage Xamarin.Forms.Page with Xamarin.Forms.WebView, or WebView custom renderers. As mentioned in the question, on Android, the custom renderer for the WebView has problems with certain kinds of pages.
using Android.Content;
using Xamarin.Forms.Platform.Android;
using Android.Webkit;
using Android.Widget;

[assembly: Xamarin.Forms.ExportRenderer(typeof(MyPage), typeof(MyPageRenderer))]
namespace MyXamarinApp.Droid
{
    public class MyPageRenderer : PageRenderer
    {
        WebView webView;

        public MyPageRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || Element == null)
            {
                return;
            }

            webView = new WebView(this.Context);

            // If you're using AXML to "inflate" the layout, you would use something like this instead:
            //webView = FindViewById<WebView>(Resource.Id.webview);

            // Important: LayoutParameters don't do anything for the layout (because the parent Xamarin.Forms page is a FrameLayout and doesn't do any automatic layout), but leaving this out is what causes the problems
            webView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.FillParent, LayoutParams.FillParent);

            // Here you can set the WebView settings, WebViewClient, CookieManager, AddJavascriptInterface etc.
            webView.Settings.JavaScriptEnabled = true;

            webView.LoadUrl("https://www.example.com/");

            this.AddView(webView);

            /*// The following works but breaks Xamarin.Forms:
            Activity activity = this.Context as Activity;
            activity.SetContentView(webView);*/
        }

        protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
        {
            base.OnLayout(changed, left, top, right, bottom);

            webView.Layout(left, top, right, bottom); // Important because LayoutParameters doesn't have an effect
        }
    }
}

It looks like leaving out the line webView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.FillParent, LayoutParams.FillParent); is what causes the WebView problems. Perhaps this is what's missing in the Xamarin.Forms custom renderer?