text:
Q: how to reverse the direction of PagerAdapter to left to right order? MainActivity.java code:
package com.androidbegin.viewpagertutorial;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Toast;

public class MainActivity extends Activity {

    // Declare Variables
    ViewPager viewPager;
    PagerAdapter adapter;
    String[] rank;
    String[] country;
    String[] population;
    int[] flag;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from viewpager_main.xml
        setContentView(R.layout.viewpager_main);

        // Generate sample data
        rank = new String[] { "1", "2", "3"};

        country = new String[] { "China", "India", "United States",
        };

        population = new String[] { "1,354,040,000", "1,210,193,422",
                "315,761,000"};

        flag = new int[] { R.drawable.page001, R.drawable.page002,
                R.drawable.page003};

        // Locate the ViewPager in viewpager_main.xml
        viewPager = (ViewPager) findViewById(R.id.pager);
        // Pass results to ViewPagerAdapter Class
        adapter = new ViewPagerAdapter(MainActivity.this, rank, country, population, flag);
        // Binds the Adapter to the ViewPager
        viewPager.setAdapter(adapter);

    }
}

ViewPagerAdapter code:
package com.androidbegin.viewpagertutorial;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ViewPagerAdapter extends PagerAdapter {
    // Declare Variables
    Context context;
    String[] rank;
    String[] country;
    String[] population;
    int[] flag;
    LayoutInflater inflater;

    public ViewPagerAdapter(Context context, String[] rank, String[] country,
                            String[] population, int[] flag) {
        this.context = context;
        this.rank = rank;
        this.country = country;
        this.population = population;
        this.flag = flag;

    }

    @Override
    public int getCount() {return rank.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((RelativeLayout) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // Declare Variables
        TextView txtrank;
        TextView txtcountry;
        TextView txtpopulation;
        ImageView imgflag;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.viewpager_item, container,
                false);

        // Locate the ImageView in viewpager_item.xml
        imgflag = (ImageView) itemView.findViewById(R.id.flag);
        // Capture position and set to the ImageView
        imgflag.setImageResource(flag[position]);

        // Add viewpager_item.xml to ViewPager
        ((ViewPager) container).addView(itemView);

        return itemView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // Remove viewpager_item.xml from ViewPager
        ((ViewPager) container).removeView((RelativeLayout) object);

    }
}

What do I need to change in either of the two classes so that it starts on the last image instead of the first (right to left)?
the behavior i want is that after the first image is displayed, is that you can't swipe to the left.
i searched a lot for clever way to implement this but no results..
thanks in advance.


text:
Q: Calling methods from different classes with the class name I have various classes with singleton pattern. They all are extending from an abstract class. Each class has a getInstance() method (with exact same name). I want to get instance with the class name (String). For example
public abstract class AbsCls {
}

public class A extends AbsCls {
  private static A a;
  private A() {
}
public synchronized static A getInstance() {
  if(a==null) {
    a == new A();
  }
  return a;
}

public class Test {
  public static void main(String[] args) {
    AbsCls[] array = new AbsCls[5];
    array[0]=neededFunction("A");
    array[1]=neededFunction("B");
  }
}

All the classes have the same structure with class A. How should be the neededFunction()?
I can write "if.. else", but i feel like there should be a more elegant way. Thanks for any help in advance...

A: You could use the full class name as in package.ClassName, reflection, and Class.forName(theName).
For instance with a String object:
try {
    String newString = (String)Class.forName("java.lang.String").newInstance();
}
catch (IllegalAccessException iae) {
    // TODO handle
}
catch (InstantiationException ie) {
    // TODO handle
}
catch (ClassNotFoundException cnfe) {
    // TODO handle
}

So your method could roughly look like:
@SuppressWarnings("unchecked")
public static <T> T getInstance(String clazz) {
    // TODO check for clazz null
    try {
        return (T)Class.forName(clazz).getMethod("getInstance", (Class<?>[])null).invoke(null, (Object[])null);
    }
    catch (ClassNotFoundException cnfe) {
        // TODO handle
        return null;
    }
    catch (NoSuchMethodException nsme) {
        // TODO handle
        return null;
    }
    catch (InvocationTargetException ite) {
        // TODO handle
        return null;
    }
    catch (IllegalAccessException iae) {
        // TODO handle
        return null;
    }
}

Edit for OP:
The (Class<?>[])null and (Object[])null are null arguments cast as their expected type.
Basically:

*

*the getMethod method of Class takes a String representing the method's name, and a varargs of Class<?> representing its parameter types. The method we call (getInstance) takes no arguments, therefore the argument to getMethod is null, but we want to cast it as the expected argument. More info here.

*the invoke method of Method takes an Object as the target instance to invoke the method against (in our case, null since it's a class method) and a varargs of Object as the arguments. But again, your getInstance method takes no arguments, so we use null and cast it as an array of Object. More info here.

A: AbsCls[] array = new AbsCls[5]; // this create object for AbsCls
 array[0]=neededFunction("A"); // calling method from AbsCls
array[1]=neededFunction("B");// calling method from AbsCls

If you create object for super class you cant get method from sub classes
 AbsCls[] array = new A[5]; //this create object for A

You access both classes if you want to call super class method user super keyword
    array[0]=neededFunction("A"); //// calling method from A
    array[1]=super.neededFunction("B");//// calling method from AbsCls

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with 'if statement' in a php form with multiple recipients My php form has a <select> option for multiple recipients with an email address associated to each of them:
<select name="sendto">
  <option value="select">-- Select --</option>
  <option value="general">General</option>
  <option value="support">Support</option>
  <option value="sales">Sales</option>
</select>

I'm able to send and receive successfully only the 'General' option, the rest fails. It's obvious the issue is with the 'if statement' but I can't figure out what the problem is exactly. Any help? Thanks.
This is the php code:
<?php
 $to = $_REQUEST['sendto'] ;
 $from = $_REQUEST['Email'] ;
 $name = $_REQUEST['Name'] ;
 $headers = "From: $from";
 $subject = "Web Contact Data";

 $fields = array();
 $fields{"Name"} = "Name";
 $fields{"Company"} = "Company";
 $fields{"Email"} = "Email";
 $fields{"Phone"} = "Phone";
 $fields{"list"} = "Mailing List";
 $fields{"Message"} = "Message";

 $body = "We have received the following information:\n\n"; foreach($fields as $a => $b){ $body .= sprintf("%20s: %s\n",$b,$_REQUEST[$a]); }

 $headers2 = "From: noreply@my-site.com";
 $subject2 = "Thank you for contacting us";
 $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.my-site.com";

if ($sendto == 'general') {
    $to = 'alex@my-site.com';
}
else if ($sendto == 'support') {
    $to = 'alabanino@my-site.com';
}
else if ($sendto == 'sales') {
    $to = 'alabanino@my-site.com';
}
else { //other options
    $to = 'alex@my-site.com';
}

 if($from == '') { print "You have not entered an email, please go back and try again"; }
    else {
 if($name == '') { print "You have not entered a name, please go back and try again"; }
     else {
 $send = mail($to, $subject, $body, $headers, '-fnoreply@yourmailer.com');
 $send2 = mail($from, $subject2, $autoreply, $headers2);
 if($send){
     header( "Location: http://www.my-site.com/thankyou.html" );}
 else {
     print "We encountered an error sending your mail, please notify webmaster@my-site.com";
   }
 }
}
 ?>

A: Where is $sento defined? This will be 'working' cos it will be defaulting to your final else condition as all others fail.
You need to add this and it should work
$sendto = $_REQUEST['sendto']

Or else use $to insetad


text:
Q: Redis SET vs SETNX performance I have a quick question to people who are more familiar with Redis internals and perhaps know the answer.
I use socket.io and have a map of sessionID - socket(s) stored. In addition to that I use SET command to store empty value to indicate user is connected (if no sockets are associated with sessionID). To account for page reloads the DEL command is executed with a timeout. This leads to situation where I have no active sockets, but the online status is still set in Redis.
This means if user use a single tab, every page reload means the SET command is executed. What I am wondering is whether SETNX would be more performant here? Basically, would the check performed by SETNX be faster than setting the value again with SET? Assuming that the value will exist in 99.99% of cases.
My guess is that it should be faster, but perhaps there's something I don't know. So could anyone confirm my guess or explain me why SET may still be faster?

A: Generally speaking, SETNX could be slightly faster as it will not set the value sometimes. However, in your use case, the differences in performance would probably be negligible given the size of value (empty string). Test it to be certain :)


text:
Q: Compatible LITE version and Incompatible PRO I published 2 version of my app: some user do see the LITE version and don't see the PRO one.
Both build are identical except for:
the pro has this two more feature
uses-permission:'android.permission.RECEIVE_BOOT_COMPLETED'
uses-permission:'com.android.vending.CHECK_LICENSE'

this is the result using aapt tool:
LITE VERSION:
package: name='it.android.smartscreenonlite' versionCode='3' versionName='1.2'
sdkVersion:'3'
targetSdkVersion:'15'
uses-permission:'android.permission.WAKE_LOCK'
uses-permission:'android.permission.VIBRATE'
uses-permission:'android.permission.USES_POLICY_FORCE_LOCK'
uses-permission:'android.permission.DISABLE_KEYGUARD'
uses-feature:'android.hardware.sensor.proximity'
application-label:'Smart Screen ON LITE'
application-label-fr:'Smart Screen ON LITE'
application-label-es:'Encendido Inteligente LITE'
application-label-it:'Accendi Schermo Intelligente LITE'
application-icon-120:'res/drawable-hdpi/smartscreenon.png'
application-icon-160:'res/drawable-hdpi/smartscreenon.png'
application-icon-240:'res/drawable-hdpi/smartscreenon.png'
application-icon-320:'res/drawable-hdpi/smartscreenon.png'
application: label='Smart Screen ON LITE' icon='res/drawable-hdpi/smartscreenon.png'
launchable-activity: name='it.android.smartscreenonlite.ActivityImpostazioni'  l
abel='Smart Screen ON LITE' icon='res/drawable-hdpi/smartscreenon.png'
uses-feature:'android.hardware.touchscreen'
uses-feature:'android.hardware.screen.portrait'
main
other-activities
other-receivers
other-services
supports-screens: 'small' 'normal' 'large' 'xlarge'
supports-any-density: 'true'
locales: '--_--' 'fr' 'es' 'it'
densities: '120' '160' '240' '320'

PRO VERSION:
package: name='it.android.smartscreenon' versionCode='3' versionName='1.2'
sdkVersion:'3'
targetSdkVersion:'15'
uses-permission:'com.android.vending.CHECK_LICENSE'
uses-permission:'android.permission.WAKE_LOCK'
uses-permission:'android.permission.VIBRATE'
uses-permission:'android.permission.RECEIVE_BOOT_COMPLETED'
uses-permission:'android.permission.USES_POLICY_FORCE_LOCK'
uses-permission:'android.permission.DISABLE_KEYGUARD'
uses-feature:'android.hardware.sensor.proximity'
application-label:'Smart Screen ON'
application-label-fr:'Smart Screen ON'
application-label-es:'Encendido Inteligente'
application-label-it:'Accendi Schermo Intelligente'
application-icon-120:'res/drawable-hdpi/smartscreenon.png'
application-icon-160:'res/drawable-hdpi/smartscreenon.png'
application-icon-240:'res/drawable-hdpi/smartscreenon.png'
application-icon-320:'res/drawable-hdpi/smartscreenon.png'
application: label='Smart Screen ON' icon='res/drawable-hdpi/smartscreenon.png'
launchable-activity: name='it.android.smartscreenon.LicenseCheck'  label='Smart
Screen ON' icon=''
uses-feature:'android.hardware.touchscreen'
uses-feature:'android.hardware.screen.portrait'
main
other-activities
other-receivers
other-services
supports-screens: 'small' 'normal' 'large' 'xlarge'
supports-any-density: 'true'
locales: '--_--' 'fr' 'es' 'it'
densities: '120' '160' '240' '320'

Those users are already using other app which uses the same permissions (license and boot one). What's the problem?


text:
Q: How to plot a continuous standard normal PDF over a normalized histogram of real discrete data Below in code are two versions. I believe plot1 might be correct but not sure why its shifted to the left and how to fix it. plot2 is copied directly from the wolfman online documentation but using my own data. It doesn't look normalized and the continuous curve is almost flat. I know something is likely wrong with both of them. Please suggest edits.
Goal is to normalize histogram of probability density so that we have a mean at zero, standard deviation is 1, and total area under graph is 1. The graph should look similar to image:

raw = {1.32, 1.37, 1.43, 1.32, 1.36, 1.33, 1.38, 1.35, 1.48, 1.28,
   1.31, 1.52, 1.51, 1.33, 1.32, 1.27, 1.35, 1.40, 1.27, 1.39, 1.50,
   1.31, 1.34, 1.48, 1.36, 1.33, 1.40, 1.29, 1.35, 1.36, 1.33, 1.30,
   1.28, 1.32, 1.34, 1.33, 1.29, 1.34, 1.34, 1.29, 1.35, 1.52, 1.29,
   1.38, 1.40, 1.28, 1.36, 1.36, 1.32, 1.62, 1.36, 1.34, 1.33, 1.33,
   1.30, 1.31, 1.33, 1.32, 1.36, 1.41};

(* plot1 almost looks correct except for shifting from mean *)
plotHistPDF[raw_, n_ : 3] :=
 Block[{len, μ, σ, bin, hist, dist},
  len = Length[raw];
  μ = Mean[raw];
  σ = StandardDeviation[raw];
  hist = Histogram[raw, Automatic, "PDF"];
  dist = Plot[
           PDF[NormalDistribution[μ, σ], x], {x, μ - n σ, μ + n σ},
           PlotRange -> All, Filling -> Axis];
  Show[
    hist, dist,
    PlotLabel -> Style["Probabality Density Distribution", Bold, Orange],
    AxesLabel -> {x, ρ}, ImageSize -> imgsize]
  ]

(* plot2 appears correctly placed but curve is flat. should be a bell shaped curve *)
Show[
  Histogram[raw, Automatic, "PDF"],
  Plot[PDF[NormalDistribution[0, 1], x], {x, -4, 4}]
]

A: I get this plot: followed @JimB advice. Time to learn some statistics, again.

A: To summarize @JimB's comment, you should plot the PDF of the normal distribution that most closely resembles your data, i.e. the one with the same mean and standard deviation:
Show[
  Histogram[raw, Automatic, "PDF"],
  Plot[
    PDF[NormalDistribution @@ Through[{Mean, StandardDeviation}[raw]], x],
    {x, -4, 4}, PlotRange -> All,
    Filling -> Axis
  ]
]

@aooiiii also mentioned another important point. You say that the plot of the PDF is "shifted to the left and how to fix it". If you mean that the distributions seem mismatched, then you have to realize that your raw data does not appear normally distributed, with its mode a bit to the left of its mean.


text:
Q: Random reals preserving Cohen reals Suppose we have a model (of $\mathsf{ZFC}$) $M$, and that $x\in 2^\omega$ is random over $M$, and that $y\in 2^{\omega}$ is Cohen over $M$. My question is whether $y$ is also Cohen over $M[x]$. In other words, if I have a real that's Cohen over a model, is it still Cohen over the model that results from performing Random forcing?

A: That depends on the particular random real $x$ and Cohen real $y$.  On the one hand, I could first choose $x$ random over $M$ and then choose $y$ Cohen over $M[x]$.  Then $y$ is also Cohen over the submodel $M$, so it's an example where the answer to your question is yes.
On the other hand, I could first choose $y$ Cohen over $M$ and then choose $x$ random over $M[y]$.  Then $x$ is also random over the submodel $M$.  I'll show that $y$ is not Cohen over $M[x]$.
Partition $\omega$ into intervals $I_n$ of rapidly increasing length. (In fact, it suffices to take $I_n$ of length $n$, but "rapidly" avoids the need for  arithmetic.) Define a symmetric binary relation $R$ on $2^\omega$ by putting $aRb$ iff $a$ and $b$ agree on infinitely many of these intervals.  Note that, for any $a$, the set of $b$'s $R$-related to $a$ is comeager but has Lebesgue measure 0.  Note also that $R$ is a low-level Borel set with code in $M$ (provided you chose the sequence of $I_n$'s in $M$). Since $x$ is random over $M[y]$, we have that $x$ and $y$ are not $R$-related. But then $y$ cannot be Cohen over $M[x]$.


text:
Q: Am I forced to use the .cgi extension? I am going to build CGI web application and start learning that technology. I'd like to use C++. So I started my local server and put a simple script in my cgi-bin folder, compiled it with g++ test.cpp -o app (using Mac OS X) and tried to run it with: localhost/cgi-bin/app. And it worked.
But reading on the web I keep seeing examples where scripts are compiled(?) as .cgi files. Am I forced to do the same? What's the difference?

A: You don't have to specify .cgi extension.
That said, please note that the choice to use CGI and C++ for developing interactive web applications is very unusual at this point.  People pretty much stopped doing it this way some time in the 90s.
Not to say that there is never a reason to do it.
But be warned.


text:
Q: Postgres JSONB Check if JSON contains string using JPA I have a jsonb column in my posgtgres table the json is of structure : {'alias':["name1","name2","name"....]}
I have written the Postgres query to check if the array in the JSON object contains the name.
select * from public.table t where json_col->'alias' ? 'name'

this works on pgAdmin
But same doesn't work in JPA
My code
@Query(value = "select * from public.table t where json_col->'alias' ? :name" ,nativeQuery = true)
    Table findUsingName(@Param("name") String name);

This throws an error : 'Mixing of ? parameters and other forms like ?1 is not supported!'
I understand this error is due to the fact ? is also used by JPA is different sense...
Can anyone help me in the JPA Query

A: I don't know what the ? operator does, but you should use the named variant of the operator as a ? in JDBC is used to define a parameter.

A: Found the postgres function for '?' i.e. jsonb_exists_any(company_alias->'alias',ARRAY[:name])


text:
Q: How to call another function with n-parameters in typescript? I've a function manipulating a given query string. And another version of it, which always uses window.location.search. This is the declaration:
class MyClass {
  public changeQuery(query: string; exclude: boolean = true; ...values: string[]): string {
    // a lot of stuff is going on here
  }

  public getQuery(exclude: boolean = true; ...values: string[]): string {
    let args: any[] = [...values];

    args.unshift(exclude);
    args.unshift(window.location.search);

    return this.changeQuery.apply(this, args); // <-- Error here @args
  }
}

I'm getting the following error:

Argument of type 'any[]' is not assignable to parameter of type '[string, (boolean | undefined)?, ...string[]]'.
Property '0' is missing in type 'any[]' but required in type '[string, (boolean | undefined)?, ...string[]]'.

So I think let args must have another type. But how can this be defined? The other option whould be to make query: string in the function updateQuery optional (and fill it inside the function with window.location.search, if undefined is given). Is this possible, too? This would be even better I think.

A: It seems so, that Aluan Haddad gave the right answer, without creating an answer. I thought in javascript, so I was overthinking this.
public getQuery(exclude: boolean = true; ...values: string[]): string {
  return this.changeQuery(window.location.search, exclude, ...values);
}

Is working like a charm. That produces this javascript output:
getQuery(exclude = true, ...values) {
    let args = [...values];
    args.unshift(exclude);
    args.unshift(window.location.search);
    return this.changeQuery.apply(this, args);
}

That seems to be the code, I tried to produce in typescript.


text:
Q: how to add modifier passed as parameter to the end of Modifier? I have a function:
@Composable
fun sendNewSmsText(passedModifier: Modifier){
Text(text = stringResource(R.string.when_sms_not_received),
    style = Typography.body2.copy(),
    modifier = Modifier.padding(4.dp)
 )
}

how to add a passedModifier to the text's end?
like:
@Composable
 fun sendNewSmsText(modifier: Modifier){
  Text(text = stringResource(R.string.when_sms_not_received),
    style = Typography.body2.copy(),
    modifier = Modifier.padding(4.dp).passedModifier
  )
 }

A: Using Modifier.then()
https://developer.android.com/reference/kotlin/androidx/compose/ui/Modifier#then(androidx.compose.ui.Modifier)
Modifier.padding(4.dp).then(passedModifier)


text:
Q: mongodb: replica-set with load balancer Is there an option for load balancing with mongodb replica sets?
I am not asking for a HAProxy or similar, but for a built-in feature from mongodb.
Could not find tips for this in the docs.

A: The 'load balancing' is achieve via sharding. By sharding you actually distribute writes/updates onto individual shards. There is no specific algorithm that does this as mongo will let you partition the data based on whatever key(s) combination
you want.
The best partition algorithms are the ones that have a compound of sequential entries plus a random one.
For example a user id can be partitioned as follow
xx-sha1(user email)
xx = time sequence

Be aware that to implement sharding you need to have three config servers and the data nodes. The data nodes can be grouped into replica sets for redundancy and can be used (only if you can) to read data from secondaries. I say only if you can to read data because the replication is done asynchronous so is no guarantee that the new data will be available at the query time on the secondaries.
Keep in mind that the partition algorithm is totally up to you and should suit your application needs. Also you should consider if you just want to write the data and only on have occasional reads or you need to read it just after you wrote it.

A: If you are using sharding, then the "load balancer" is the mongos process - actually it is more like a router - it keeps an in-memory copy of the config database and can make decisions based on the shard key.
If you mean load balancing across identical replica sets or across the members of the set, then there is a feature request to have mongos handle that scenario too (https://jira.mongodb.org/browse/SERVER-1594), however given how the drivers operate it is not really necessary (it would make the drivers less complex though).
In a single replica set, you cannot distribute writes, they all must go to the primary.  You can distribute reads to the secondaries already, via Read Preferences as you deem appropriate.  The driver keeps track of what is a primary and what is a secondary and routes queries appropriately.


text:
Q: How many natural numbers $\leq 100$ are not of the form $n^2,n^3,n^5?$ Given a set $S$ of natural numbers lesser or equal to $100$ that are NOT of the form $n^2$, $n^3$, $n^5$, what is the cardinality of $S$?
Naturally, I just computed how many numbers are of that form and subtracted it, which gave me $84$. I was given the hint that $2^7=128>100$ but I'm not sure what to do with this information.

A: I'll assume $0$ is not a natural number.
Since $100=10^2$, there are $\color{blue}{10}$ squares up to $100$.
Since $\lfloor\sqrt[3]{100}\rfloor=4$, there are $\color{blue}4$ cubes up to $100$.
Since $2^5<100$ but $3^5>100$, there are $\color{blue}2$ fifth powers up to $100$.
There are $\color{orange}2$ sixth powers up to $100$, and $1$ is in all $\color{lime}3$ of the above sets.
So I get $\color{blue}{10}+\color{blue}4+\color{blue}2-\color{orange}1-\color{lime}2=13$ squares/cubes/fifth powers up to $100$,
which means $87$ numbers up to $100$ that are not those.


text:
Q: Apple accepts the same build I have submitted my app on iTunes Connect Individual account the last year. So, it is in iTunes now. I want to use the same code build to submit the app in iTunes Connect Organization account. What my point is if I use the same build to submit the app, will Apple accept my app? If not what is the reason?

A: There should be no problem with that - if only you change bundle ID.
But better idea is to transfer existing project to another account - than you don't have to wait for review process.
https://developer.apple.com/news/?id=6112013c

A: If you don't want transfer your app, Your app will be there in two account. It will lead to reject your binary according to duplication.
According to Section 2.11 of the App Store Review Guidelines.
you can see this line..

Apps that duplicate apps already in the App Store may be rejected, particularly if there are many of them, such as fart, burp, flashlight, and Kama Sutra apps

But  you can take advantage with your old code by below.

Re skinned template apps that simply duplicate content and/or
  functionality create clutter, diminish the overall experience for the
  end user, and reduce the ability of developers to market their
  applications. This is not in compliance with the App Store Review
  Guidelines.

A: I take it you want to remove the original app from iTunes, so there shouldn't be any problem with duplication at all - but you should remove it before submitting the new one of course :-).


text:
Q: PyQt5 mysql driver not found Under Ubuntu 17.04 I develop a Python 3 application using PyQt5 (which uses Qt5 5.8.0) and mysql (5.7.18).  All has been well recently until today, I now get upon launching:
QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QPSQL QPSQL7

This is what happens if you have not previously done a:
apt-get install libqt5sql5-mysql

but I have done that, and tried uninstalling it and reinstalling it with same result.
Running locate libqsqlmysql shows me:
/usr/lib/x86_64-linux-gnu/qt5/plugins/sqldrivers/libqsqlmysql.so
/usr/local/lib/python3.5/dist-packages/PyQt5/Qt/plugins/sqldrivers/libqsqlmysql.so

The first of these is dated Feb 9 2017, I believe it is Qt5 and not PyQt5, it ldds without error, and I do not think is relevant.
The second however is dated Jun 21 2017, so looks like the culprit.  If I go: ldd /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/plugins/sqldrivers/libqsqlmysql.so, in the output I note:
libmysqlclient.so.18 => not found
libssl.so.10 => not found
libcrypto.so.10 => not found

Am I right that is the problem?  So it's a PyQt5 issue, not a Qt5 one?  Can anyone suggest how to remedy? (I do not have an old state to revert to.)

A: Well, this turned out to be a pip3/PyCharm issue:

*

*I has previously done apt-get install python3-pyqt5.

*The apt-get install libqt5sql5-mysql had previously installed /usr/lib/x86_64-linux-gnu/qt5/plugins/sqldrivers/libqsqlmysql.so, and all was well.

*Then PyCharm made me do apt-get install python3-pip (I was lucky I recalled this), and proceeded to do some kind of pip3 install pyqt5 behind the scenes.

*This had created its own /usr/local/lib/python3.5/dist-packages/PyQt5/Qt/plugins/sqldrivers/libqsqlmysql.so, and as can be seen from the ldd output there had left the area in an incomplete/inconsistent state.

*pip3 uninstall pyqt5 removed that, and reverted me to an error-free installation.

I had previously managed to avoid any pip3, successfully installing everything via apt-get.  This experience has left me not trusting pip3 at all, if it can simply create an erroneous installation without any messages.


text:
Q: can SSL encrypt and decrypt with one key in java I have project to transfer data from client to server and I use ssl in java and I use one key to encrypt and decryption
I use keytool to create the key
server
Security.addProvider(new Provider());
        //Specifying the Keystore details
        System.setProperty("javax.net.ssl.keyStore","testkeystore.ks");
        System.setProperty("javax.net.ssl.keyStorePassword","mypass");

        // Enable debugging to view the handshake and communication which happens between the SSLClient and the SSLServer
        // System.setProperty("javax.net.debug","all");
    }

            // Initialize the Server Socket
            SSLServerSocketFactory sslServerSocketfactory = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
            sslServerSocket = (SSLServerSocket)sslServerSocketfactory.createServerSocket(intSSLport);

client
 System.setProperty("javax.net.ssl.trustStore", "/home/lap/NetBeansProjects/Dionaea-001/testkeystore.ks");
    {
        // Registering the JSSE provider
        Security.addProvider(new Provider());
    }

    try {
        // Creating Client Sockets
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)sslsocketfactory.createSocket(strServerName,intSSLport);

my questions
it is possible to use one key in SSL?
how I can know the type of encryption AES or DES?

A: The certificate and private key in your server keystore are only used for authenticating the server.
With SSL/TLS, the encryption keys are shared keys negotiated during the handshake.
You can see which encryption algorithm from the cipher suites that is used, which you can get from the SSLSession once you've established the connection. (You can get the session from the SSLSocket.)


text:
Q: Consuming ASMX WebService from WCF I am trying to consume an ASMX web service from my WCF service. Here is what I did and i get the following error.
"There was no endpoint listening at "http://... " that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
Please help me. Where I am doing wrong? What I am missing?
I created a WCF Service Library and added a reference to the ASMX web service with the help of the WSDL file provided to me.
  namespace WCFClueClient
{
        public class Service1 : IService1
    {
        public string GetData(string value)
        {
         ClueClientServiceReference.InteractiveOrderHandlerClient client = new WCFClueClient.ClueClientServiceReference.InteractiveOrderHandlerClient();
            string response = client.handleInteractiveOrder(value);
            return string.Format("You entered: {0}", response);
        }

           }
I have a console application which has refernce to my WCF service
  namespace CLUE
{
    class Program
    {
        static void Main(string[] args)
        {

            CLUETestServiceReference.Service1Client client = new CLUE.CLUETestServiceReference.Service1Client();

           string response =  client.GetData("JOHN DOE");

                }
    }
}

my app.config file
 <system.serviceModel>
<bindings>
  <basicHttpBinding>
    <binding name="InteractiveOrderHandlerBinding" closeTimeout="00:01:00"
      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
      allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
      maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
      messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
      useDefaultWebProxy="true">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <security mode="None">
        <transport clientCredentialType="None" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
  </basicHttpBinding>
  <wsHttpBinding>
    <binding name="WSHttpBinding_IService1" closeTimeout="00:01:00"
      openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
      bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
      maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
      textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
      <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
        maxBytesPerRead="4096" maxNameTableCharCount="16384" />
      <reliableSession ordered="true" inactivityTimeout="00:10:00"
        enabled="false" />
      <security mode="Message">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="Windows" negotiateServiceCredential="true"
          algorithmSuite="Default" establishSecurityContext="true" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<client>
  <endpoint address="http://alalppnc079.choicepoint.net:8280/CPRules-rfCommunicationEJB/InteractiveOrderHandlerURI"
    binding="basicHttpBinding" bindingConfiguration="InteractiveOrderHandlerBinding"
    contract="ClueClientServiceReference.InteractiveOrderHandler"
    name="InteractiveOrderHandlerPort" />
  <endpoint address="http://localhost:8731/Design_Time_Addresses/WCFClueClient/Service1/"
    binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"
    contract="WCFCLUETEstServiceReference.IService1" name="WSHttpBinding_IService1">
    <identity>
      <dns value="localhost" />
    </identity>
  </endpoint>
</client>
<services>
  <service name="WCFClueClient.Service1" behaviorConfiguration="WCFClueClient.Service1Behavior">
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8731/Design_Time_Addresses/WCFClueClient/Service1/"   />
      </baseAddresses>
    </host>
    <!-- Service Endpoints -->
    <!-- Unless fully qualified, address is relative to base address supplied above -->
    <endpoint address=""  binding="wsHttpBinding" contract="WCFClueClient.IService1">
      <!--
          Upon deployment, the following identity element should be removed or replaced to reflect the
          identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
          automatically.
      -->
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <!-- Metadata Endpoints -->
    <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
    <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="WCFClueClient.Service1Behavior">
      <!-- To avoid disclosing metadata information,
      set the value below to false and remove the metadata endpoint above before deployment -->
      <serviceMetadata httpGetEnabled="True"/>
      <!-- To receive exception details in faults for debugging purposes,
      set the value below to true.  Set to false before deployment
      to avoid disclosing exception information -->
      <serviceDebug includeExceptionDetailInFaults="False" />
    </behavior>
  </serviceBehaviors>
</behaviors>

A: Hey, in this post there is a cool explanation of that problem:Stackoverflow post
And if you don't get the trouble ... just press F5 on your solution and standup the website ... then go to your console app build file (inside debug folder) and execute the .exe.
It seems that you are trying to work with your webservice host and client at the same debugger.
Hope it helps!


text:
Q: wrong ELF class: ELFCLASS64 (Possible cause: architecture word width mismatch) I am trying to run jar for Serial Communication in Ubuntu 14.04 which requires librxtxSerial.so to be in 'jdk/bin' folder. I referred below link:
wrong ELF class: ELFCLASS32 (Possible cause: architecture word width mismatch)
I tried with both 32-bit/64-bit librxtxSerial.so in 'jdk/bin' but is stuck with both the below error :
OpenJDK Server VM warning: You have loaded library /usr/lib/jni/librxtxSerial-2.2pre1.so which might have disabled stack guard. The VM will try to fix the stack guard now.
It's highly recommended that you fix the library with 'execstack -c <libfile>', or link it with '-z noexecstack'.
java.lang.UnsatisfiedLinkError: /usr/lib/jni/librxtxSerial-2.2pre1.so: /usr/lib/jni/librxtxSerial-2.2pre1.so: wrong ELF class: ELFCLASS64 (Possible cause: architecture word width mismatch) thrown while loading gnu.io.RXTXCommDriver
Exception in thread "main" java.lang.UnsatisfiedLinkError: /usr/lib/jni/librxtxSerial-2.2pre1.so: /usr/lib/jni/librxtxSerial-2.2pre1.so: wrong ELF class: ELFCLASS64 (Possible cause: architecture word width mismatch)
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary1(ClassLoader.java:1968)
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1893)
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1883)
        at java.lang.Runtime.loadLibrary0(Runtime.java:849)
        at java.lang.System.loadLibrary(System.java:1088)
        at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
        at test.Test.main(Test.java:32)

Java Version : 1.7 64-bit
Ubuntu OS Release :
NAME="Ubuntu"
VERSION="14.04.1 LTS, Trusty Tahr"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 14.04.1 LTS"
VERSION_ID="14.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

When I tried to run it with JAVA 1.8 it gave following error
Error: Could not find or load main clas test.Test (//My jar name is Test)


text:
Q: getParent() is null in onResume inside TabHost child activity I have a tabhost widget which starts different activies by using Intents.
TabSpec tab = mTabHost.newTabSpec("profile");
tab.setIndicator("profile");
Intent i3 = new Intent(ctx, ProfileActivity.class);
tab.setContent(i3);
mTabHost.addTab(tab);

All childs are defined as embeded:
    <activity android:exported="false" android:name="com.example.app.ProfileActivity" android:label="ProfileActivity view">
       <intent-filter>
          <category android:name="android.intent.category.EMBED"></category>
          <action android:name="android.intent.action.MAIN"></action>
       </intent-filter>
    </activity>

Unfortunately I can see an occasional crash inside my ProfileActivity onResume function.
It crashes on this line, because getParent() returns null.
((MainActivity) getParent()).goToTab("splash")

It's not happening all the time - it's very occasional.
Anyone had this problem?

A: As Documentation says: public final Activity getParent () Since: API Level 1
Returns the parent activity if this view is an embedded child.
Is your Activity an embedded child? If yes then it will return parent activity context otherwise null


text:
Q: xamarin android: Hamburger menu items disappear when app is built in release When i build my xamarin.forms app in debug for android, i see the hamburger menu items, however as soon as i build in release mode, they disappear. This is specifically occuring in the android project,im using masterdetailpages, and this happens in the master page.
any help will be appreciated. The following is the code the master page:
    <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"      x:Class="myApp.ViewAndViewModels.BookMasterDetailPageMaster"
             xmlns:local="clr-namespace:myApp.ViewAndViewModels;assembly=myApp"
             Title="☰" BackgroundColor="#91D8F7">
    <StackLayout>
        <ListView x:Name="MenuItemsListView"
              SeparatorVisibility="None"
              HasUnevenRows="true"
              ItemsSource="{Binding MenuItems}">
            <ListView.Header>
            <StackLayout BackgroundColor="#91D8F7">
                <Image x:Name="AppImage" BackgroundColor="#91D8F7"></Image>
                <Label Text="Menu" HorizontalOptions="CenterAndExpand"
               VerticalOptions="CenterAndExpand" FontSize="31">
                       <Label.FontFamily>
                                    <OnPlatform x:TypeArguments="x:String">
                                        <On Platform="iOS" Value="Alvi Nastaleeq" />
                                        <On Platform="Android" Value="Alvi Nastaleeq.ttf#Alvi Nastaleeq" />
                                        <On Platform="UWP">/Assets/Fonts/Alvi Nastaleeq.ttf#Alvi Nastaleeq</On>
                                    </OnPlatform>
                                </Label.FontFamily>
                </Label>
            </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
<Grid Grid.Row="1" ColumnSpacing="0" >

                        <StackLayout Grid.Row="1"
                                     Orientation="Horizontal"
                                     Spacing="0"
                                     Margin="0,0">
                          <Image Source="{Binding IconImageSrc}" WidthRequest="32" HeightRequest="32"></Image>

                          <Label Text="{Binding Title}" HorizontalOptions="CenterAndExpand"
               VerticalOptions="CenterAndExpand" FontSize="30">
                                <Label.FontFamily>
                                    <OnPlatform x:TypeArguments="x:String">
                                        <On Platform="iOS" Value="Alvi Nastaleeq" />
                                        <On Platform="Android" Value="Alvi Nastaleeq.ttf#Alvi Nastaleeq" />
                                        <On Platform="UWP">/Assets/Fonts/Alvi Nastaleeq.ttf#Alvi Nastaleeq</On>
                                    </OnPlatform>
                                </Label.FontFamily>
                            </Label>
                        </StackLayout>
                        </Grid>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class BookMasterDetailPageMaster : ContentPage
    {
        public ListView ListView;

        public BookMasterDetailPageMaster()
        {
            InitializeComponent();
            AppImage.Source = ImageSource.FromResource("myApp.Assets.MainMenuIcon.png");

            BindingContext = new BookMasterDetailPageMasterViewModel();
            ListView = MenuItemsListView;
        }

        class BookMasterDetailPageMasterViewModel : INotifyPropertyChanged
        {
            public ObservableCollection<BookMasterDetailPageMenuItem> MenuItems { get; set; }
            public ImageSource IconImageSource { get; set; }

            public BookMasterDetailPageMasterViewModel()
            {
                IconImageSource = ImageSource.FromResource("myApp.Assets.Icons.articon.png");

                MenuItems = new ObservableCollection<BookMasterDetailPageMenuItem>(new[]
                {
                    new BookMasterDetailPageMenuItem { Id = 1, Title = "Menu1",IconImageSrc = this.IconImageSource,TargetType = typeof(Menu1) },
                    new BookMasterDetailPageMenuItem { Id = 2, Title = "Menu2", IconImageSrc = this.IconImageSource },
                    new BookMasterDetailPageMenuItem { Id = 3, Title = "Menu3", IconImageSrc = this.IconImageSource },
                    new BookMasterDetailPageMenuItem { Id = 4, Title = "Menu4", IconImageSrc = this.IconImageSource },

                });
            }

            #region INotifyPropertyChanged Implementation
            public event PropertyChangedEventHandler PropertyChanged;
            async void OnPropertyChanged([CallerMemberName] string propertyName = "")
            {
                if (PropertyChanged == null)
                    return;

                //PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            #endregion
        }
    }

A: I'm only answering cause I can't comment yet, so you can count this as a comment
You need to provide more information, code snippets or examples if you can't share your code.

A: I managed to solve the problem. In my particular case, i was using Dotfuscator for the xamarin android project in release, and as soon as i disabled this, the menu items started to show.


text:
Q: Create a running total in SQL with hours but only using work hours This might be a strange question... but will try to explain the best i can ...
BTW : There is no chance in implementing through Stored Procedures... it should be made in SQL Query only ... But if the only option is SP, then i have to adapt to that ...
I have a table with the following elements :

RUN
WORKORDER
LOCATION
TRAVELTIME
NUMEQUIP
TOT_TIME

NO99
1
Start

NO99
2
Customer 1
112
1
8

NO99
3
Customer 2
18
11
88

NO99
4
Customer 3
22
93
744

NO99
5
Customer 4
34
3
24

I need to add a running DATE and HOUR by calculating the amount of time it takes from one line tho another BUT, and this is important, to take into consideration working hours ( from 9:00 to 13:00 and from 14:00 to 18:00 ( in US format : from 9am to 1pm, and 2pm to 6pm)... As example ... considering that my start date and time would be 10/May/2022 9:00 :

RUN
WORKORDER
LOCATION
TRAVELTIME
NUMEQUIP
TOT_TIME
DATE
TIME

NO99
1
Start

10/05/22
9:00

NO99
2
Customer 1
112
1
8
10/05/22
10:52

NO99
3
Customer 2
18
11
88
10/05/22
11:18

NO99
4
Customer 3
22
93
744
10/05/22
14:08

NO99
5
Customer 4
34
3
24
12/05/22
10:06

This result is achieved by calculating the estimated time to make the trip between customers (TRAVELTIME), and after arriving is also added the time spent on maintenance (TOT_TIME that is Number of Equipments (NUMEQUIP) vs 8 minutes per equipment)... By this, and since customer 3 will have 744 minutes (12 h and 58 minutes) in maintenance... and those minutes will spawn through 3 days, the result should be as shown...
With the following query i can have almost the desired effect... but cannot take into account only work hours ... and all time is continuous...
Select
     RUN,WORKORDER,LOCATION,TRAVELTIME,
     DateAdd(mi,temprunningtime-TOT_TIME,'9:00') As TIME,
     NUMEQUIP,NUMEQUIP*8 AS TOT_TIME,sum(MYTABLE.TRAVELTIME +
     MYTABLE.TOT_TIME) OVER (ORDER BY MYTABLE.ORDER) AS temprunningtime
FROM   MYTABLE

With this query (slightly altered) i get an running TIME, but does not take into account the 13:00-14:00 stop, and the 18:00-9:00 stop...
It might be a bit confusing but any ideias on this would be very appreciated... and i will try to explain anyway i can...


text:
Q: Android: Install ADT locally I have already had the  necessary ADT plugins for Android programming in Eclipse.
(Eclipse Java EE IDE for Web Developers.
Version: Kepler Service Release 1
Build id: 20130919-0819)
I know the common way to install them is this link
(to download and install them), but i am curious about installing them when they are exist in my local machine?
Thanks

A: Download from android developers site herelink

A: You should download from Android developer site http://developer.android.com/sdk/installing/installing-adt.html#Troubleshooting,
e.g. ADT-22.2.1


text:
Q: \Locale::getDefault() returns always 'en' in Symfony deployed on the server When I call \Locale::getDefault() In my Symfony2 application i get always 'en' when on server.
In dev server is always ok.
In any case $request->getLocale() and $request->getDefaultLocale() return what is expected, i.e. 'fr', 'en', 'es' depending on the route.
How can I influence \Locale over the application depending on my Request ?

A: You have to enable intl in your php.ini : intl.default_locale = fr.
And install intl for php : sudo apt-get install php7.0-intl


text:
Q: Autofac Random Parameterless public constructor. Error I have an MVC/WebApi app.  I started using Autofac for this solution.
Autofac works.  However, randomly I'll receive the error:
An error occurred when trying to create a controller of type 'SomeController'. Make sure that the controller has a parameterless public constructor.
When I clean the solution and rebuild.  And no more error.  I thought it was my instance of Visual Studio (maybe need to run repair).  However, I just tried to release to IIS and I received the error again.
Has anybody encountered this before and can anybody help me out?
Here's Some Code Details:
I have all registrations are done in modules like so:
public class CryptographyModule :  Module
{
    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<AesCryptographyService>()
            .As<IAesCryptographyService>()
            .InstancePerRequest();
    }
}

and I'm using this for bootstrapping Autofac:
public static class Bootstrapper
{
    public static void Run()
    {
        BootStrapAutofac();
    }

    private static void BootStrapAutofac()
    {
        var builder = new ContainerBuilder();
        var localAssemblies = GetLocalAssemblies();
        builder.RegisterApiControllers(localAssemblies);
        builder.RegisterControllers(localAssemblies);
        builder.RegisterAssemblyModules(localAssemblies);

        //build container
        var container = builder.Build();
        var webApiResolver = new AutofacWebApiDependencyResolver(container);
        GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

        var mvcResolver = new AutofacDependencyResolver(container);
        DependencyResolver.SetResolver(mvcResolver);

    }

    private static Assembly[] GetLocalAssemblies()
    {
        return AppDomain.CurrentDomain.GetAssemblies()
            .Where(a => a.GetName().Name.StartsWith("Loc"))
            .ToArray();
    }
}

A: I had a problem like this. My problem was that I wasn't setting DependencyResolver.SetResolver(); and GlobalConfiguration.Configuration.DependencyResolver in the application entry point (Global.asax, Application_Start). So ASP.NET couldn't resolve my dependencies in my controller and then I got the same exception.
Setting the dependencies resolvers at the first moment the application starts, solved my problem.
In your case, as you're saying that cleanning and rebuild the solution works, maybe the problem is how you getting the assemblies to register in Autofac. Try log every assembly that is being registered when you call GetLocalAssemblies and see if the assemblies that have the controllers and the assemblies that have the dependencies are being registered.

A: In my case, I simply wasn't looking deep enough in the stack trace.  Deeper down in the inner exceptions was the actual error, probably due to Autofac not being able to locate a dependency.


text:
Q: How can I tell if my paypal certificate is SHA-256? - PayPal service upgrades I use IPN endpoints and have received emails from paypal saying PayPal is upgrading the certificate for www.paypal.com to SHA-256.
I just want to make sure my certificate will keep working.
I have tried checking on https://shaaaaaaaaaaaaa.com, https://shachecker.com, www.sslshopper.com/ssl-checker.html but none will check it (I assume they all require an https site, which mine isn't?).
I have tried a transaction though the sandbox and this works fine.
I have run openssl s_client -connect www.sandbox.paypal.com:443 -showcerts -CApath /etc/ssl/certs/ on my ubuntu server and see a lot of information ending in Verify return code: 0 (ok) it then just hangs. Does that mean there is a problem? What am I looking for in this information?
(If I run the same for www.paypal.com it pauses on the Verify line, then says closed)

A: Here are the details for the Certificate Upgrade:
Merchant Response Guide
Certificate FAQ
This comes from the Merchant Response Guide:

Our Response:
    In accordance with industry standards, PayPal will no longer accept secure
  connections to the API/IPN endpoints that are expecting our Certificate/trust chain to be signed by the G2 Root Certificate. Only
  secure connection requests that are expecting our certificate/trust chain to be signed by the G5 Root Certificate will result in successful secure
  connections.

Here is how to check your Certificate through Linux. This comes from GitHub:
How to Check All Certificates through Linux
#!/bin/bash

echo "All certificates in ca-certificates.crt, listed by subject:"
awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt

echo "All certificates in ca-certificates.crt, listed by subject, check for presence of VeriSign's 'Class 3 Public Primary - G5':"
awk -v cmd='openssl x509 -noout -subject' '/BEGIN/{close(cmd)};{print | cmd}' < /etc/ssl/certs/ca-certificates.crt | grep "G5"


text:
Q: Facebook comment box plugin I am using Facebook comment box plugin:
<fb:comments href="${myPageUrl}" num_posts="20" width="630"></fb:comments>

Every thing is working fine. The problem is that I want to store the comment posted into my database. Is there any way to fetch the text posted on the comment box.
I am using the following js to catch comment-create event.
FB.Event.subscribe('comment.create', function(response) {
        alert(response.commentID)
});

I'm getting some commentId from this but I don't know how to fetch the exact comment posted on a particular comment-create event.

A: Coomie: Actually whenever a comment is posted, I catch the event thru 'comment.create'. I was able to catch the event but I was wondering how to get the comment(text) posted at that particular event. Like event.text or event.comment but there was no direct method found
So, now I am manipulating it with fql. Which is somewhat similar to you example. First retrieving the whole list and then selecting the top one.
My sample code is below:
FB.Event.subscribe('comment.create', function(response) {
      FB.api({
        method: 'fql.query',
        query: "SELECT post_fbid, fromid, object_id, text, time from comment WHERE  object_id in (select comments_fbid from link_stat where url ='${PageUrl}') order by time desc limit 1"
      },
      function(response) {
        var feed = response[0];
        alert(feed.text)
      });
});

So this method is giving me exactly the same result I want.

A: I don't have the complete answer but this should get you on your way.
You can use the facebook graph api to extract information about an open graph id (an open graph id is FB's way of identifying a person, website, application or URL). Eg. this page:
http://www.inhousegroup.com.au/newsroom/23-best-practice-for-advanced-seo/ (the place that fired me)
uses a comment box. The web page has an open id of 10150441190653416. So when you comment on this page facebook sees your comment as a wall post on that page's "wall".
Using the graph api, you can get some JSON info about the page here:
http:/graph.facebook.com/10150441190653416
And you can get the posts from this address:
http://graph.facebook.com/10150441190653416/posts
But you'll have to get an access token.
Then you just have to import the posts on save and compare your db to the JSON and add records as neccessary.
Good luck!

A: FB.Event.subscribe('comment.create', function(response) {
  var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
  FB.Data.waitOn([commentQuery], function () {
    text = commentQuery.value[0].text;
    // Use your preferred way to inform the server to save comment
    $.post( 'http://example.com/comment', text )
  });
});


text:
Q: Cannot see the message body in activeMq when message sent through wso2 esb I am new to this.I created a jms message store in wso2 esb and sent a message to it.message was received in activeMq but cannot see the message body in Activemq.
Message Details:
org.apache.synapse.message.store.impl.commons.StorableMessage@79f1d1d8

A: As ESB using jms message stores to store messages as objects, you can't see the message body via activemq. You can use message processor to get messages from the store and then use it in whatever the process you want.
As ESB use message store purely for storing process, it will use exact format. That is why you have to use processors to work with stored messages.


text:
Q: formulario para reserva de fechas ¿Como puedo hacer para comparar las fechas que tengo ya en MySQL con las que acabo de ingresar para saber si están disponibles?
Tengo un programa para reservar las fechas con horario de dos rampas que se tienen en la empresa, pero al momento de querer obtener los datos que ya están en MySQL para que los compare con los nuevos, al parecer no lo hace por que me sigue apareciendo el mensaje de "FECHA Y HORA RESERVADA CORRECTAMENTE", aunque esté dentro del rango de fechas ya reservadas.
Les comparto el código:
<?php

include('db.php');

if (isset($_POST['save_solicitud'])) {

  $sql = "SELECT fechahoradel, fechahorahasta FROM solicitud";
  $resultado = mysqli_query($con, $sql);
  $del = $fechahoradel;
  $hasta = $fechahorahasta;
  $dbdel = $row['fechahoradel'];
  $dbhasta = $row['fechahorahasta'];

  if (($del >= $dbdel && $hasta <= $dbhasta) || ($del <= $dbdel && $hasta >= $dbhasta)) {

  } else {
    $nombre = $_POST['nombre'];
    $area = $_POST['area'];
    $rampa = $_POST['rampa'];
    $fechahoradel = $_POST['fechahoradel'];
    $fechahorahasta = $_POST['fechahorahasta'];
    $comentarios = $_POST['comentarios'];
    $query = "INSERT INTO solicitud (nombre, area, rampa, fechahoradel, fechahorahasta, comentarios) VALUES ('$nombre', '$area', '$rampa', '$fechahoradel', '$fechahorahasta', '$comentarios')";
    $result = mysqli_query($conn, $query);
    if (!$result) {
      die("Query Failed.");
    }
  }

  $_SESSION['message'] = 'FECHA Y HORA RECERVADA CORRECTAMENTE';
  $_SESSION['message_type'] = 'success';

  header('Location: index.php');
}
?>


text:
Q: Converting float values of big endian to little endian using C# Is it possible to convert floats from big to little endian? I have a value from a big endian platform that I am sending via UDP to a Windows process (little endian). This value is a float, but when I am trying BitConverter.ToSingle I always get 5.832204E-42, but it should be 36.000.
What am I doing wrong?
Here is a code snipped:
// Receive thread
private void ReceiveData()
{
    int count = 0;

    IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("10.0.2.213"), port);
    client = new UdpClient(remoteIP);
    while (true)
    {
        try
        {
            IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
            byte[] data = client.Receive(ref anyIP);

            float x = BitConverter.ToSingle(data, 0);
            float y = BitConverter.ToSingle(data, 4);
            float z = BitConverter.ToSingle(data, 8);
            float alpha = BitConverter.ToSingle (data, 12);
            float theta = BitConverter.ToSingle (data, 16);
            float phi = BitConverter.ToSingle (data, 20);

            print(">> " + x.ToString() + ", "+ y.ToString() + ", "+ z.ToString() + ", " +
                  alpha.ToString() + ", "+ theta.ToString() + ", "+ phi.ToString());

            // Latest UDP packet
            lastReceivedUDPPacket=x.ToString()+" Packet#: "+count.ToString();
            count = count+1;
        }

A: 36.0 and 5.832204E-42 are endian-opposites, so this is an endianness problem. On Windows / .NET, you are usually little-endian, so I'm guessing the data is big-endian. That means you need to reverse the data for each value, separately (not the entire array).
To write this in a way that is CPU-safe, the best option is to check BitConverter.IsLittleEndian, and compensate when necessary. For example:
public static float ReadSingleBigEndian(byte[] data, int offset)
{
    return ReadSingle(data, offset, false);
}
public static float ReadSingleLittleEndian(byte[] data, int offset)
{
    return ReadSingle(data, offset, true);
}
private static float ReadSingle(byte[] data, int offset, bool littleEndian)
{
    if (BitConverter.IsLittleEndian != littleEndian)
    {   // other-endian; reverse this portion of the data (4 bytes)
        byte tmp = data[offset];
        data[offset] = data[offset + 3];
        data[offset + 3] = tmp;
        tmp = data[offset + 1];
        data[offset + 1] = data[offset + 2];
        data[offset + 2] = tmp;
    }
    return BitConverter.ToSingle(data, offset);
}

with:
float x= ReadSingleBigEndian(data, 0);
float y= ReadSingleBigEndian(data, 4);
float z= ReadSingleBigEndian(data, 8);
float alpha= ReadSingleBigEndian(data, 12);
float theta= ReadSingleBigEndian(data, 16);
float phi= ReadSingleBigEndian(data, 20);


text:
Q: Is this a basis for the Scott topology on the collection of open sets of a topology? If $\mathcal{O}(X)$ is the collection of open sets in the topological space $X$ ordered by inclusion and $K\subseteq X$ is a compact subset of $X$ then it is easy to see that:
$$\mathscr{U}_K = \{O\in\mathcal{O}(X) : K\subseteq O\}$$
is open in the Scott topology on $\mathcal{O}(X)$. If $X$ is finite then the collection $\{\mathscr{U}_K:K\ \mbox{compact in}\ X\}$, is clearly a basis for this topology.
My question is: Is this collection always a basis for the Scott topology on $\mathcal{O}(X)$?


text:
Q: Number of days between 2 dates I am trying to figure out how to find the difference between 2 dates in days, however when trying the following:
DateTime O = d_out;
DateTime I = d_in;
TimeSpan span = I.Subtract(O);
var days = span.Days;

( d_out & d_in are variables holding date values)
It returns the difference between days only and doesn't return the number of days for months and year.
To give you a clearer understanding the code above returns "-1" for difference between dates "06/08/18"(06 Aug 18) & "05/09/18"(05 Sept 18), how can i get it to output "30" instead?

A: span.TotalDays will give you the total number of days
Yes it does
using System;
public class Program
{
    public static void Main()
    {
        var d1=DateTime.Parse("1/2/18");
        var d2=DateTime.Parse("2/3/18");
        Console.WriteLine(d2.Subtract(d1).TotalDays);
    }
}

outputs 32
See my Fiddle

A: I have run this in the C# interactive and works just fine:
var start = new DateTime(2018, 8, 6);
var end = new DateTime(2018, 9, 5);
var span = end - start;
span.Days
30

Are you sure it's not some date formatting issue like e.g. you are running with  american locale that interprets first number as month?
I would suggest that you verify in debug which exact dates do you have after both variables are assigned.

A: You're parsing months as minutes. In DateTime string formatting, M is month and m is minute.
using System;

public class Program
{
  public static void Main()
  {
      var d1=new DateTime(2018, 1, 6, 0, 8, 0);
      var d2=new DateTime(2018, 1, 5, 0, 9, 0);
      var span = d2.Subtract(d1);
      Console.WriteLine(span.TotalDays);
      Console.WriteLine(span.Days);
  }
}

Result:
-0.999305555555556
0


text:
Q: How did my coworker manage to make git checkout move files? Normally when you:

*

*git checkout foo

*Modify a file

*git checkout bar
Git will tell you that you can't change branches because you have un-committed modifications. (I don't have the exact message in front of me, but it's something to that effect).  You then normally use git stash to get rid of those modifications, and you're on your merry way.
My coworker (who is new to Git and therefore is not intentionally doing anything advanced) doesn't have that behavior.  On her machine, when she does git checkout bar, it just moves the modifications that she made on foo into bar.  This is very confusing to me, as I've been using Git for at least a year now and never seen it behave that way.
What could my coworker possibly have done to make it so that Git simply moves un-added/un-committed modified files between branches, rather than complaining and requiring git stash?

A: (I just wrote up the following text here for coworkers yesterday who are new to Git. Hope it helps.)
If you have made changes to files on branch A and want to switch to branch B (which is unrelated), then it's a good idea to commit the changes to branch A first. This way, the changes will still be on branch A when you come back to it later. (Another option is called "stashing", which is useful in some situations – see http://schacon.github.com/git/git-stash.html for more information.)
If you don't commit the changes first, then there are two situations that can arise. Consider a file "file.txt", and branches A and B. The two situations are:

*

*The latest version of file.txt on branch A and branch B is identical. In this case, a "git checkout B" will carry over the changes to file.txt to your working directory after successfully switching to branch B. This can be useful for things like changes to platform configuration files. Git will list the files carried over in this way in the output of the "git checkout" command.

*The latest versions of file.txt on branch A and branch B are different. When you ask to switch branches to branch B, git will refuse to switch branches because doing so would overwrite your changes to file.txt. You'll get a message from git saying that you must commit (or stash) the conflicting file(s) first.

If you have more than one changed file, then any file in situation (2) will prevent a branch switch.
Finally, if you want to discard modifications to a file, use a command like "git checkout -- file.txt". This will throw away any uncommitted modifications to file.txt and restore it to the latest committed version from your current branch.

A: "Normal" is actually what you co-worker sees. When there is some modification in your working directory and you switch to another branch, the changes will be available on that branch as well.
When you do get the message that you cannot switch is when the branch you are on and the branch you are switching to have diverged ( with respect to the files that are modified in the working directory) As long as the branches you are switching between have the same version for the files that are modified in the working directory, you will be able to switch branches.
Test:
git init .
touch a
git add a
git commit -m "adding a"
git branch temp
vi a #add something
git checktout temp # allows you to change
git commit -am "content in a"
vi a #add more content
git checkout master #won't allow you to change!


text:
Q: Recording an IR signal and playing it again on Raspberry Pi bullseye I have a Teco aircon with an ifrared remote. I connected an IF receiver and an IF transmitter to my Pi and they are working fine.
EC systems are different to TVs, in that they send a rather long sequence of information each time you press a button. irrecord fails miserably trying to get what button you pressed. All it gets is the gap (50000) and the frequency (38000).
I got strong inspiration from this post on doing this. So...
First, I record what's being sent:
ir-ctl -rTEMPERATURE.txt --mode2 -r --device=/dev/lirc1 -1

This is a specific mode, with a specific temperature.
The file is saved and looks like this:
pulse 3117
space 1536
pulse 487
space 1093
pulse 487
space 1095
(...227 lines...)
space 1061
pulse 516
space 300
pulse 517

I then try and resent the exact same thing to my aircon:
ir-ctl -d /dev/lirc0 -sTEMPERATURE.txt -g 50000 --carrier 38000

But nothing happens. The aircon doesn't seem to respond.
(Note that I know the transmitter is working, because I tried to run the sending and the receiving at the same time, and the receiver acknowledged receiving data.)
I tried different "carrier" options, and none of them worked.
So, questions:

*Why isn't the aircon getting the message?

*How do I translate "TEMPERATURE.txt" in actual data (that is, bytes)

*If I manage to do (1), how do I then send that rather than a bunch of pulses?
Am I doing this fundamentally wrong?
I spent my whole week end on this... and am frankly at my wits' end. I will deeply appreciate any hints.
UPDATE Things got much weirder. I looked at the actual pulses and spaces and translated them into actual on/off bits and then bytes. The result was alarming: no matter what button I press, the end result is always always C4D36440020000000A6 (in hexadecimal). The length of pulses and spaces varies a little but that is ALWAYS the end result. But surely, it can't be...? Surely different keys should provide different data?


text:
Q: Finding the ip address of another computer on the network? Is there a program which can tell me the ip address of a computer when is connected to my network?  A list of names or ip addresses.
For example when my wife is on my main desktop computer I can either go on another desktop or laptop and work.  However I don't know the ip address of the computer she's on it's dhcp and no static ip addresses.  I would like to ssh into the main desktop and work on it.  Sometimes I have asked her if I could get on for a minute to get the ip address.  From a terminal I do an ifconfig and get the address.    I could get it from the router too but that is requires logging into the router. There must be some short command I can run?  All the computers are  running Ubuntu and samba is not installed. Once I know the ip address I can ssh into the main desktop.

A: you could try nmap, if you don't have it, it can be installed via the following :-
sudo apt-get install nmap

you can then scan your network by issuing :-
nmap -sP 192.168.1.0/24

obviously change address range if your network differs

A: Modern releases of Ubuntu use avahi, so one could also use avahi-discover
sudo apt-get install avahi-discover

and run with:
avahi-discover

this allows you to view all the machines on the network and see the IP address, MAC address and services running on these machines.
Alternatively one could use:
avahi-browse -rat

A: Just as apacheuk mentionned, using nmap is a great and efficient way.
Actually the -O option enables you to get additional informations such as the MAC address, the open ports, the OS type, the distance (in hops):
nmap -O 192.168.1.0/24

Please note that you main need to be logged in as root or sudo in order to be able to do that.

A: You can login to your router and look at the connected devices list
Here is another way :
You can login using the computer name of the client
So run cat /etc/hostname on your wifes computer, you may get something like wife-System-Product-Name if that is the case you can run ssh wife@wife-System-Product-Name.local and login without using the ip address, that address only changes if you edit the /etc/hostname and /etc/hosts files or do a reinstall and give the system a new name


text:
Q: Converting sqlite3 database to PyQt QCompleter/QStringListModel Ok so, I'm setting up a QLineEdit that uses QCompleter with QStringListModel.
I'm trying to setup the QStringListModel to setStringList to a dynamic list that is pulled from my sqlite3 database.
I've tried multiple ways but this seems to be the closest I've got. When I print new_list I can see the list print the database titles but when I try to pass the titles to the setStringList as a variable the program will run but when I search a string there's no auto completion.
Here's the source code that will allow easy testing:
import sys
import sqlite3
import time
import datetime
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic.properties import QtGui

conn = sqlite3.connect('gamedatabase.db')
c = conn.cursor()

class window(QMainWindow):

    # Defines Initial Window Settings
    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(650, 300, 500, 400) # window geometry
        self.home()

    def home(self):
        self.edit = QLineEdit(self)
        self.edit.move(250, 250)
        self.completer = QCompleter()
        self.edit.setCompleter(self.completer)
        self.model = QStringListModel()
        self.completer.setModel(self.model)
        self.get_data()
        self.show()

    def get_data(self):
        c.execute(" SELECT title FROM gamedatabase ")
        results = c.fetchall()
        new_list = [i[0] for i in results]
        print(new_list) # Test print
        self.model.setStringList(new_list) #From here up I was able to get the
        # code to work but there's no auto completion in the QLineEdit.
def run():
    app = QApplication(sys.argv)
    Gui = window()
    sys.exit(app.exec_())

if __name__ == "__main__":
    run()

I've tried:
self.model.setStringList(['this', 'will', 'work',) # This will work.
self.model.setStringList([new_list]) # Does not work, returns error
# (TypeError: index 0 has type 'list' but 'str' is expected)

I've tried googling as much as I could but there doesn't seem to be much information about using PyQt or Sqlite3 in depth. I'm new to python so if there's any forums I've overlooked or missed that provides in depth information into some of these modules please let me know as I'd really appreciate it.
Thanks in advance.
TLDR: Select all game titles from sqlite3 database and set to setStringList for QCompleter and QStringListModel.


text:
Q: lmfit 'Parameters' object has no attribute '_asteval' I have just updated lmfit package to version 0.9.15 in Python 2.7 64b, and the following error is raising when creating a new Parameters object (i.e. p = lmfit.Parameters()):
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "C:\Python27_64b\lib\site-packages\lmfit\parameter.py", line 65, in __init__
    super(Parameters, self).__init__(self)
  File "C:\Python27_64b\lib\collections.py", line 48, in __init__
    self.update(*args, **kwds)
  File "C:\Python27_64b\lib\site-packages\lmfit\parameter.py", line 87, in update
    for sym in other._asteval.user_defined_symbols():
AttributeError: 'Parameters' object has no attribute '_asteval'

I just tried this example from link:
import numpy as np
import lmfit
def double_exp(x, a1, t1, a2, t2):
    return a1*np.exp(-x/t1) + a2*np.exp(-(x-0.1) / t2)

model = lmfit.Model(double_exp)
truths = (3.0, 2.0, -5.0, 10.0)
x = np.linspace(1, 10, 250)
np.random.seed(0)
y = double_exp(x, *truths)+0.1*np.random.randn(x.size)
p = model.make_params(a1=4, t1=3, a2=4, t2=3)

but it did not work. Therefore I tried to create a Parameters object from lmfit:
import lmfit

p = lmfit.Parameters()

but it did not work either.
I am using the following versions:

*

*Python 2.7 64b

*lmfit 0.9.15

*numpy 1.16.5

*uncertainties 3.1.2

*six 1.11.0

*asteval 0.9.16

I would appreciate if you could help me out.
SOLUTION:
The problem was the version of Python 2.7. I updated to Python 2.7.17, and now it works!
Pablo.

A: Please do as follows:
pip uninstall lmfit==0.9.15
pip uninstall asteval==0.9.16

And Then again install it as following sequence:
pip install asteval==0.9.16
pip install lmfit==0.9.15


text:
Q: Error: message "with parameters optimization using mlr3" I am using parameters optimization (random search) with mlr3 but it gives me the following error. I tried with other models too (kknn) but the same error comes in.
Error: Resampling 'cv' may not be instantiated

///My code is here

data = readARFF("xerces.arff")
index= sample(1:nrow(data), 0.7*nrow(data))
train= data[index,]
test= data[-index,]
task = TaskRegr$new("data", backend = train, target = "bug")

learner5=lrn("regr.randomForest")
resampling_cv = rsmp("cv", folds = 10L)
resampling_cv$instantiate(task)
measure= msr("regr.mae")

search_space = paradox::ParamSet$new(
 params = list(paradox::ParamInt$new("ntree", lower = 100, upper = 500)))

terminator = trm("evals", n_evals = 30)
tuner = tnr("random_search")

at = AutoTuner$new(
        learner = learner5,
        resampling = resampling_cv,
        measure = measure,
        search_space = search_space,
        terminator = terminator,
        tuner = tuner,  store_tuning_instance = TRUE,
        store_benchmark_result = TRUE,
        store_models = TRUE
)

A: You instantiate the resampling with resampling_cv$instantiate(task). Remove this line and it should work.


text:
Q: PIL.Image vs skimage.io: When to use each, and which (if one) is prefered over the other in general? I have been using Image for opening and getting pixel info, and have read things like "PIL is the future and blabla..", but I have seen that skimage is extensively used.
Which one should I use for general image processing? I would feel more comfortable with this question answered..

A: In general it is safe to say that Pillow (install this rather than PIL as Pillow is maintained) is the one to go for if you are manipulating Image->Image as this is its main focus.
However, if you are reading an image for manipulation by other science kit based tools, such as machine learning, then go for skimage.io or better its replacement imageio thanks to @cris-luengo for pointing this our and you are likely to have to do less conversion back and forth.
The other consideration is the size:
Results of pip download scikit-image to a Windows 64 machine:
21/10/2022  06:20         3,363,278 imageio-2.22.2-py3-none-any.whl
21/10/2022  06:20         2,023,640 networkx-2.8.7-py3-none-any.whl
21/10/2022  06:20        14,643,698 numpy-1.23.4-cp310-cp310-win_amd64.whl
21/10/2022  06:20            40,750 packaging-21.3-py3-none-any.whl
21/10/2022  06:20         3,276,402 Pillow-9.2.0-cp310-cp310-win_amd64.whl
21/10/2022  06:20            98,338 pyparsing-3.0.9-py3-none-any.whl
21/10/2022  06:20         4,162,789 PyWavelets-1.4.1-cp310-cp310-win_amd64.whl
21/10/2022  06:20        12,044,719 scikit_image-0.19.3-cp310-cp310-win_amd64.whl
21/10/2022  06:20        40,141,232 scipy-1.9.3-cp310-cp310-win_amd64.whl
21/10/2022  06:20           210,312 tifffile-2022.10.10-py3-none-any.whl
              10 File(s)     80,005,158 bytes

Results of pip download Pillow to a Windows 64 machine:
21/10/2022  06:22         3,276,402 Pillow-9.2.0-cp310-cp310-win_amd64.whl

Note that the download of scikit-image includes Pillow as a dependency so you are going to be "using" Pillow whichever way you go but a lot depends on how accessible and in what form it is accessible.
If you are going for the Scipy route anyway you are likely to need all or most of that 80 MB but if you are not then Pillow at 3 MB is a much lighter space commitment.


text:
Q: Data is not going in database in MERN Data is not going in Database in MERN ---
Everything is looking fine and also got status 200 and alert "post created" but data is not going in my database.
How to debug this error. I have tried all solutions. At least tell me the possible reasons for this error. it will help me a lot.
Schema
const mongoose = require("mongoose");

const postSchema = new mongoose.Schema({
title: {
    type: String,
    required: true,
},
description: {
    type: String,
    required: true,
},
picture: {
    type: String,
    required: false,
},
username: {
    type: String,
    required: true,
},
category: {
    type: String,
    required: false,
},
createDate: {
    type: Date,
    default: Date.now,
},
})

const post = new mongoose.model('post', postSchema);

module.exports = post;

server router
const express = require("express");
const router = express.Router();
const post = require("../schema/post-schema");
router.post('/create', async(req,res) => {
try{
    console.log(req.body);
    const { title, description, picture, username, category, createDate } = req.body;
    const blogData = new post({
        title:title,
        description:description,
        picture:picture,
        username:username,
        category:category,
        createDate:createDate
    });

    console.log("user " + blogData);
    const blogCreated = await blogData.save();
    if(blogCreated)
        {
            return res.status(200).json({
                message: "blog created successfully"
            })
        }
    console.log("post "+post);
} catch(error){
    res.status(500).json('Blog not saved '+ error)
}
})
 module.exports = router;

client file
const initialValues = {
title: '',
description: '',
picture: 'jnj',
username: 'Tylor',
category: 'All',
createDate: new Date()
}
const CreateView = () => {
const [post, setPost] = useState(initialValues);
const history = useHistory();
const handleChange = (e) => {
    setPost({...post, [e.target.name]:e.target.value});
}

const savePost = async() => {
    try {
    const {title, description, picture, username, category, createDate} = post;
    console.log(post);
    const res = await fetch('/create', {
        method: "POST",
        headers: {
            "Content-Type":"application/json"
        },
        body: JSON.stringify({title, description, picture, username, category, createDate})
    })
    console.log(post);
    console.log("res is  "+ res);
    if(res.status===200 )
    {
        window.alert("post created");
        console.log(res);
    }
    }
    catch(e){
        console.log(`save post error ${e}`);
    }
}

const classes = useStyles();
const url = "https://images.unsplash.com/photo-1543128639-4cb7e6eeef1b?ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8bGFwdG9wJTIwc2V0dXB8ZW58MHx8MHx8&ixlib=rb-1.2.1&w=1000&q=80";
return (
    <>
    <Box className={classes.container}>
    <form method="POST">
        <img src={url} alt="banner" className={classes.image}/>
        <FormControl className={classes.form}>
            <AddIcon fontSize="large" color="action" />
            <InputBase placeholder="Title" className={classes.textfield} name="title" onChange={(e)=>handleChange(e)}/>
            <Button variant="contained" color="primary" onClick={()=>savePost()}>Publish</Button>
        </FormControl>
        <TextareaAutosize aria-label="empty textarea" placeholder="Write here..." className={classes.textarea} name="description" onChange={(e)=>handleChange(e)}/>
    </form>
    </Box>
    </>
)
}

export default CreateView;

A: I think problem is you checking status 200 , so your server returning status 200 in anyway as response . You have to check your server side , and check if is returning code 400 or anything else on failure .


text:
Q: Need a script File to clear Cache Tables in a Drupal Database I need to take a dump of MySQL Database, i usaully do these manual steps do Perform dumping.

    login to phpmyadmin
    select database
    select sql tab
    paste these lines

        TRUNCATE watchdog;
        TRUNCATE cache; and
        TRUNCATE cache_admin_menu;

And click on OK to clean the cache.

I need to carryout the same activity via sime automated way, so that i can run in Cron job

A:
    [root@localhost home]# mysql -u root -ppasswd < /root/Downloads/testscript.sql

    I had create one file with name testscript.sql

    text in the file as follows

/*
     * My First MySQL Script - testscript.sql.
     * You need to run this script with an authorized user.
     */
    USE dbname;                     -- Set system database 'dbname' as the current database
    TRUNCATE `cache`;
    TRUNCATE `cache_admin_menu`;
    TRUNCATE `cache_block`;
    TRUNCATE `cache_bootstrap`;
    TRUNCATE `cache_field`;
    TRUNCATE `cache_filter`;
    TRUNCATE `cache_form`;
    TRUNCATE `cache_image`;
    TRUNCATE `cache_libraries`;
    TRUNCATE `cache_menu`;
    TRUNCATE `cache_page`;
    TRUNCATE `cache_path`;
    TRUNCATE `cache_rules`;
    TRUNCATE `cache_token`;
    TRUNCATE `cache_update`;
    TRUNCATE `cache_views`;
    TRUNCATE `watchdog`;

A: you can run the following command
mysql -u {username} -p{password} -e "FLUSH QUERY CACHE"

or you can create the query, save it on a file and run:
mysql -u {username} -p {password} < /path/to/query.sql


text:
Q: How to add the google map in the listview to show every record's location I want to add the google map on every list/record on listview .The latitude and longitude is fetched from the database .Pass the lat lng to the to google map to get the location on the google map .As per clicked on the direction button ,the it should have to show the google map .Here is my code .....

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:data/dbHelper.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class showOutlets extends StatefulWidget {

  @override
  State<showOutlets> createState() => showOutletsState();
}
class showOutletsState extends State<showOutlets> {
  SQLHelper db = SQLHelper();
  late GoogleMapController mapController;

    List LatLng=  [];      ** // Longitude and latitude is fetched from the database in the list/map**

  List outlets = [];
  bool _isLoading = false;
  initState(){
    Future.delayed(Duration(seconds: 5)).then((onvalue) async{
      LatLng=await db.getLatLng();
      print("type-->${LatLng}");
      setState(() {
        _isLoading = true;
      });

    });
    Future.delayed(Duration(seconds: 3)).then((onvalue) async {
      outlets = await db.getOutletsData();
      print("type-->${outlets}");
      setState(() {
        _isLoading = true;
      });

      filterController.addListener(() {
        setState(() {
          filter = filterController.text;
        });
      });
    });
  }
  static  var boldStyle= const TextStyle(
    fontWeight: FontWeight.bold,
  );
  String? filter;
  TextEditingController filterController = new TextEditingController();
  Widget _buildListView() {
    return ListView.builder(
        itemCount: outlets == null ? 0 : outlets.length,
        itemBuilder: (BuildContext context, int i) {
          if (filter == null || filter == "") {
            return new ListTile(

**              //Here I want to pass the google map widget  which contains the
               //longitude and latitude from the map data  in the trailing:IconButton **

              title: new Text(outlets[i]['OutletID']+" - "+outlets[i]['OutletName']),
              subtitle: new Text("Phone#: "+outlets[i]['Telephone']+"\nAddress: "+outlets[i]['Address']),
              trailing:   new IconButton(onPressed: null, icon:Icon(Icons.directions,color: Colors.blue,)),

            );
          } else {
            if (outlets[i]['OutletName'].toLowerCase().contains(filter..toString().toLowerCase()) || outlets[i]['OutletID'].toLowerCase().contains(filter.toString().toLowerCase())) {
              return new ListTile(
                title: new Text(outlets[i]['OutletID']+" - "+outlets[i]['OutletName']),
                subtitle: new Text("Phone#: "+outlets[i]['Telephone']+"\nAddress: "+outlets[i]['Address']),
                trailing:    IconButton(onPressed: null, icon:Icon(Icons.directions,color: Colors.blue,)),

              );

            } else {
              return new Container();
            }
          }

        });
  }

 // googleMap(){
 //    return  GoogleMap(initialCameraPosition:new CameraPosition(
 //      target: LatLng,
 //      zoom: 11.0,
 //    ));
 //
 // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title:  const Text('User Data' ),

        ),
        body:_isLoading == false? const Center(

          child: CircularProgressIndicator(),
        ):
        Padding(
            padding: const EdgeInsets.all(5.0),
            child: Column(
              children: <Widget>[
                Padding(
                    padding:   EdgeInsets.only(top: 8.0, left: 8.0, right: 8.0),
                    child: TextField(
                      style:   TextStyle(fontSize: 18.0, color: Colors.black),
                      decoration: InputDecoration(
                        prefixIcon:  Icon(Icons.search),
                        hintText: "Search Customers...",
                      ),
                      controller: filterController,
                    )),
                Expanded(
                  child:  Padding(
                      padding:   EdgeInsets.only(top: 05.0),
                      child: _buildListView()
                  ),
                ),
              ],
            )
        )
    );
  }
}


text:
Q: DB2- select rows with date_column of last month I need to select count(field) from table where the date_column is within the last month, i.e. from the first of the last month till the first of this month. As this query will be automated it will need to refer to the last month of any given day.
Also the date_column has a datatype of timestamp
Thanks in advance!

A: SELECT (CAST(current timestamp AS DATE)) - (DAY(CAST(current timestamp AS DATE)) - 1)DAYS FROM sysibm.sysdummy1;
SELECT (CAST(current timestamp AS DATE)) - (DAY(CAST(current timestamp AS DATE)) - 1)DAYS
- 1 MONTH
FROM sysibm.sysdummy1;
Managed to find these queries, to find the first of this month and last month


text:
Q: Writing the contents of a struct to yml file I have a struct like below
type config struct{
    version int
    mapping map[string]string
}

I would like to write the contents of the above struct to a yml file in Go.
I tried with below but no luck.
func writeConfig(c *config) error {
    d, err := yaml.Marshal(c)
    if err != nil {
        return err
    }
    home, err := os.UserHomeDir()
    if err != nil {
        return err
    }
    configpath := filepath.FromSlash(home + "/abc/config.yml")

    // Open file using READ & WRITE permission.
    file, err := os.OpenFile(configpath, os.O_RDWR, 0644)
    if err != nil {
        return err
    }
    defer file.Close()

    // Write some text line-by-line to file.
    _, err = file.WriteString(string(d))
    if err != nil {
        return err
    }

    // Save file changes.
    err = file.Sync()
    if err != nil {
        return err
    }
    return nil
}

Is there is library/way to achieve this? Thank you!

A: This library should help you get what you need: https://github.com/go-yaml/yaml
A requirement for this is to export the members of your config struct (capital names).
Here is a short example for your struct definition:
package main

import (
    "log"
    "os"

    "gopkg.in/yaml.v2"
)

type config struct {
    Version int
    Mapping map[string]string
}

func main() {

    file, err := os.OpenFile("test.yml", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        log.Fatalf("error opening/creating file: %v", err)
    }
    defer file.Close()

    enc := yaml.NewEncoder(file)

    err = enc.Encode(config{
        Version: 7,
        Mapping: map[string]string{
            "key":  "value",
            "key2": "value2",
        },
    })
    if err != nil {
        log.Fatalf("error encoding: %v", err)
    }

}

This will result in the following yaml file:
version: 7
mapping:
  key: value
  key2: value2


text:
Q: Error:(14, 45) error: unclosed character literal I have an error in  NEWS_API_KEY when I edited it return back in this class
/* Automatically generated file. DO NOT MODIFY */

package com.news.droiddebo.mytimes;

    public final class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String APPLICATION_ID = "com.news.droiddebo.mytimes";
    public static final String BUILD_TYPE = "debug";
    public static final String FLAVOR = "";
    public static final int VERSION_CODE = 5;
    public static final String VERSION_NAME = "2.0";
    // Fields from build type: debug
    public static final String NEWS_API_KEY   ='1da651fa26f34134bb880c82ff7f0541';
    }

A: Use double quote (") while initialize String variable,
public static final String NEWS_API_KEY ="1da651fa26f34134bb880c82ff7f0541";


text:
Q: Should I use the Web API when I do not fully embrace REST I am developing a single page app running in desktop browser, tablet browser and maybe phone browser. I am return only JSON from my backend wether it is ASP.NET MVC or Web API.
When I think of Web API or read about it I always hear the words REST/RESTfull. Independently from what REST is I like some features about Web API which I have not in MVC (by default but maybe it can be implemented somehow but I dont want that extra effort...)

*

*Return HttpStatus codes like 200 for GET or 201 when the Ressource is created. My single page app knows and reacts on this codes.

*Return DTOs directly in the controller and c# classes are automatically serialized to json. With MVC this is not a one-liner. Not dealing with ActionResults.

*Web API is very much designed about 'cool' urls/routing I will also have deep/complex routing on my client.

*My Web API endpoints are just 'ajax callbacks' I do not need REST things like include a self.link in every retrieved ressource etc...

Of course I do not create/modify ressources on a Get request. But I already have been used to this style when I was doing MVC. So I like and will do many REST styles but not because of REST itself rather its common practice.
Should I really design great restfull API`s to use the Web API ? I do not know what is Microsofts recommendation about the Web API or wether they have really a guideline about it...

A: In my experience Web API has often been a great help, and rarely a hindrance. If you do it "their way," it saves you a lot of ugly work around serialization/routing/binding. If you don't want to do it "their way," you don't have to. You can extend the routing engine. You can implement your own serialization. You can return raw JSON where you see fit. Nothing in Web API forces you to follow the REST concept to a T (trust me I have seen this in action). I haven't heard this complaint before from anyone who has used it - I would suggest you give it a try and see just how far off it really is.

A: REST is not at all required to use Web API. In fact, it is quite easy to turn on and use session management as well.
In fact, while RESTful approaches have some real advantages, I wouldn't recommend going 100% RESTful. It is simply not possible to make them fully secure without using a third-party authentication provider. We built a fully RESTful prototype and explored many different mechanisms to secure the site. In the end, though, every one had one vulnerability or another (it helps to have a CISSP on staff). So I talked to one of the top security experts at Norton and he agreed that, yes, there is always a way to exploit a fully RESTful, standalone app. Symantec is apparently building a "wrapper" technology that gets around this but it was easier to either go with a third-party authentication provider or just go back to MS-based security using session cookies.


text:
Q: gulpfile.js compiles css incorrectly Styles on my project organized this way:
 styles/
       /1.less
       /2.less
       /..
       /style.less
       /style.css

In style.less are imports in order:
@import '1';
@import '2';
//..

in example 1.less contain properties for html tag, 2.less contain properties
for body tag, 3.less contain properties for div tags;
I expect the output should I get something like:
html {
    /*this styles first*/
}

body {
    /*this styles second*/
}

div {
    /*this styles third*/
}

but in compiled style.css i get a duplicate style properties:
html {
    /*this styles first*/
}
div {
     /*this styles third*/
}
html {
     /*this styles first*/
}
body {
     /*this styles second*/
}
div {
     /*this styles third*/
}
body {
     /*this styles second*/
}

Build system - Gulp, and gulpfile.js looks like this:
'use strict';

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    concat = require('gulp-concat'),
    less = require('gulp-less'),
    csso = require('gulp-csso')

var path = {
    build: {
        css: 'styles/'
    },
    src: {
        style: 'styles/*.less'
    }
};
gulp.task('style:build', function () {
    gulp.src(path.src.style)
        .pipe(less())
        .pipe(concat('style.css'))
        .pipe(gulp.dest(path.build.css))
});
gulp.task('build', [
    'style:build'
]);
gulp.task('default', ['build']);
gulp.task('watch', function(){
  gulp.watch(path.src.style, ['build']);
});

In my opinion the error lies in gulpfile.js.

A: Like georg already posted, concatenation of css file is usually used in a way that we import all less files into main less file which is then served to gulp in order to create css file. So use this:
var path = {
  build: {
    css: 'styles/'
  },
  src: {
    style: 'styles/style.less'
  }
};

Or if you want to use all files in gulp for concatenating, delete @import from main less file.