text:
Q: SQL - Get the last entries without 'order by' I have a problem with a sql-query for my database. I want to get the last n-entries of a specific Table. Usually I would perform the following query: 'Select Top 1000 (*) FROM Table ORDER BY Column DESC', but the problem is, that the table contains a lot of data and always ends up in a timeout because of the order process and even if the timeout wouldn't occur, I just can't tolerate the delay in my application.
So what I am looking for is a way to get the last entries without re-ordering the table!
Am I just indulge in wishful thinking, or is there a way to get this done?

A: There is no way to do this. Relational databases are not required to keep their rows in any particular order... So, there's no way of knowing which row is physically stored last. You'll need to use the ORDER BY. Sorry about that...
You might be able to improve performance with some appropriate indexes, though. This sort of thing should be pretty fast with an index.

A: I had similar problems with searching within the MESSAGE Field of a huge log4net log table.
Fortunately the LOG table has a timestamp field so I was able to speedup the query by adding add additional filter conditions and indexes.
SELECT top 1000 * FROM table WHERE time_stamp >= today

or

SELECT top 1000 * FROM table WHERE id > first_id_today

Additional: avoid using (*) especially if you have binariy fields in your table!


text:
Q: NUnit Test cases skipping owin middleware I have an OAuthServerProvider issuing tokens after authenticating username and passwords. When the username or password is invalid I reject the owin Context, which will by default return 400 Bad Request as the status code.
But I want to respond with 401 Unauthorized
To achieve this I have written a middleware which will check the header and see if a custom header is present and if so will replace the status code with 401.
if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey(Constants.OwinChallengeFlag))
{
   var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag);
   context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
   context.Response.Headers.Remove(Constants.OwinChallengeFlag);
}

This works absolutely fine when I hit it with fiddler, but the unit test I have written below always gets a 400. Somehow when I make a request with my unit test the middleware is skipped.
[TestFixture]
public class UnitTest1
{
    private TestServer _server;

    [SetUp]
    public void SetUp()
    {
        _server = TestServer.Create<Startup>();
    }

    [Test]
    public void ShouldReturnUnauthorizedResponse()
    {

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/token");

        //wrong password
        var requestContent = "grant_type=password&UserName=foo&Password=bar";

        request.Content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");

        var response = _server.HttpClient.SendAsync(request).Result;

        //This assert fails, but shouldn't
        Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
    }
}

Need to know what I am doing wrong here.

A: I finally figured it out....
await _next.Invoke(environment) was the culprit. I was invoking it with the same environment Dictionary Object which was passed into the middleware and hence the modification made to the context object was not reflecting in the unit test.
The following code works as expected....
public async Task Invoke(IDictionary<string, object> environment)
{
    var context = new OwinContext(environment);

    var response = context.Response;

    response.OnSendingHeaders(state =>
    {
        var resp = (OwinResponse)state;
        if (resp.StatusCode == 400 && resp.Headers.ContainsKey(Constants.OwinChallengeFlag))
        {
            var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag);
            resp.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
            resp.ReasonPhrase = HttpStatusCode.Unauthorized.ToString();
            resp.Headers.Remove(Constants.OwinChallengeFlag);
        }
    }, response);

    await _next.Invoke(context.Environment);
}

Apart from passing the environment variable obtained from modified context object, modifying the response header inside the response.OnSendingHeaders is essential, this ensures the headers are modified before the response Headers are dispatched.
However I still have no idea how fiddler was picking up the correct response status code.
Hope it helps someone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fastest way to check if set exists in database set Say I have a database with millions of urls with millions more to come. I need a fast way of checking if a batch of urls exist in the database. At the moment I have this:
foreach($urls as $url) {
  $this->db->or_where('url', $url->url);
}

Which produces queries like this:
WHERE url = 'foo' OR url = 'bar' OR ...

Are there faster ways to check if sets of data exist in a database?

A: Someting like:

SELECT EXISTS(SELECT 1 FROM table1 url = 'foo' OR url = 'bar' OR ...
)


text:
Q: What Is The Smallest Solution to $7x^5=11y^{13}$? I started teaching myself Number Theory from a pretty basic textbook and I got completely stuck with this problem.
Let $x$ and $y$ be two non-zero natural numbers such that $7x^5=11y^{13}$ .
The lowest possible value for $x$ has a prime factorization of the form $a^cb^d$ . What's the value of the sum $a+b+c+d$ ?
Can anyone show a solution ? I'm much more interested in the way of thinking rather than the result.

A: From $7x^5 = 11y^{13}$, we have that $11$ divides $x$ and $7$ divides $y$. Let $x=7^a 11^b m$ and $y=7^c11^dn$, where $$\gcd(m,7)=\gcd(m,11)=\gcd(n,7)=\gcd(n,11)=1$$
This gives us that
$$7^{5a+1}11^{5b}m^5 = 7^{13c}11^{13d+1}n^{13}$$
This means $5a+1=13c$, $5b=13d+1$ and $m^5=n^{13}$. Since we are after the smallest possible $x$, we have $m=n=1$, $a=5,c=2$ and $b=8,d=3$. This gives us that
$$x=7^5\cdot11^8$$


text:
Q: A good multi-level partial view (user control) stucture If have a filter form with multiple filter control inside like first name, last name, birth date, database name etc. Some of them need to be wrap into a control and reuse in the future, so I have something like:
@model FilterViewModel
<form ....>
@Html.Partial("FirstNameLastName", model.FirstNameLastNameFilterViewModel)
@Html.Partial("BirthDate", model.BirthDateFilterViewModel)
<input >//submit form
</form>

The partial views "FirstNameLastName" and "BirthDate" have it's UI and view model. I am wondering when I click submit, will my MVC controller function get all the fields in those partial views and make them into a FilterViewModel object with FirstNameLastNameFilterViewModel and BirthDateFilterViewModel filled?
If not, do you knows how to do it or any other good way to make it works with clean code.
Thanks

A: OK. I admitted I am lazy before asking this quesion.
After an experiment with MVC3, I found this supported by default.
You just need to make your ViewModel into levels and use it on UI in the same structure, it works perfect.
Thanks.


text:
Q: How do I declare my select query in PL/SQL? I want to declare a select query to use it in a trigger but I am a noob in sql in general :P Can somebody help me?
My code (example):
DECLARE Primary_Keys VARCHAR(20);
BEGIN
SELECT cons.constraint_type
FROM all_constraints cons, all_cons_columns cols
WHERE cols.owner = 'DAB_NAME'
AND cons.constraint_type = 'P'
AND cons.constraint_name = cols.constraint_name
AND cons.owner = cols.owner;
END;

A: You may use a PROCEDURE composed of BULK COLLECT with FORALL :
SQL> set serveroutput on;
SQL> CREATE OR REPLACE PROCEDURE pr_list_constraints(
                              i_owner IN all_cons_columns.owner%TYPE
                              )
IS
BEGIN
      DBMS_OUTPUT.PUT_LINE('Constraint Types for '||i_owner);
      DBMS_OUTPUT.PUT_LINE('------------------------------- ');
   FOR constraint_rec
      IN (SELECT distinct cons.constraint_type
            FROM all_constraints cons, all_cons_columns cols
           WHERE cols.owner = i_owner --'DAB_NAME'
           --AND cons.constraint_type = 'P'
             AND cons.constraint_name = cols.constraint_name
             AND cons.owner = cols.owner)
   LOOP
      DBMS_OUTPUT.PUT_LINE(constraint_rec.constraint_type);
   END LOOP;
END;
/
SQL> var p_owner varchar2(50);
SQL> exec pr_list_constraints(:p_owner);

 Constraint Types for DAB_NAME
 -------------------------------
 R
 U
 P
 C

P.S. Using a DB trigger is irrelevant for such type of tasks.


text:
Q: Split characters from elements in array of object in JavaScript I have a following array of Object, I wanted to match the Object Keys from locales array and match with the value property in the object.
Output: If the Object key from locales matches the value property, then i want to display the text in Object values from locales.
What i have in an array is:
[{
 value: 'dz'
 locales: [
    {ar-dz: "Hello World"},
    {ar-dk: "Hello World"}
 ]
}]

I am stuck in a logic beyond this point.
for(var i = 0; i < data.locales.length; i++) {
    var localearray = Object.keys(data.locales[i]));
    var locales = localearray[i].split('-');
    console.log(locales);
}

A: Use .find on the objects to identify the first object whose (only) key's suffix after the - matches the value you're looking for:

const obj = {
 value: 'dz',
 locales: [
    {'ar-dz': "Hello World"},
    {'ar-dk': "Hello World"}
 ]
};

const locale = obj.locales.find(
  locale => obj.value === Object.keys(locale)[0].split('-')[1]
);
if (locale) console.log(Object.values(locale)[0]);

Note that you also

*

*need commas between separate key-value pairs

*need to surround invalid identifiers in object literals with ' or " delimiters


text:
Q: Code count used Excel Rows but ignores hiddenrows I am new to VBA with Excel and I want to get the amount of used Rows in my excel sheet.
Currently I am having this Code:
Private Sub

LastRow = Range("A" & Rows.Count).End(xlUp).row
Msgbox LastRow

End Sub

My Problem is that sometimes the Last Rows are hidden(height = 0) but I want the Code to still count them.
How to do this?
Thanks in Advance!

A: Hi you can try below code to find last row even if the row is hidden
Dim WS As Worksheet
Dim LastCell As Range
Set WS = Thisworkbook.Worksheets("Sheet1")
With WS
    Set LastCell = .Columns(1).Find(what:="*", _
        after:=.Cells(.Rows.Count, "A"), _
        LookIn:=xlFormulas, _
        lookat:=xlPart, searchdirection:=xlPrevious)
End With
Debug.Print LastCell.row


text:
Q: Mysql count(*) is failing me

if(!$this->MakeProcedure("StupidProcedure", "OUT msg VARCHAR(25)" )){
            echo "could not create procedure";
  }

if(!$this->db->query("SET @msg = ''") || !$this->db->query("CALL StupidProcedure(@msg)")){
          echo "CALL to StupidProcedure  failed:";
}  else   {
    $res= $this->db->query("SELECT @msg as _p_out");
     $row = $res->fetch();
                echo $row['_p_out']." counted columns ";
}

I have tables authors and publishers within mysql DB. They both have ISBN
Column in common. I then issued a call (through php) to a stored procedure
That contains the following code:
BEGIN
DECLARE count int;

                    SELECT count (*) FROM
                                    (
                                       SELECT distinct
                                       table_name
                                       FROM information_schema.columns
                                       WHERE table_name IN ('authors', 'publishers')
                                       AND column_name = 'ISBN'
                                       and table_schema = 'myDB'
                                    )any_alias
                    INTO count;
                    SELECT count INTO msg;      /*just to debug counter*/
END

Basically, I want the above snippet to return 2 as counted number of tables that
have ISBN column in common (to reflect in count variable). Unfortunately,
count is always returning 0 in spite of multiple - checking that ISBN column is
there (with phpmyadmin). Why is count(*) behaving strangely ? or is there
a special .ini configuration that I must set ?
here is my test driver:
Any help will be greatly appreciated.

A: Woooow ! Finally I've got it. Here's the sql code snippet that does the dirty fix:

BEGIN
DECLARE count int;
                    SELECT count(1)
                    FROM information_schema.columns
                    WHERE table_name IN ('authors', 'publishers')
                    AND column_name = 'ISBN'
                    AND table_schema = 'test'
                    INTO count;
                    SELECT count INTO msg;      /*just to debug counter*/
END
//PRINT 'Thank you guys !'


text:
Q: Can Minecraft: Pocket Edition join a player on Xbox Live? My brother is trying to get my nephew to join on his iPad and I'm on Xbox one. I try to invite him and it just shows up on the Xbox. I look up my name to join and it shows I'm playing on Xbox live but he can't join.

A: No. Unfortunately, this is not possible.
Minecraft is hoping to add that in the future.

A: Yes! If you are on the same wifi (same house and stuff), have whoever is on the world that they are gonna play on, go on the world settings and go to the multiplayer section, and make sure "Enable LAN" and make sure that is on. Then go into the world and if the other person looks in the friends section they should be able to join. If different wifis, make sure both are logged into an Xbox account (even the iPad needs to log into an xbox account, there should be a sign in button on the title screen and you can log in or make an account for free), then friend each other (you might need the xbox app for this on iPad im not sure), and go into the friends section and if someone is playing a world, as long as multiplayer is on they can play!


text:
Q: can I use a multiprocessing pool to work on procedures? My understanding is that multiprocessing pools allows for multiple CPU usage when using functions. Such that something is returned:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

How would I preform a procedure which similarly maximises CPU usage.
I expected the following to work, but it did nothing.
from multiprocessing import Pool

def f(x):
    textfile.write(x)

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))
    textfile.close()

what can be done to maximise CPU usage when writing to text files?


text:
Q: Use .NET for fast read/write of large files i am trying to search through a number of large files and replace parts of the text, but i keep running into errors.
i tried this, but sometimes i'll get an 'out of memory' error in powershell
#region The Setup
$file = "C:\temp\168MBfile.txt"

$hash = @{
    ham = 'bacon'
    toast = 'pancakes'
}
#endregion The Setup

$obj = [System.IO.StreamReader]$file
$contents = $obj.ReadToEnd()
$obj.Close()

foreach ($key in $hash.Keys) {
    $contents = $contents -replace [regex]::Escape($key), $hash[$key]
}
try {
    $obj = [System.IO.StreamWriter]$file
    $obj.Write($contents)
} finally {
    if ($obj -ne $null) {
        $obj.Close()
    }
}

then i tried this (in the ISE), but it crashes with a popup message (sorry, don't have the error on hand) and tries to restart the ISE
$arraylist = New-Object System.Collections.ArrayList
$obj = [System.IO.StreamReader]$file
while (!$obj.EndOfStream) {
    $line = $obj.ReadLine()
    foreach ($key in $hash.Keys) {
        $line = $line -replace [regex]::Escape($key), $hash[$key]
    }
    [void]$arraylist.Add($line)
}
$obj.Close()
$arraylist

and finally, i came across something like this, but i'm not sure how to use it properly, and i am not even sure if i am going about this the right way.
$sourcestream = [System.IO.File]::Open($file)
$newstream = [System.IO.File]::Create($file)
$sourcestream.Stream.CopyTo($newstream)
$sourcestream.Close()

any advice would be greatly appreciated.

A: You can start with a readcount of 1000 and tweak it based on the performance you get:
get-content textfile -Readcount 1000 |
    foreach-object {do something} |
    set-content textfile

or
(get-content textfile -Readcount 1000) -replace 'something','withsomething' |
set-content textfile


text:
Q: Disable onClicklistener When Internet is not availaible I'm using an adapter class to populate my Fragment with Blogpost and Like Button. But when device is offlline and when User presses like button then app crashes.
So I'm looking forward to disable the click function when Device is offline and only enable when device is online.
So How can I apply button to clickable(false); when device is offline.
Here is my BlogRecycleadapter class code
package com.nepalpolice.cdp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.nepalpolice.cdp.webfaq.isNetworkStatusAvialable;

public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {

    public List<BlogPost> blog_list;
    public Context context;
    private Button mbutton;

    private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;

    public BlogRecyclerAdapter(List<BlogPost> blog_list){

        this.blog_list = blog_list;

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
        context = parent.getContext();
        firebaseFirestore = FirebaseFirestore.getInstance();
        firebaseAuth = FirebaseAuth.getInstance();

        mbutton = (Button)  view.findViewById(R.id.blog_like_btn);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {

        holder.setIsRecyclable(false);

        final String blogPostId = blog_list.get(position).BlogPostId;
        final String currentUserId = firebaseAuth.getCurrentUser().getUid();

        String desc_data = blog_list.get(position).getDesc();
        holder.setDescText(desc_data);

        String image_url = blog_list.get(position).getImage_url();
        holder.setBlogImage(image_url);

        String user_id = blog_list.get(position).getUser_id();
        //User Data will be retrieved here...
        firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {

                if(task.isSuccessful()){

                    String userName = task.getResult().getString("name");
                    String userImage = task.getResult().getString("image");

                    holder.setUserData(userName, userImage);

                } else {

                    //Firebase Exception

                }

            }
        });

        long millisecond = blog_list.get(position).getTimestamp().getTime();
        String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
        holder.setTime(dateString);

        //Get Likes Count
        firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                if (!documentSnapshots.isEmpty()){

int count = documentSnapshots.size();
holder.updateLikesCount(count);

                }else{
holder.updateLikesCount(0);

                }

            }
        });

        //Get Likes

        firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context),new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {

                if (documentSnapshot.exists()){

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
                    }
                    else {
                        holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
                    }
                } else {

                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
                    }else{
                        holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
                    }
                }

            }
        });

        //like Feature

        holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                        if (!task.getResult().exists()){

                            Map<String, Object> likesMap = new HashMap<>();
                            likesMap.put("timestamp", FieldValue.serverTimestamp());

                            firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);

                        } else {
                            firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();

                        }

                    }
                });

            }
        });

    }

    @Override
    public int getItemCount() {

        return blog_list.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private View mView;

        private TextView descView;
        private ImageView blogImageView;
        private TextView blogDate;

        private TextView blogUserName;
        private CircleImageView blogUserImage;
        private ImageView blogLikeBtn;
        private  TextView blogLikeCount;

        public ViewHolder(View itemView) {
            super(itemView);
            mView = itemView;

        }

        public void setDescText(String descText){

            descView = mView.findViewById(R.id.blog_desc);
            descView.setText(descText);

            blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
        }

        public void setBlogImage(String downloadUri){

            blogImageView = mView.findViewById(R.id.blog_image);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.image_placeholder);
            Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).into(blogImageView);

        }

        public void setTime(String date) {

            blogDate = mView.findViewById(R.id.blog_date);
            blogDate.setText(date);

        }

        public void setUserData(String name, String image){

            blogUserImage = mView.findViewById(R.id.blog_user_image);
            blogUserName = mView.findViewById(R.id.blog_user_name);

            blogUserName.setText(name);

            RequestOptions placeholderOption = new RequestOptions();
            placeholderOption.placeholder(R.drawable.profile_placeholder);

            Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);

        }

public void  updateLikesCount (int count){

            blogLikeCount = mView.findViewById(R.id.blog_like_count);
            blogLikeCount.setText(count + "Likes");
}

    }

Here is the image file of error report

I used
 mimageview = (ImageView) view.findViewById(R.id.blog_like_btn);

and
if (!isNetworkStatusAvialable(mimageview.getContext())){
mimageview.setClickable(false);
}

But it still throws me an error and didn't solve the problem.

A: Heres code that would check whether the user has an internet connection.
 ConnectivityManager connectivityManager
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(!(activeNetworkInfo != null && activeNetworkInfo.isConnected())){
 //user does not have an internet connection
 //put code here that diables the button
} else {
//user does have an internet connection
//put code here that enables the button
 }

Add this code to when you bind the data to the view and disable the button if you dont have a connection.
Based on your code it would look something like this:
 @Override
public void onBindViewHolder(final ViewHolder holder, int position) {
ConnectivityManager connectivityManager
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(!(activeNetworkInfo != null && activeNetworkInfo.isConnected())){
 //user does not have an internet connection
 //heres code that diables the button
 holder.blogLikeBtn.clickable(false);
}
//put the rest of your method code here
}

Although this is one way to solve your problem, a better way would be to add this code to the onClick event of the button and then check if the user has a connection and if he does not then show him a dialog explaining to him that he needs an internet connection and then exiting.
These are two approaches to solving your problem.
Note: Make sure you add this permission to your manifest <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> otherwise you will get a Exception when using the above code.

A: Create a class.
public class InternetStatus {

    private static InternetStatus instance = new InternetStatus();
    static Context context;
    ConnectivityManager connectivityManager;
    NetworkInfo wifiInfo, mobileInfo;
    boolean connected = false;

    public static InternetStatus getInstance(Context ctx) {
        context = ctx.getApplicationContext();
        return instance;
    }

    public boolean isOnline() {
        try {
            connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            connected = networkInfo != null && networkInfo.isAvailable() &&
                    networkInfo.isConnected();
            return connected;

        } catch (Exception e) {
            System.out.println("CheckConnectivity Exception: " + e.getMessage());
            Log.v("connectivity", e.toString());
        }
        return connected;
    }

}

Use it like so... change this....
if (InternetStatus.getInstance(context.isOnline()) {
    Log.i(TAG, "User is online");
} else {
    Log.e(TAG, "User does not have an internet connection");
}

Also, you shouldn't disable a button before the user has the ability to press it. You should allow the user to press the button, then check if there is a connection. If not, show a snackbar or toast or dialogbox.


text:
Q: Jasmine: looped tests fail to run if asynchronous I'm working on implementing a test that reads a list of files from a given directory. The list is then checked against a Map object that uses filenames as keys. If a match is found I want to execute some tests, if not skip the file and move on to the next one.
I have the test working if I just grab one object from the Map but it fails when I try to loop. I want to run tests by looping over multiple files.
It only seems to be a problem if I have async calls in my tests. Using a completely synchronous loop I can get it to run just fine. Here is an example of the synchronous loop (I realize this is a very contrived example but it works as expected):
describe('a test', () => {
  const list = ['a', 'b', 'c'];

  const test = (x) => {
    describe(`should run ${x}`, () => {
        beforeAll(async () => {
            console.log('beforeAll');
        });

        beforeEach(async () => {
            console.log('beforeEach');
        });

        for(let i = 0; i < 2; i++) {
          it(`should log iteration ${i}`, async () => {
            console.log(x, i);

            expect(i).toBeTruthy();
          });
        }
    });
  }

  for (let i = 0; i < list.length; i++) {
    test(list[i]);
  }
});

The output from the above snippet suggests that it runs just fine:

This same pattern does not work if it is asynchronous though. In fact, the nested describe in test isn't even running as far as I can tell. I logged the project variable to the console so I could see that it was getting called but the logging in... statement in the beforeAll isn't getting executed at all. It seems like it's just skipping right over it. How do I make this work with async/await?
describe('Import Project', () => {
  const _page = new PageFactory();
  const utils = new Utils();
  const projPath = browser.params.projPath;

  let projectGuid: string;

  const test = (project) => {
    describe(`importing ${project.name}`, () => {
        beforeAll(async () => {
            console.log('logging in...'); //not getting executed for some reason
            await _page.loginPage.login(browser.params.username, browser.params.password);

            // import
            await _page.projectsPage.importProject(projectPath + project.filename)
                .withImportType(project.importType)
                .withProjectName(project.projectName)
                .inEnvironment(project.environment)
                .import();

            projectGuid = await utils.extractGuid();
        });

        afterEach(async () => {
            await _page.designerPage.navigateTo(projectGuid);
        });

        for(let i = 0; i < project.operations.length; i++) {
            const operation = project.operations[i];

            it(`should run ${operation.name} successfully`, async () => {
                await runOperation(operation.name);

                const status = await _page.operationLogsPage.getStatus(operation.outcomeTarget);
                expect(status).toEqual(operation.expectedStatus);
            });
        }
    });
  }

  utils.getProjects().then(projects => {
    // projects is a string[] of filenames
    // that are returned using fs.readdir()
    for (let i = 0; i < projects.length; i++) {
        const myProject = projectMap.get(projects[i]);

        if (myProject) {
            test(myProject);
        }
    }
  });
});

The output from this is just Executed 0 of 0 specs SUCCESS in 0.003 sec.
I don't understand how this would be any different than manually writing out all these nested describe blocks. If I wrote each one out it would work just fine but for some reason in a loop it doesn't want to work. Any ideas?

A: I couldn't figure out how to get this to work the way I wanted. Instead I decided to use node's child_process.execSync and looped through each file that way. It's not ideal but it works. Takes a bit longer since each file I want to run tests on creates a new session but I'm tired of trying to make it work the other way.
I'm running the script using node ./path/to/test.js --baseUrl=http://<myUrl>
Here's the relevant part of the code:
fs.readdir(projectsPath, (err, files) => {
  if (err) {
    throw new Error('Unable to scan directory: ' + err);
  }

  let i = 0;

  const next = () => {
    if (i < files.length) {
        const file = files[i];
        console.log('running tests on:', file);

        const runCmd = `nodenv --exec "yarn run e2e:all ${baseUrl} --params.projectToImport=${file} --suite import_projects"`

        // exec
        try {
            execSync(runCmd, { cwd: workingDir, stdio: 'inherit' },
                (error, stdout, stderr) => {
                    if (error) {
                        console.error(error);
                        return;
                    }

                    console.log(stdout);
                });
        } catch (err) {
            if (err.stderr) {
                console.log('stderr:', err.stderr.toString());
            }
        }

        // next iteration
        i++;
        next();
      }
  }

  next();
});


text:
Q: Prove that if $2b^2+1 = 3^b$ where $b$ is a positive integer, then $b \leq 2$
Prove that if $2b^2+1 = 3^b$ where $b$ is a positive integer, then $b \leq 2$.

Is there some way we can transform the equation in order to get the inequality? We have $2b^2 = 3^b-1$.

A: Subtract $b^3$ from both sides.
$2b^2 + 1 -b^3 = 3^b-b^3$
$\Rightarrow b^2(2-b) = 3^b - (b^3+1)$
Now think about the expression
$3^b - (b^3+1)$.
Both $3^b$ and $b^3+1$ are monotonically increasing. Being an exponential function, $3^b$ grows faster than $b^3+1$ for positive b. These two facts ensure that if at any non-negative point $3^b$ dominates $b^3+1$, it will continue to dominate $b^3+1$ at subsequent points. And as a matter of fact, $3^b=b^3+1$ for $b=0$
Thus, for $b\geqslant0$ we have $3^b-(b^3+1)\geqslant0$
$\Rightarrow b^2(2-b)\geqslant0$
$\Rightarrow 2 \geqslant b$

A: Given:  $ \qquad \displaystyle  2b^2+1 = 3^b \tag 1$
We see immediately $b=1$ and $b=2$ give equalities.
What if $b$ grows over $2$, so $b=2+c$? Let's first denote $ß=\lg3 $ and we know, $ß >1$ . With this we make the ansatz:
$$     2(2+c)^2+1 = 3^{2+c}  \tag 2$$
and develop by expanding and rearranging
$$ \begin{array}{rll}
     2(2+c)^2+1 &= 9\cdot 3^c  \\
  9+8c+2c^2 &= 9\cdot (1+ßc + ß^2c^2/2! &+ ß^3c^3/3! + ... ) \\
  1+8/9c+2/9c^2 &= 1+ßc + ß^2c^2/2 &+ ß^3c^3/3! + ...\\
 \text{ getting }&\\
  (8/9-ß)c+1/18(4-9ß^2)c^2 &=   &\phantom+ ß^3c^3/3! + ... & \qquad (3)\\
\end{array}$$

*

*The rhs is positive with $c>0$.

*Because $ß>1$ the parentheses on the lhs are negative. So for all $c>0$ the lhs is negative.

So for all $c>0$  in (3) (and thus $b>2$ in (1)) the lhs is smaller than the rhs and the equality (1) does never hold.

A: You've got the right idea about getting an inequality. Since exponential functions grow much faster than polynomials, we should expect $3^b$ to dominate $2b^2+1$ at some point. We can show that it happens at $b=2$ using induction.
Induction hypothesis: Suppose that $2b^2+1<3^b$ for some particular value $b>2$.
Induction step: We want to prove $2(b+1)^2<3^{b+1}$ holds as well.
Let's work on the left side. We have
$$ \begin{array}{ll} 2(b+1)^2+1 & = 2b^2+4b+3 \\ & = [2b^2+1]+[2(2b)+1]+1 \\ & < [2b^2+1]+[2b^2+1]+1 \\ & <3^b+3^b+3^b \\ & =3^{b+1}.  \end{array} $$
That is, we've proved $2(b+1)^2<3^{b+1}$, and so the claim follows.
If you're not very familiar with induction, what we've just shown is that if the inequality holds for a particular value of $b$, then it holds for the next value of $b$ as well. This leads to a chain
$$ \begin{array}{lc} & 2(3^2)+1<3^3 \\ \implies & 2(4^2)+1<3^4 \\ \implies & 2(5^2)+1<3^5 \\ \implies & 2(6^2)+1<3^6 \\ \implies & \vdots \end{array}$$
Thus, $2b^2+1<3^b$ holds for all $b>2$.


text:
Q: ndk-build errors, string format, clang no such file or directory I've tried creating a simple jni test app from "Beginning Android Games 3rd Ed" book. I copy-pasted the code, but when I try to link with ndk-build, I get the following error messages:
D:\apps\android\projects\NDK\app\src\main\java>ndk-build
[armeabi-v7a] Compile++ arm  : jniutils <= jniutils.cpp
jni/jniutils.cpp:8:52: error: format string is not a string literal (potentially insecure)
      [-Werror,-Wformat-security]
    __android_log_print(ANDROID_LOG_VERBOSE, cTag, cMessage);
                                                   ^~~~~~~~
jni/jniutils.cpp:8:52: note: treat the string as an argument to avoid this
    __android_log_print(ANDROID_LOG_VERBOSE, cTag, cMessage);
                                                   ^
                                                   "%s",
1 error generated.
make: *** [obj/local/armeabi-v7a/objs/jniutils/jniutils.o] Error 1

If I try to treat these errors as warnings and suppress these with the following lines in android.mk / application.mk:
APP_CFLAGS += -Wno-error=format-security
LOCAL_DISABLE_FORMAT_STRING_CHECKS := true

Then I get this error:
D:\apps\android\projects\NDK\app\src\main\java>ndk-build
[armeabi-v7a] SharedLibrary  : libjniutils.so
clang++.exe: error: no such file or directory: '遶上・llog'
make: *** [obj/local/armeabi-v7a/libjniutils.so] Error 1

Which I guess is just some garbage from memory, like a string /variable hasn't been addressed correctly.
I'm very new to jni, so I'm at a bit of a loss of how to troubleshoot this.

Code follows:
JniUtils.java
package com.badlogic.androidgames.ndk;
import java.nio.ByteBuffer;
public class JniUtils {
    static {
        System.loadLibrary("jniutils");
    }
    public static native void log(String tag, String message);
    public static native void copy(ByteBuffer dst, float[] src, int offset, int len);
}

jniutils.cpp
#include <android/log.h>
#include <string.h>
#include "jniutils.h"
JNIEXPORT void JNICALL Java_com_badlogic_androidgames_ndk_JniUtils_log
    (JNIEnv *env, jclass clazz, jstring tag, jstring message) {
    const char *cTag = env-> GetStringUTFChars(tag, 0);
    const char *cMessage = env-> GetStringUTFChars(message, 0);
    __android_log_print(ANDROID_LOG_VERBOSE, cTag, cMessage);
    env-> ReleaseStringUTFChars(tag, cTag);
    env-> ReleaseStringUTFChars(message, cMessage);
}

JNIEXPORT void JNICALL Java_com_badlogic_androidgames_ndk_JniUtils_copy
    (JNIEnv *env, jclass clazz, jobject dst, jfloatArray src, jint offset, jint len) {
    unsigned char* pDst = (unsigned char*)env-> GetDirectBufferAddress(dst);
    float* pSrc = (float*)env-> GetPrimitiveArrayCritical(src, 0); memcpy(pDst,
    pSrc + offset, len * 4);
    env-> ReleasePrimitiveArrayCritical(src, pSrc, 0);
}

application.mk
APP_ABI := armeabi-v7a x86
APP_PLATFORM := android-19

android.mk
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := jniutils
LOCAL_LDLIBS := − llog
LOCAL_ARM_MODE := arm
LOCAL_SRC_FILES := jniutils.cpp
include $(BUILD_SHARED_LIBRARY)


text:
Q: Which PyTorch version is CUDA 3.0 compatible? I have a Nvidia GeForce GTX 770, which is CUDA 3.0 compatible, but upon running PyTorch training on the GPU, I get the warning
Found GPU0 GeForce GTX 770 which is of cuda capability 3.0.
PyTorch no longer supports this GPU because it is too old.
The minimum cuda capability that we support is 3.5.

and subsequently the error RuntimeError: CUDA error: no kernel image is available for execution on the device.
Was there an old PyTorch version, that supported graphics cards like mine with CUDA capability 3.0? If yes, which version, and where to find this information? Is there a table somewhere, where I can find the supported CUDA versions and compatibility versions?
If it is relevant, I have CUDA 10.1 installed.


text:
Q: How do I center text inside of a div with Foundation? I feel like I'm overthinking this or missing something small. I need to center text inside of a div with Foundation. Here is what I am currently working with:
[1]

[2]

[3]        My Text for Today
[4]

[5]

I've tried replacing line 1 with the following:

I've tried replacing line 2 with the following:

I've tried replacing line 5 with the following:

My Text for Today

I've tried a combination of all three of the above with absolutely no luck.
I'm trying to do this without CSS. Trying to do this with just Foundation. How do I center the My Text for Today text?

A: You just need to add the utility class of foundation as

A: In foundation 6.5 you can align horizontal and vertical with this:

Text


text:
Q: node js post request only works second time I have one strange issue, when I submit form, it redirects to form action URL then it shows blank page. When I reload it again it will display the data.
index.jade - http://172.18.0.60:3000/
  form#command(action='runcommand', method='post')
    input#cmdls(type='checkbox', name='cmdls', value='ls -la')
    label(for='cmdls') List Files
    br
    input#cmdpwd(type='checkbox', name='cmdpwd', value='pwd')
    label(for='cmdpwd') Print Working Directory
    br
    input#cmddate(type='checkbox', name='cmddate', value='date')
    label(for='cmddate') Date
    br
    input.button(type='submit', value='Run')

app.js
var tmp="";
app.post('/runcommand',function(req,res){

    for (var key in req.body) {

            console.log(key);
            function puts(error, stdout, stderr) { sys.puts(stdout) }
            exec(req.body[key], function(error, stdout, stderr) {
              if (!error) {
                    tmp+=stdout;
              } else {
                tmp+=stderr;
              }
            });

    }

    res.render("result",{ data: tmp });

});

result.jade - http://172.18.0.60:3000/runcommand
extends layout
block content
    h1= "Result"
    pre=  data

When I submit form it will redirect to http://172.18.0.60:3000/runcommand only displaying h1, when I reload it again it display data.
why it is behave like this?

A: exec() is asynchronous so it finishes AFTER you call res.render().  So, you need to render only after all the exec() calls have finsished.  This would probably be easier to code if you used promises and Promise.all() to keep track of when all the exec() calls were done, but you could also use a counter to know when the last one was done.
Here's a scheme using a counter:
app.post('/runcommand', function(req, res) {

    let keys = Object.keys(req.body);
    let cnt = 0;
    let tmp = '';
    if (!keys.length) {
        // render something when there were no keys
        res.render(...)
    } else {
        keys.forEach(function(key) {
            console.log(key);

            exec(req.body[key], function(error, stdout, stderr) {
                if (!error) {
                    tmp += stdout;
                } else {
                    tmp += stderr;
                }
                ++cnt;
                // if all exec calls have finished, the render
                if (cnt === keys.length) {
                    res.render("result", {data:tmp});
                }
            });
        });
    }
});

P.S. This code looks like it allows any client to run any arbitray program on the server (if it's in the path or they can construct the full path).  That seems very dangerous.
P.P.S.  Accumulating tmp outside the handler like you were doing in your original code is a disaster for multiple users using your server as multiple requests can tromp on either other's value in tmp.  Accumulated data like this needs to either be in a local variable inside the request handler or in a property on the request object so that it can never conflict with other requests in process.


text:
Q: How to print hexademical from byte[]? My goal is to follow the RFC6455 [Page 8]
The server would then take the SHA-1 hash of this,
   giving the value 0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6
   0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea.

I am assuming 0xb3 equals to 179.
This is the lines of code I use to print the byte[]. The LOGGER is sl4fj.
  private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketWorkerThread.class);

    public void onOpen() {
        String GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        byte[] SHA_1_hash_value = MessageDigest.getInstance("SHA-1").digest(
                ("dGhlIHNhbXBsZSBub25jZQ==" + GUID).getBytes()
        );
        StringBuilder sb = new StringBuilder();
        for (byte b : SHA_1_hash_value) {
          sb.append(String.format("%02X ", b));
        }
    }

My expected result:
0xb3 0x7a 0x4f 0x2c 0xc0 0x62 0x4f 0x16 0x90 0xf6
   0x46 0x06 0xcf 0x38 0x59 0x45 0xb2 0xbe 0xc4 0xea

The actual result:
64 3A 23 A1 A9 CE 6D 23 B2 71 B8 D5 45 CE A8 5F 25 CD 45 1E

A:   private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketWorkerThread.class);

public void onOpen() {
    String GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    byte[] SHA_1_hash_value = MessageDigest.getInstance("SHA-1").digest(
            ("dGhlIHNhbXBsZSBub25jZQ==" + GUID).getBytes()
    );
    StringBuilder sb = new StringBuilder();
    for (byte b : SHA_1_hash_value) {
      sb.append("0x" + String.format("%02X ", b).toLowerCase());
    }
}


text:
Q: What to learn before using a JavaScript library / framework? It seems that many of the JavaScript questions are answered by the simple use of pushing a library, without taking into account the person asking the question. I think libraries are great myself, but sometimes I think that we're too quick to throw a library down someone's throat.
Imagine a person asks a question and it's apparent that they barely know JavaScript. They're just using code they found and piecing it together with other code, and really have no firm foundation to work on. To add a library on top of that flimsy foundation seems like a disaster waiting to happen.
With that in mind, what JavaScript / programming / web browser concepts do you think are necessary to understand before a library/framework is introduced to a person? Should a framework / library be part of the learning process?
I don't think someone has to grasp absolutely everything to use a library, I just think some people would be better served with a "Library X might help solve your problems, but before you do that, you might want to read up on the following concepts", rather than just a "use library x" answer.

A: What you should learn are some fundamental programming techniques:

*

*closures

*continuations

*function objects / what a "first class" function is

*JavaScript object oriented design

*difference between "prototype" languages and traditional Object Oriented languages

*Absolutely firm grounding in HTML and CSS: standards, tricks, and various browser compatibility issues

*UI Design Principals

With that in mind, today its practically impossible to develop without a library.  I recommend Dojo but others use jQuery, YUI, etc...
When choosing a library, you need to have a firm understanding of what problem you are trying to solve.  Is it browser abstraction? dealing with communication? charting? animations? graphics? UI toolkits?
Each library has its "niche", so you need to really know what you're specific problem domain is and in turn choose a library accordingly.

A: I would suggest using the brick and mortar kind of library and find a good book on JavaScript.

A: I think that one reflex reaction to a "how do implement X" is "don't reinvent then wheel", and this is generally good advice. I think that if you have to ask how to do something reasonably complex, and it's already in a library then you're going to waste massive time trying to piece together something from a few answers on SO.
So barring the obvious: learn the syntax of the language, learn how to debug etc., by and large a library is the right answer. And that's not just to say "Use the library, disengage brain" it also means "Study the library, look at the issues it's solving - you didn't realise your problem was so complex? Well the folks who put hours and days into the library studied the problem in some detail and probably developed the library by using it extendsively. Study the implementation and learen how."
I think that studying good code is a very good way to learn.

A: Libraries bring similarities to browsers where so much is different from browser to browser. This is why, I'd suspect, people suggest their usage in various answers. Nothing is stoping anyone from reading a good js book if they want to actually understand what is going on, but we surely cannot shove books and tutorials down anyone's throat. You need to want to learn before that would be worth anything.

A: They should read this http://www.amazon.com/exec/obidos/ASIN/0596517742/wrrrldwideweb
And check out some of the links here http://www.crockford.com/


text:
Q: How to Call the one php page content and display it another php page using ajax I have index page, in that i have 2 button "Staff Details" and "Student Detalis"
When i click "Staff Details" , the content of "staffDetails.php" should display in index.php
Similarly, "STudent details" also
Ajax Function:
function search1()
    {       $.ajax({
                    Type:'GET',
                    url:'StaffDetails.php',
                    success:function(html)
                    {
                        document.getElementById("StaffDetails").innerHTML=html;
                    },
                })
    }

A: here is a complete ajax function use like this and help full for you in future
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<input type="button" value="Staff Details" onclick="search1()" />
<input type="button" value="Student Details" onclick="search2()" />

here is full ajax working and tested example hope no question left now.
Thanks!


text:
Q: How to rotate a stack of images in 3D space? I have a stack of 2D images.
lets say below are the dimensions of this volume.

Depth(Number of images) - 100
Width(Pixels in X axis) - 200
Height(Pixels in Y-axis) - 200

I want to rotate this volume and create Bitmaps out of this. I am using C# to implement this.
Here is what i did:
List<short[]> volumebuffer = new List<short[]>(noImages);
for (int img = 0; imge<noImages; img++)
{

    short[] tmpArray = new short[ImgTotalHeight * ImgTotalWidth];
    int index = 0;
    for (int aHeight = 0; aHeight<ImgTotalHeight; aHeight++)
    {
       for (int aWidth = 0; aWidth<ImgTotalWidth; aWidth++)
       {
           tmpArray[index++] = image[aWidth + aHeight * ImgTotalWidth];

       }
    }
    #append this tmpArray to a List<>
    vomumebuffer.Add(tmpArray);

}

In the above code the volumebuffer will contain all the pixel values of all the images. I am converting each short array of each image to byte array and creating the bitmaps out of it.
Now i want to rotate this volume and create bitmaps out of it. I want create only 90 degree orientations.
I tried to read the pixel values in different axis.
Like for reading pixel values in Width-> Depth -> Height order etc..
But this will need many for loops for each orientation.
Is there any better way to achieve orientation of the volume?
Please help me on how i can rotate this volume at 90 degrees in different orientations.
Thanks in advance.

A: you should add methods to index the volume by x,y,z coordinates. Rotation in 90-degrees steps would then simply be switching places of the indices, keeping one dimension fixed. For example
bitmap[u, v] = volume[0, v, u]

or
bitmap[u, v] = volume[v, 0, u]

or
bitmap[u, v] = volume[xSize - v, u, 0]

there should be 24 valid combinations in total
you can replace 0 with whatever valid value you want, and you need to ensure the u/y coordinates are limited to corresponding volume-dimension.
Edit:
Example using multidimensional arrays in order to make indexing clearer. You would need to exchange this with corresponding code, and convert the result to a bitmap.
        var volume = new ushort[1, 2, 3];
        var bitmap = new ushort[volume.GetLength(2), volume.GetLength(1)];
        for (int v = 0; v < bitmap.GetLength(1); v++)
        {
            for (int u = 0; u < bitmap.GetLength(0); u++)
            {
                bitmap[u, v] = volume[0, v, u];
            }
        }


text:
Q: Create directory in external storage in Android Hello I am trying to create a directory in the external storage but it is not working for me. I debugged the application there I find that code execute perfectly myDirectory.mkdirs(); but this does not create the directory when I see it using the SD card explorer
Any idea why it is not creating the PMS directory in the external storage ?
String capturedPhotoName = System.currentTimeMillis() + ".png";

try {
    File myDirectory = new File(Environment.getExternalStorageDirectory()+ "/PMS/");
    if(!myDirectory.exists()) {
        myDirectory.mkdirs();
    }
    File photo = new File(myDirectory, capturedPhotoName);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
    imageUri = Uri.fromFile(photo);
    startActivityForResult(cameraIntent, CAMERA_INTENT_REQUEST);
} catch(Exception e) {
    Log.e("PMS", e.getMessage());
}

A: Try this:
boolean success = (new File(getActivity().getApplicationContext().getFilesDir()+"/YourAppFolderName")).mkdir();
        if (!success){
            Log.w("directory not created", "directory not created");
        }

Also in the manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: Yeah really very silly mistake I made, forgot to add permission to write in the SD Card but it should have thrown the exception
Anyway, it solved my issue
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


text:
Q: Mulesoft NetSuite Connector throw java.lang.NullPointerException: charsetName Error I am getting this error in my mulesoft application while making a search call to NetSuite connector (v11.5.12).
org.apache.cxf.phase.PhaseInterceptorChain: Interceptor for {http://client.internal.soap.mule.org/}ProxyService#{http://client.internal.soap.mule.org/}invoke has thrown exception, unwinding now
java.lang.NullPointerException: charsetName

This error has suddenly started to come in the production environment. I am not able to replicate the same in lower environment.
Mule Application is deployment on Anypoint CloudHub with Mule Runtime version 4.4.0
NetSuite connector version v11.5.12
No recent changes deployed to production, existing application started to throw this error while searching
I enabled NetSuite Debug Logger and below are the logs it generated.
        DEBUG 2023-02-15 13:50:53,636 [[finance-bulk-api].NetSuite_Config.04 SelectorRunner] [processor: netsuite-advance-search/processors/1/processors/0/processors/0; event: a91c2ba0-ad09-11ed-b6b5-88665a243a09] org.mule.service.http.impl.service.HttpMessageLogger.NetSuite_Config: REQUESTER
    POST /services/NetSuitePort_2021_1 HTTP/1.1
    SOAPAction: search
    Host: 1111.suitetalk.api.netsuite.com
    User-Agent: AHC/1.0
    Connection: keep-alive
    Accept: */*
    Content-Type: text/xml
    Transfer-Encoding: chunked

    c57
    <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><preferences xmlns="urn:messages_2021_1.platform.webservices.netsuite.com"><warningAsError>false</warningAsError><disableMandatoryCustomFieldValidation>false</disableMandatoryCustomFieldValidation><disableSystemNotesForCustomFields>false</disableSystemNotesForCustomFields><ignoreReadOnlyFields>false</ignoreReadOnlyFields><runServerSuiteScriptAndTriggerWorkflows>false</runServerSuiteScriptAndTriggerWorkflows></preferences><tokenPassport xmlns="urn:messages_2021_1.platform.webservices.netsuite.com"><account xmlns="urn:core_2021_1.platform.webservices.netsuite.com">****</account><consumerKey xmlns="urn:core_2021_1.platform.webservices.netsuite.com">*****</consumerKey><token xmlns="urn:core_2021_1.platform.webservices.netsuite.com">****</token><nonce xmlns="urn:core_2021_1.platform.webservices.netsuite.com">****</nonce><timestamp xmlns="urn:core_2021_1.platform.webservices.netsuite.com">****</timestamp><signature xmlns="urn:core_2021_1.platform.webservices.netsuite.com" algorithm="HMAC_SHA256">fhpl/bxKP/cfuAYhSQ/MULWdkfjfnkfkUlMbWguVr9a6MaXS5fhRUDJVIdjdonddU=</signature></tokenPassport><searchPreferences xmlns="urn:messages_2021_1.platform.webservices.netsuite.com"><bodyFieldsOnly>false</bodyFieldsOnly><returnSearchColumns>true</returnSearchColumns><pageSize>10</pageSize></searchPreferences></soap:Header><soap:Body><ns0:search xmlns:ns0="urn:messages_2021_1.platform.webservices.netsuite.com">
      <ns0:searchRecord xmlns:ns01="urn:sales_2021_1.transactions.webservices.netsuite.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns01:TransactionSearchAdvanced">
        <ns01:criteria xmlns:ns01="urn:sales_2021_1.transactions.webservices.netsuite.com">
          <ns01:basic>
            <ns02:lastModifiedDate xmlns:ns02="urn:common_2021_1.platform.webservices.netsuite.com" operator="within">
              <ns03:searchValue xmlns:ns03="urn:core_2021_1.platform.webservices.netsuite.com">2023-02-13T22:00:49</ns03:searchValue>
              <ns03:searchValue2 xmlns:ns03="urn:core_2021_1.platform.webservices.netsuite.com">2023-02-14T22:00:49</ns03:searchValue2>
            </ns02:lastModifiedDate>
            <ns02:recordType xmlns:ns02="urn:common_2021_1.platform.webservices.netsuite.com" operator="is">
              <ns03:searchValue xmlns:ns03="urn:core_2021_1.platform.webservices.netsuite.com">Invoice</ns03:searchValue>
            </ns02:recordType>
          </ns01:basic>
        </ns01:criteria>
        <ns01:columns xmlns:ns01="urn:sales_2021_1.transactions.webservices.netsuite.com">
          <ns01:basic>
            <ns02:amountRemaining xmlns:ns02="urn:common_2021_1.platform.webservices.netsuite.com"/>
            <ns02:internalId xmlns:ns02="urn:common_2021_1.platform.webservices.netsuite.com">
              <ns03:searchValue xmlns:ns03="urn:core_2021_1.platform.webservices.netsuite.com" internalId="null"/>
            </ns02:internalId>
          </ns01:basic>
        </ns01:columns>
      </ns0:searchRecord>
    </ns0:search></soap:Body></soap:Envelope>

    DEBUG 2023-02-15 13:50:53,636 [[biz-prc-ent-finance-bulk-api].NetSuite_Config.04 SelectorRunner] [processor: netsuite-advance-search/processors/1/processors/0/processors/0; event: a91c2ba0-ad09-11ed-b6b5-88665a243a09] org.mule.service.http.impl.service.HttpMessageLogger.NetSuite_Config: REQUESTER
    0

    DEBUG 2023-02-15 13:50:58,153 [[finance-bulk-api].NetSuite_Config.04 SelectorRunner] [processor: netsuite-advance-search/processors/1/processors/0/processors/0; event: a91c2ba0-ad09-11ed-b6b5-88665a243a09] org.mule.service.http.impl.service.HttpMessageLogger.NetSuite_Config: REQUESTER
    HTTP/1.1 504 Gateway Time-out
    Server: AkamaiGHost
    Mime-Version: 1.0
    Content-Type: text/html
    Content-Length: 176
    Expires: Wed, 15 Feb 2023 08:20:58 GMT
    X-Reference-Error: 97.27697c68.1676449258.23382b2c
    Date: Wed, 15 Feb 2023 08:20:58 GMT
    Connection: close
    Akamai-GRN: 0.df523617.1676449254.1f240dc8

    <TITLE>Error</TITLE>
    An error occurred while processing your request.

    Reference &#3

5;97.27697c68.1676449258.23382b2c

    WARN  2023-02-15 13:50:58,155 [[MuleRuntime].uber.02: [finance-bulk-api].netsuite-to-salesforce-sync-shcedular-flow.BLOCKING @32c6a070] [processor: netsuite-advance-search/processors/1/processors/0/processors/0; event: a91c2ba0-ad09-11ed-b6b5-88665a243a09] org.apache.cxf.phase.PhaseInterceptorChain: Interceptor for {http://client.internal.soap.mule.org/}ProxyService#{http://client.internal.soap.mule.org/}invoke has thrown exception, unwinding now
    java.lang.NullPointerException: charsetName
        at java.io.InputStreamReader.<init>(InputStreamReader.java:99) ~[?:1.8.0_312]

A: Clearly the error is a timeout on the Netsuite infrastructure:
HTTP/1.1 504 Gateway Time-out

It it not possible to know the cause of the error from the data provided. It could be a Netsuite issue, a configuration issue (wrong connection address?), or simply that the operation takes too long to complete (data issue, which may vary between environments).
It would be recommended to upgrade to the latest Mule Netsuite connector release and test again. There have several fixes and improvements since the version you are using was released, including security fixes and error messages improvements. Even if it doesn't solve the issue you are experiencing you would be better covered against those issues.


text:
Q: Is it fine to flag one line answers or link-only answers? Recently I noticed one person who gave two answers in one hour. In the first answer he/she just added one link and another answer he just added few words in the answer. Stack Overflow provides a comment feature so I think they should use this instead of giving very short answers without description or more info about answer.
So my confusion is if it's okay to flag these particular types of answers, who just give answers for getting reputation only.

A: I declined the flags on those posts. In the first one, the question itself was faulty. The answer was about as good of an answer as you could expect for that question. For the second, I left a comment detailing how the OP could improve their answer.


text:
Q: ImportError: dlopen ... when using tensorflow When I was using a tensorflow model for classification, I got the following error. I am not sure what is the reason. I installed all required packages. I googled for a while but could not find the answer. Can anyone help me with this? (My machine is a Mac.)
The error:
/Users/user_name/Desktop/tensorflow/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
return f(*args, **kwds)
/Users/user_name/Desktop/tensorflow/lib/python3.6/importlib/_bootstrap.py:219: RuntimeWarning: numpy.dtype size changed, may indicate binary incompatibility. Expected 96, got 88
return f(*args, **kwds)
Traceback (most recent call last):
File "parse_file.py", line 39, in <module>
process_file(**vars(args))
File "parse_file.py", line 29, in process_file
from audio.processor import WavProcessor, format_predictions
File "/Users/user_name/Desktop/project/devicehive-audio-analysis/audio/processor.py", line 18, in <module>
import tensorflow as tf
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in <module>
from tensorflow.python import *
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 82, in <module>
from tensorflow.python import keras
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/__init__.py", line 26, in <module>
from tensorflow.python.keras import activations
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/activations/__init__.py", line 22, in <module>
from tensorflow.python.keras._impl.keras.activations import elu
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/__init__.py", line 21, in <module>
from tensorflow.python.keras._impl.keras import activations
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/activations.py", line 24, in <module>
from tensorflow.python.keras._impl.keras.engine import Layer
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/__init__.py", line 21, in <module>
from tensorflow.python.keras._impl.keras.engine.topology import get_source_inputs
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/engine/topology.py", line 31, in <module>
from tensorflow.python.keras._impl.keras.utils import conv_utils
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/utils/__init__.py", line 22, in <module>
from tensorflow.python.keras._impl.keras.utils import data_utils
File "/Users/user_name/Desktop/tensorflow/lib/python3.6/site-packages/tensorflow/python/keras/_impl/keras/utils/data_utils.py", line 23, in <module>
from multiprocessing.pool import ThreadPool
File "/Users/user_name/anaconda3/lib/python3.6/multiprocessing/pool.py", line 26, in <module>
from . import util
File "/Users/user_name/anaconda3/lib/python3.6/multiprocessing/util.py", line 17, in <module>
from subprocess import _args_from_interpreter_flags
File "/Users/user_name/anaconda3/lib/python3.6/subprocess.py", line 136, in <module>
import _posixsubprocess
ImportError: dlopen(/Users/user_name/Desktop/tensorflow/lib/python3.6/lib-dynload/_posixsubprocess.cpython-36m-darwin.so, 2): Symbol not found: __Py_set_inheritable_async_safe
Referenced from: /Users/user_name/Desktop/tensorflow/lib/python3.6/lib-dynload/_posixsubprocess.cpython-36m-darwin.so
Expected in: flat namespace
in /Users/user_name/Desktop/tensorflow/lib/python3.6/lib-dynload/_posixsubprocess.cpython-36m-darwin.so


text:
Q: is there a way to extract Mapstruct mapping? Let says I have a basic case where I map an object to an other, I need to declare the mapping in the Mapper class.
For validation I may want to remember the original field name and his corresponding mapping.
Is there a way to do it with mapstruct without having to do a mapping "manually"
here is an example of what I would expect.
public class PersonDemo {

    public static void main(String[] args) {
        final PersonMapper mapper = Mappers.getMapper(PersonMapper.class);
        Person person = mapper
            .toPerson(new PersonDto()
                .setFirstName("John")
                .setName("Doe"));

        System.out.println(person);

        System.out.println("Expected " + toPersonDesc("firstName") + " to be firstName");
        System.out.println("Expected " + toPersonDesc("name") + " to be lastName");
    }

    @Mapper
    public interface PersonMapper {
        @Mapping(target = "lastName", source = "name")
        Person toPerson(PersonDto dto);

    }

    //expected method. to be generated somehow from the mapping.
    static String toPersonDesc(String fieldName) {
        switch (fieldName) {
            case "name": return "lastName";
            case "firstName": return "firstName";
        }
        return null;
    }

    @Data
    @Accessors(chain = true)
    public static class Person {

        private String lastName;
        private String firstName;
    }

    @Data
    @Accessors(chain = true)
    public static class PersonDto {

        private String name;
        private String firstName;
    }
}

A: It's impossible with Mapstruct. There's another question similar to yours: How to provide MapStruct Mapping annotation mapping meta data at runtime. The answer there describes "some" approach to the problem, but it's very limited - it simply scrapes the information from the @Mapping annotations (no support for implicit mappings).
It would be quite useful to have this though - you should propose this feature to the Mapstruct team.


text:
Q: Proving $364 \mid n^{91} - n^7$ [Generalization of Euler & Fermat Theorems] I am trying to prove this statement which is equivalent to show $n^{91} = n^7 \pmod{ 364}$. By splitting modulus theorem $n^{91} = n^7 \bmod 91$ and $\bmod 4$. Then I don't know what to do next... Can anyone help me?

A: It's a special case of below Euler-Fermat generalization with $\,e = 7,\, f = 84,\ \prod p_i^{e_i} =  2^2\cdot 7\cdot 13 $
Theorem $\  $ Suppose that $\ m\in \mathbb N\ $ has the prime factorization $\:m = p_1^{e_{1}}\cdots\:p_k^{e_k}\ $ and suppose that for all $\,i,\,$ $\  e_i\le e\ $ and $\ \phi(p_i^{e_{i}})\mid f.\ $ Then $\ m\mid a^e(a^f-1)\ $ for all $\: a\in \mathbb Z.$
Proof $\ $ If $\ p_i\mid a\ $ then $\:p_i^{e_{i}}\mid a^e\ $ by $\ e_i \le e.\: $ Else $\:a\:$ is coprime to $\: p_i\:$ so by Euler's phi theorem, $\!\bmod q = p_i^{e_{i}}\!: \ a^{\phi(q)}\equiv 1\,$ thus $\,a^f\equiv 1\, $ by $\: \phi(q)\mid f.\ $  Since all $\ p_i^{e_{i}}\,$ divide $\, a^e (a^f - 1)\ $ so too does their product $\,m\,$ by lcm = product for coprimes, or by unique prime factorization.
Examples $\ $ You can find many illuminating examples in prior questions, e.g. below
$\qquad\qquad\quad$ $24\mid a^3(a^2-1)$
$\qquad\qquad\quad$ $40\mid a^3(a^4-1)$
$\qquad\qquad\quad$ $88\mid a^5(a^{20}\!-1)$
$\qquad\qquad\quad$ $6p\mid a\,b^p - b\,a^p$

A: Use Euler's theorem:
Mod $4$:  either $n\equiv0 $ or $2$, so $n^{91}\equiv n^7\equiv0$, or $\color{blue}{n^2\equiv 1}$ so $n^{91}\equiv n^{84}n^7\equiv (n^2)^{42}n^7\equiv n^7$
Mod $7$:  either $n\equiv0$, so $n^{91}\equiv n^7\equiv 0$, or $\color{blue}{n^6\equiv 1}$ so $n^{91}\equiv n^{84}n^7\equiv(n^6)^{14}n^7\equiv n^7$
Mod $13$:  either $n\equiv0$, so $n^{91}\equiv n^7\equiv 0$, or $\color{blue}{n^{12}\equiv 1}$ so $n^{91}\equiv n^{84}n^7\equiv(n^{12})^{7}n^7\equiv n^7$


text:
Q: Need to achieve the below output using Kusto Query language(KQl) Sample Data. We are expected to receive Products everyday with Total counts.

TimeStamp
Product Desc
Product Code
Available count

2022-01-02T09:00:00Z
Berries
111
10

2022-01-02T09:00:00Z
Chocolate
222
20

2022-01-02T09:00:00Z
Mayo
333
30

2022-01-03T09:00:00Z
Berries
111
15

2022-01-03T09:00:00Z
Chocolate
222
22

2022-01-04T09:00:00Z
Berries
111
30

If no product received on that particular day, i have to show the last date received product as the current day.

TimeStamp
Product Desc
Product Code
Available count

2022-01-03T09:00:00Z
Berries
111
15

2022-01-03T09:00:00Z
Chocolate
222
22

2022-01-03T09:00:00Z
Mayo
333
30

2022-01-04T09:00:00Z
Berries
111
30

2022-01-04T09:00:00Z
Chocolate
222
22

2022-01-04T09:00:00Z
Mayo
333
30

A: datatable (['TimeStamp']:datetime,['Product Desc']:string,['Product Code']:int,['Available count']:int)
[
     '2022-01-02T09:00:00Z' ,'Berries'   ,111 ,10
    ,'2022-01-02T09:00:00Z' ,'Chocolate' ,222 ,20
    ,'2022-01-02T09:00:00Z' ,'Mayo'      ,333 ,30
    ,'2022-01-03T09:00:00Z' ,'Berries'   ,111 ,15
    ,'2022-01-03T09:00:00Z' ,'Chocolate' ,222 ,22
    ,'2022-01-04T09:00:00Z' ,'Berries'   ,111 ,30
]
| summarize arg_max(['TimeStamp'], *) by ['Product Code']

Product Code
TimeStamp
Product Desc
Available count

333
2022-01-02T09:00:00Z
Mayo
30

222
2022-01-03T09:00:00Z
Chocolate
22

111
2022-01-04T09:00:00Z
Berries
30

Fiddle


text:
Q: Help implementing an op-amp circuit to amplify an AC signal and set its offset above 0 I'm currently working on a project for a college class involving sound signal processing (FFT processing using a ESP32).
I am stuck at the implementation of a signal amplifier and offsetting it to prevent negative signals.
The microprocessor of choice was the ESP32, and as far as I found online, the analog input pins have a input range of 0 - 3.3 V. Our input signal can go as high/low as +-120 mV. After a little research I found out that using an op-amp would be a good choice.
I bought a NE5532p and tried using it by following a lot of guides and resources I found online, but none of them worked. I mainly tried to implement both an inverting and non-inverting negative-feedback loop so that I could control the gain, and using a positive DC voltage to offset the signal into a positive value (I think it won't matter much if the lowest value is something like 100 mV above 0 V since once I can read it on the ESP I can manipulate it by code).
So far I have been using mostly circuit simulation software since I only have few days in which I can have access to a osciloscope, and even when it worked on simulations, I couldn't make it work in real life.
I worry there might be something I missed about how op-amps work, or some little detail about them, but it seemed pretty simple once you get a hang of the basics.
If you guys could lend a hand on the subject I would truly appreciate it (it's really frustrating waiting a week to try out the circuit just to see it not working for some unknown reason).
Here´s a sketch I made on TinkerCad mostly to show here, the color code for the wires are given below:
Pink is the DC offset voltage into the non-inverting input
Red is the DC voltage from the power supply (originally 5 V but transformed into ~3.2 V for the Vcc+)
Blue is the  AC signal
Orange is the feedback loop/Vout

A: In the op-amp's datasheet, you find constraints concerning the acceptable range of input voltages (often called "common mode input voltage range"). Whatever circuit you build must guarantee that the inverting input or non-inverting inputs are never presented with a potential that falls outside this range.
For the NE5532, this datasheet says on page 3 that a typical device will not behave well if either input exceeds +13V, or falls below −13V, with supply potentials of ±15V. In the worst (unlucky) case, this range could be as small as ±12V. We can interpret this to mean that an input potential must always be at least 3V above the op-amp's negative supply potential, and simultaneously never exceed 3V less than positive supply.
As an example, this op-amp is completely unusable for applications with supplies of 0V and +5V, since the input can never drop below (0+3)=+3V or exceed (5-3)=+2V, which is clearly impossible to achieve, or is at best severely restrictive.
Even with a larger single-ended supply of, say, 0V & 15V, the simplest amplifier configuration would fail miserably:

simulate this circuit – Schematic created using CircuitLab
Before you even consider the inverting input, you've already violated the constraints of the op-amp by tying the non-inverting input to 0V. According to the datasheet, if the negative supply to this op-amp is 0V, then it requires (typically) at least +2V at an input.
This is why the datasheet doesn't even talk about using single-ended supplies. Sure, the op-amp can tolerate a potential difference of 30V between its supply pins, so that a single-ended supply of 0V & +30V won't do any damage, but in such cases, the acceptable input potentials will be constrained to between +2V and +28V (or if you are unlucky, +3V to +27V), which isn't very useful. When everything is relative to 0V, it makes much more sense to use a truly negative supply potential, so that the input range includes 0V.
If you wish to use a single-ended supply (in other words the op-amp's negative supply potential is 0V), then you need a device whose input voltage range includes the negative supply, or preferably slightly beyond (below) it.
In addition, you must consider the device's output voltage range which never includes the supply potentials. Even the best "rail-to-rail" output devices cannot reach closer than ten millivolts or so from the supply potentials.
Consider devices such as the LM358 (LM324) and the TLC2272, which are designed for use with single-ended supplies, and can also work with supplies down to only 3V or so, making them much more useful for anything involving ESP32s, Arduinos or Raspberry Pis and such.
If your source signal potential may be negative, obviously you can't do this:

simulate this circuit
It's a classic non-inverting configuration, but the negative supply of 0V constrains the non-inverting input to be always 0V or above (or somewhere in that ballpark, the datasheet will tell you the actual minimum level). Also, the output can't drop below 0V, so all negative inputs will be "clipped".
None of this means you can't use a single-ended supply to process/amplify signals that go negative. There are biasing techniques that can ensure the op-amp inputs remain within acceptable limits, and that centre the output at some point in between the supplies, even if the source signal swings beyond them, but this topic is large and complex.
My understanding of your problem is that you have an input signal that swings between −120mV and +120mV, and that you require an output proportional to the input, which swings between 0V and +3.3V.
To start with, then, this gives you a gain \$A\$ of:
$$
\begin{aligned}
A &= \frac{3.3 - 0}{0.12 - (-0.12)} \\ \\
&= \frac{3.3}{0.24} \\ \\
&= 13.7 \\ \\
\end{aligned}
$$
When the input is zero, you require an output half-way between 0V and 3.3V, so the offset \$C\$ is:
$$
\begin{aligned}
C &= \frac{3.3 + 0}{2} \\ \\
&= 1.65 \\ \\
\end{aligned}
$$
The relationship between \$V_{IN}\$ and \$V_{OUT}\$  is therefore:
$$
\begin{aligned}
V_{OUT} &= A\times V_{IN} + C \\ \\
&= 13.7 V_{IN} + 1.65 \\ \\
\end{aligned}
$$
How you implement this depends on what you are actually measuring. If you are trying to measure, for example, the amplitude of the source signal, or the source signal is AC and you can tolerate some phase shifting or other frequency dependent behaviour, you may use capacitors to decouple any source DC from the amplifier's own operating point, and set that operating point quite easily:

simulate this circuit
This approach requires no negative supply, but suffers from the usual caveats when using capacitive AC coupling. There will always be high-pass filter behaviour, with a cut-off frequency of about 2Hz in this example, and there will be a "settling time" while the capacitors charge to their final average voltages. However, those capacitors keep the op-amp's input potentials always within acceptable bounds. Once settled, the input-output relationship, given a sinusoidal input, will be like this:

If you require DC coupling (frequency dependency behaviour is undesirable, or the input is very slow moving, or can stay at a constant level for extended periods of time) then capacitors are out of the question, and you'll have to find an alternative solution. It gets complicated if you need gain to be positive, partly because it's really difficult to maintain op-amp input potentials inside the power supply range, when the input goes negative. However, if you are sampling this signal with an ADC then you can perform post-processing in software to compensate for a negative gain:

simulate this circuit

This is an inverting, summing amplifier, with gain of −13.7 (for the input signal \$V_{IN}\$), but we offset the output by providing a supplementary negative input potential, with a gain of −1. Obviously, the problem here is the need to derive a negative potential somehow.
One of the reasons that this inverting amplifier approach works, is that op-amp inputs are always zero, or near-zero, due to the "virtual earth" principle employed here. As long as the op-amp you use is comfortable with inputs slightly below the negative supply rail, it will work just fine.
The moral of the story might be that concerning op-amps, everything is complicated by the use of single-ended supplies. Since this is a college project, I imagine it will be easy for you to obtain a negative supply and just avoid this hurdle altogether. A word of warning, though: if you power your op-amp from dual supplies, then it can output negative potentials, and that can kill your ADC. Take care.
Since you already have an NE5532, and if I assume you can source a negative supply from somewhere, maybe your best bet is an adaptation of the above circuit:

simulate this circuit

You must use at least ±6V as supplies to the op-amp, and I've adjusted R3 to keep the output offset the same, given the increased negative potential.
The two diodes D1 and D2 clamp the output close to 0V and 3.3V in the case where the op-amp produces something outside that range, just to protect whatever comes next. Perhaps your ADC already has input protection diodes, in which case you may omit D1 and D2. R4 is there to limit current that flows when clamping occurs, to protect the op-amp and ADC.
Hope all this gives you some sense of direction.


text:
Q: getrusage system call: what is "maximum resident set size" man getrusage 2 says
ru_maxrss (since Linux 2.6.32)
              This is the maximum resident set size used (in kilobytes). For RUSAGE_CHILDREN, this is the resident set size of the largest
              child, not the maximum resident set size of the process tree.

So what does this number mean exactly?

A: A process's resident set size is the amount of memory that belongs to it and is currently present (resident) in RAM (real RAM, not swapped or otherwise not-resident).
For instance, if a process allocates a chunk of memory (say 100Mb) and uses it actively (reads/writes to it), its resident set size will be about 100Mb (plus overhead, the code segment, etc.).  If after the process then stops using (but doesn't release) that memory for a while, the OS could opt to swap chunks of that memory to swap, to make room for other processes (or cache).  The resident set size would then decrease by the amount the kernel swapped out.  If the process wakes up and starts re-using that memory, the kernel would re-load the data from swap, and the resident set size would go up again.
The ru_maxrss field of struct rusage is the "high water mark" for the resident set size. It indicates the peak RAM use for this process (when using RUSAGE_SELF).
You can limit a process's resident set size to avoid having a single application "eat up" all the RAM on your system and forcing other applications to swap (or fail entirely with out-of-memory conditions).


text:
Q: Interact with a webpage containing dynamic list using Python I am trying to write a Python program to automatically add tasks to todoist.  I am currently trying to use mechanize but not sure if this is what I need because it is set up to interact with forms and I'm not sure if todoist is using HTML forms for input.  This is my code so far:
import mechanize;
import re;

br = mechanize.Browser();
br.open("http://todoist.com/");
assert br.viewing_html();
print br.title();
print br.forms();

Which prints
To-do list and task manager. Free, easy, online and mobile: Todoist
<generator object __call__ at 0x02D69288>

So it is successfully connecting to todoist but I am not sure how to access the input forms to actually have it put tasks in?  Also not sure why br.forms() prints the reference rather than the value (which is an empty list)?

A: There are a few modules already available that allow me to interface with the todoist API.  This one seems to be working well in case anyone comes searching with the same question:  https://github.com/Garee/pytodoist


text:
Q: Program not running when double clicked but runs from cmd? I have made a python gui using tkinter and i have been running it through the commandline. But when i tried to open it by double clicking, it shortly shows the window but exits again. I tried commenting out all the places where it uses images thinking that it is because it dosent have file-editing permissions when its run by double click and it worked! But i need to use images in the gui, anyone have solutions?
import tkinter as tk
from PIL import Image, ImageTk
import time

root = tk.Tk()
root.title("Krypto Coin")
root.iconbitmap('icon.ico')
root.configure(bg="#112233")

Frame = tk.Frame(root, width=1200, height=800, bg="#112233")
Frame.grid(columnspan=3, rowspan=5)

icon = Image.open('icon_round.png')
icon = ImageTk.PhotoImage(icon)
icon_label = tk.Label(image=icon, borderwidth=0, highlightthickness=0)
icon_label.place(relx=0.5, rely=0.2, anchor="center")

text = tk.Label(root, text="Welcome to Krypto Coin (KTC)", bg="#112233", fg="#ffffff", font=("Arial", 32))
text.place(relx=0.5, rely=0.45, anchor="center")
text = tk.Label(root, text="Enter id of the receiver and amount", bg="#112233", fg="#ffffff", font=("Arial", 24))
text.place(relx=0.5, rely=0.5, anchor="center")

def trasfer_button_pressed():
    time.sleep(0.1)
    trasfer_button_text.set("Loading...")
    trasfer_button.configure(state="disable")
    trasfer_button.configure(bg="#112233")
    input_id.configure(state="disable")
    input_amount.configure(state="disable")

def trasfer_button_enter(e):
    if trasfer_button_text.get() == "Transfer":
        trasfer_button.configure(bg="#334455")

def trasfer_button_leave(e):
    if trasfer_button_text.get() == "Transfer":
        trasfer_button.configure(bg="#223344")

trasfer_button_text = tk.StringVar()
trasfer_button = tk.Button(root, textvariable=trasfer_button_text, command=lambda:trasfer_button_pressed(), bg="#223344", fg="#ffffff", width=15, height=1, font=("Arial", 24), borderwidth=0, highlightthickness=0)
trasfer_button_text.set("Transfer")
trasfer_button.place(relx=0.5, rely=0.65, anchor="center")
trasfer_button.bind("<Enter>", trasfer_button_enter)
trasfer_button.bind("<Leave>", trasfer_button_leave)

input_id = tk.Entry(root, width=48, font = "Arial 14", bg="#334455", fg="#ffffff", borderwidth=0, highlightthickness=0)
input_id.insert(0, "ID")
input_id.place(relx=0.45, rely=0.8, anchor="center", height=30)

input_amount = tk.Entry(root, width=20, font = "Arial 14", bg="#334455", fg="#ffffff", borderwidth=0, highlightthickness=0)
input_amount.insert(0, "Amount")
input_amount.place(relx=0.65, rely=0.8, anchor="center", height=30)

root.mainloop()


text:
Q: how to select table row items in table layout in android? I want to select a date range in the calendar by dragging across the table row. If anyone has any idea, please help.

A: You can still start from this project : Android Calendar View
Then add a setOnLongClickListener on the component.
With this listener, you should have the first day and also the last day. So you should be able to change dates appearence  between these.

A: You should check this question's answer,using android:clickable="true" and android:onClick="clickHandlerCell",then you can color the chosen in the clickHandlerCell method.


text:
Q: How many axioms can you remove from ZF set theory and still have an "interesting" version of mathematics? Obviously you can remove the axiom of choice from ZFC set theory to get ZF set theory. Using ZF only you can still construct most of mathematics and proofs.
This led me to wonder how many more axioms could you remove and still form some kind of complicated quasi-mathematical structure. In the sense that one could combine the axioms together to create theorems that are non-trivial and non-predictable?
As the axioms are similar to string replacement rules, I would imagine you could create interesting theorems starting with just 2 axioms.
The list of axioms are:

*

*Axiom of extensionality

*Axiom of regularity

*Axiom schema of specification

*Axiom of pairing

*Axiom of union

*Axiom schema of replacement

*Axiom of infinity

*Axiom of power set

*Well-ordering theorem OR axiom of choice.

How many could you remove and still have an intersting quasi-set theory?
I would define "interesting" in this sense as that a theorem would have a non-obvious proof.
Perhaps even some axioms are not needed in much of modern mathematics?

A: Taking the stance

I would define "interesting" in this sense as that a theorem would have a non-obvious proof

entirely seriously, one sufficient criterion for interestingness in this case would be essential incompleteness: a consistent computably axiomatizable theory is essentially incomplete iff it has no consistent computable completion. Note that this is stronger than mere incompleteness; for example, the theory of algebraically closed fields is computably axiomatizable and incomplete, but is contained in the computable consistent complete theory of algebraically closed fields of characteristic $17$.
It turns out that essential incompleteness shows up quite early on indeed! For example, Montagna and Mancini showed that we already wind up with an essentially incomplete theory once we can show that the empty set exists and that we can always adjoin new individual elements to existing sets. In fact (this really just follows from the same argument), the problem of deciding which sentences are theorems of this theory $\mathsf{N}$ is exactly as hard as the problem of deciding which sentences are theorems of $\mathsf{ZFC}$.


text:
Q: How to use 1 SQL query related to date and time in order to compare value difference

SELECT c.treatment_category, a.treatment_id, MAX(a.counts - b.counts) AS ReviewDifference

FROM

(SELECT treatment_id, COUNT(treatment_id) AS counts
FROM review
WHERE DATE(review.created) BETWEEN DATE(TIMESTAMP'2016-01-01 00:00:00.0') AND DATE(TIMESTAMP'2016-12-31 23:59:59.999')
GROUP BY treatment_id) a

LEFT JOIN

(SELECT treatment_id, COUNT(treatment_id)
FROM review
WHERE DATE(review.created) BETWEEN DATE(TIMESTAMP'2015-01-01 00:00:00.0') AND DATE(TIMESTAMP'2015-12-31 23:59:59.999')
GROUP BY treatment_id) b

ON a = b

LEFT JOIN

(SELECT t.treatment_category AS category, r.treatment_id AS number
FROM treatment t
LEFT JOIN review r
ON t.treatment_id = r.treatment_id
GROUP BY category, number) c

ON b.treatment_id = c.number

GROUP BY a.treatment_id, c.treatment_category
ORDER BY ReviewDifference DESC
LIMIT 1;

I need some hints or simpler query on how to do this question since it is related to date and time. Thank you.

*

*What treatment category has seen the biggest increase in reviews from 2015 to 2016?

Please see below for the tables.

I have provided my code snippet and I would like to find a simpler and cleaner way on writing the code.

A:  SELECT t.treatment_id, t.treatment_name,
        COUNT( CASE WHEN YEAR(created) = 2016 THEN r.review_id END)
      - COUNT( CASE WHEN YEAR(created) = 2015 THEN r.review_id END) as review_count
 FROM treatments t
 JOIN reviews r
   ON t.treatment_id = r.treatment_id
 GROUP BY t.treatment_id, t.treatment_name,
 ORDER BY review_count DESC


text:
Q: Whenever I type pip install on my Mac I get this error: fish: 'pip install tweepy' terminated by signal SIGABRT (Abort) Whenever I type pip install on my Mac, I get this error
fish: 'pip install tweepy' terminated by signal SIGABRT (Abort) and then I get this popup:
https://imgur.com/a/uILEq1v
It does not matter what Python library I try to install, I just get the same error

A: Your problem has nothing to do with the fish shell. The python 2.7 binary used by pip is attempting to load the /usr/lib/libcrypto.dylib shared library and that library in turn is calling abort(). Probably because it isn't compatible with the python 2.7 binary you installed with Homebrew. You probably recently updated macOS but didn't update the software installed by Homebrew. Try running brew upgrade then brew update.
And, as Mark noted in his comments, python 2.7 is dead and you really should switch to python 3.x.


text:
Q: When using scope "https://outlook.com/Calendars.ReadWrite" returns an empty token I'm trying to write an app that automatically add/delete/update events (Calendar) in office 365.
I followed this tutorial: https://dev.outlook.com/RestGettingStarted/Tutorial/dotnet . This way I managed to get the app to read mails and read events.
But when I try to add the scope ""https://outlook.office.com/Calendars.ReadWrite" so I can add events, I don't seem to be able to get a working authorisation token.
When I use breakpoints I see that the value for authResult.Token is null. How can I get a proper token?
public class HomeController : Controller
{
    // The required scopes for our app
    // "https://outlook.office.com/calendars.read",
    // "https://outlook.office.com/Calendars.ReadWrite"
    // "https://outlook.office.com/mail.read",
    private static string[] scopes = { "https://outlook.office.com/mail.read",
            "https://outlook.office.com/Calendars.ReadWrite" };

    public async Task<ActionResult> SignIn()
    {
        string authority = "https://login.microsoftonline.com/common";
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
        AuthenticationContext authContext = new AuthenticationContext(authority);

        // The url in our app that Azure should redirect to after successful signin
        Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

        // Generate the parameterized URL for Azure signin
        Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, clientId,
            redirectUri, UserIdentifier.AnyUser, null);

        // Redirect the browser to the Azure signin page
        return Redirect(authUri.ToString());
    }

    public async Task<ActionResult> Authorize()
    {
        // Get the 'code' parameter from the Azure redirect
        string authCode = Request.Params["code"];

        string authority = "https://login.microsoftonline.com/common";
        string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
        string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"];
        AuthenticationContext authContext = new AuthenticationContext(authority);

        // The same url we specified in the auth code request
        Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));

        // Use client ID and secret to establish app identity
        ClientCredential credential = new ClientCredential(clientId, clientSecret);

        try
        {
            // Get the token
            var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(authCode,
                redirectUri, credential, scopes);

            // Save the token in the session
            Session["access_token"] = authResult.Token;

            // Try to get user info
            Session["user_email"] = GetUserEmail(authContext, clientId);

            // return Content("Access Token: " + authResult.Token);
            return Redirect(Url.Action("Inbox", "Home", null, Request.Url.Scheme));
        }
        catch (AdalException ex)
        {
            return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
        }
    }


text:
Q: Band combinations for identifying limestone quarries What are the most useful band combinations for identifying current and recently closed limestone quarries (Landsat 5 and Landsat 8)?  In particular, for a dry sparsely vegetated region like much of Oman in the Middle East.

A: In my experience, when trying to classify new target types, it's probably safest to start with all bands, especially with Landsat since the number of bands is small (there is no memory/processing constraint that requires feature selection, as would be the case in hyperspectral imagery). Most classifiers will be able to show some statistic about which bands were most used, and if those measures are consistent you can then restrict your bands further. You will also usually get some gains by using multiple images over the same site, which will lead to vegetation, soil moisture, etc. differences that could potentially help distinguish the class of interest.
Note that for specific mineral identification, hyperspectral sensors tend to be the better option.


text:
Q: Java question about instance variables vs. local variables Sorry if I'm missing something obvious here, but I'm confused about what's going on. I declare Workout mWorkout; as an instance variable at the top of my class. Up until this point, it hasn't been initialized.
This code works: createWorkout returns a Workout object, which is stored in the local variable test, and then the instance variable mWorkout is set from that.
public void startWorkout() {
    Workout test = workoutFactory.createWorkout();
    mWorkout = test;
}

Whereas this code doesn't:
public void startWorkout() {
    mWorkout = workoutFactory.createWorkout();
}

mWorkout remains null even though createWorkout is still returning a Workout object.
Above code is slightly simplified for clarity.

A: Try qualifying mWorkout with this.
this.mWorkout = workoutFactory.createWorkout();

My assumption is that you have defined a local mWorkout that's shadowing your instance variable with the same name.

A: My bet is that somewhere in the non-working version of startWorkout you have declared a method-scope instance of mWorkout which is masking the instance field. If you tried this.mWorkout = ... you might get a different result.


text:
Q: Can I create a form to fill out a custom HTML email signature with JavaScript? I'm kind of familiar with coding, and I have heard that running script in an email signature is absolutely bad form; however, a client has asked me to create a way to allow their employees to input their own information into the signature so that they are all uniform. None have a coding background and I don't want to create 100 custom HTML signatures/create new ones for future hires. Only three "fields" would need to be customized.
So, I thought of sharing a simple web app like this (in its simplest form):


text:
Q: Using Microsoft attributes with Google TTS In my application, I am already using Google TTS but I am amazed by Microsoft TTS because they are providing a lot more useful attributes than Google. Since I am more familiar with Google, I would like to keep my implementation but would still like to be able to use MS attributes like:
<mstts:express-as style="cheerful">
    That'd be just amazing!
</mstts:express-as>

Is that possible?

A: There are no style attributes in Google Text-to-Speech, but you can change the Standard voice to a WaveNet voice[1].
The WaveNet voice synthesizes speech with more human-like emphasis and inflection on syllables, phonemes, and words. You can see all the supported voices in Google Text-to-Speech[2].
[1]https://cloud.google.com/text-to-speech/docs/wavenet#wavenet_voices
[2]https://cloud.google.com/text-to-speech/docs/voices