text:
Q: SQL : Select statement order by other table i want to select a column but with diferent order :
i have 2 table :
table_name:
+------+-----------+
| id   | name      |
+------+-----------+
| 1    |    Sindra |
| 2    |    Auli   |
| 3    |    Brian  |
| 4    |    Bina   |
| 5    |    zian   |
| 6    |    Bri    |
| 7    |    Andre  |
+------+-----------+

table_temp, id_temp_name foreign key of id(table_name) :
+------+--------------+
| id   | id_temp_name |
+------+--------------+
| 1    |    1         |
| 2    |    3         |
| 3    |    4         |
| 4    |    2         |
+------+--------------+

with this query :
  SELECT  table_name.id,table_name.name
  FROM table_name JOIN table_temp ON table_name.id= table_temp.id_temp_name
  ORDER BY table_temp.id_temp_name

i was looking for result that exactly same with id_temp_name order , but it showing value that not in to table_temp to order by asc ,so the result will be :
+------+-----------+
| id   | name      |
+------+-----------+
| 1    |    Sindra |
| 3    |    Brian  |
| 4    |    Bina   |
| 2    |    Auli   |
| 7    |    Andre  |
| 6    |    Bri    |
| 5    |    zian   |
+------+-----------+

thanks for any advice, .

A: Now, I tried so many times, and I could find queries that displays result exactly same as you needed. But work has to be done in two steps with an assumption that ids can't be negative.
Step-1: Create a valuable:
mysql> SET @max_id = (SELECT MAX(id) FROM table_name) * 2;
Query OK, 0 rows affected (0.00 sec)

Step-2: A nested Query that use above variable:
mysql> SELECT  a.id,
    ->         a.name
    -> FROM (
    -> SELECT  t.id as `id`,
    ->         t.name as `name`,
    ->         IF(t2.id, t2.id, @max_id := @max_id - 1)  as `id2`
    -> FROM table_name t
    -> LEFT OUTER JOIN table_temp t2
    ->   ON t.id= t2.id_temp_name
    -> GROUP BY t.id
    -> ORDER BY CASE  WHEN t2.id  THEN t2.id
    ->          ELSE  -t.id  END
    -> ) as a
    -> ORDER BY a.id2;
+------+--------+
| id   | name   |
+------+--------+
|    1 | Sindra |
|    3 | Brian  |
|    4 | Bina   |
|    2 | Auli   |
|    7 | Andre  |
|    6 | Bri    |
|    5 | zian   |
+------+--------+
7 rows in set (0.00 sec)

Check it working @ SQL Fiddle.
The logic is very simple, I used a bit math, and added new Id on the fly in inner SQL query. I used max_id variable twice of max value of present id in table_name purpose fully because I am generating id that should be grater than max and in decreasing order (I did subtraction).
Give it a try!!

A: AFTER EDIT 1:
You can proceed to this_way
SELECT  tgejala.id_gejala,tgejala.nama_gejala
FROM tgejala
LEFT JOIN ttemp ON tgejala.id_gejala= ttemp.idtemp_gejala
ORDER BY CASE WHEN ttemp.id_temp is NULL THEN 1 ELSE 0 END

EDIT 2:
Ok then see the below this would work
SELECT  tgejala.id_gejala,tgejala.nama_gejala
FROM tgejala
LEFT JOIN ttemp ON tgejala.id_gejala= ttemp.idtemp_gejala
ORDER BY CASE WHEN ttemp.id_temp is NULL THEN 1 ELSE 0 END, table_name.id desc

This will give you the following result
+------+-----------+
| id   | name      |
+------+-----------+
| 1    |    Sindra |
| 3    |    Brian  |
| 4    |    Bina   |
| 2    |    Auli   |
| 7    |    Andre  |
| 6    |    Bri    |
| 5    |    zian   |
+------+-----------+

A: If I understand correctly, you need a left outer join so you keep all the records in the first table:
  SELECT  tn.id, tn.name
  FROM table_name tn LEFT OUTER JOIN
       table_temp tt
       ON tn.id= tt.id_temp_name
  ORDER BY (tt.id_temp_name is not null) desc,
           tt.id_temp_name ;

The first condition in the order by is to ensure that the missing values go last, regardless of the order of the second clause.

A: Try This:
Select a.id_temp_name, b.name
from table_temp a, table_name b
where a.id = b.id
order by a.id_temp_name;

See if that works for you.

A: Here is the solution for your problem in SQL Server:
SELECT  table_name.id,table_name.name
FROM table_name as table_name
LEFT JOIN table_temp as table_temp ON table_name.id= table_temp.id_temp_name
ORDER BY CASE
    WHEN cast(table_temp.id as varchar) IS NOT NULL
        THEN cast(table_temp.id as varchar)
    ELSE table_name.name  END asc


text:
Q: Using Git is there equivalent to Mercurial Push command? I've been using TortoiseHg/Mercurial for many years and am now using Git for first time with SourceTree and TortoiseGit GUI.  From this link I understand that PUSH is different on Git from Mercurial.  Mercurial PUSH only affects the remote repository but doesn't touch the workspace.  PUSH with Git on the other hand not only updates the repository but also the workspace (and index which Mercurial doesn't have).
My question is does Git have the equivalent of Mercurial PUSH?  Can I PUSH to a remote repository and leave the workspace and index as it is?  I know Git FETCH is the equivalent of Mercurial PULL in that neither of them modify the local workspace.  Effectively I'm looking for a reverse FETCH for Git.  Is that possible or must I always open the remote repository and do a FETCH instead?

A: Edit: TL;DR summary:

*

*When using Git, you can push to a repository humans use, that has a work-tree.  You just should not push to the current branch within that repository, at least, not without special considerations.  So Git blocks this by default.

*Mercurial allows you to push to such repositories, including to the "current branch"—this phrase means something different in Mercurial—because in Mercurial, what Git would call a "detached HEAD" is a normal and usable state.  This can be done in Git, it's just not very practical.

*Therefore, Git offers, and you should generally use, bare repositories as push targets.  These have no work-tree and therefore Git allows pushes to them, even to the "current branch" (Git's notion, rather than Mercurial's).
Original complete reply below.

As MrTux said, this claim is wrong:

PUSH with Git on the other hand not only updates the repository but also the workspace (and index which Mercurial doesn't have).

While pushing updates the repository (adding new commits as usual), it does not—at least, not by default—update the index, nor the work-tree.  (It can be configured to do so in versions of Git starting from Git 2.4.0.)
The problem here is a mismatch between some fairly deep philosophical notions.  The answer to this:

My question is does Git have the equivalent of Mercurial PUSH? Can I PUSH to a remote repository and leave the workspace and index as it is?

is "yes, using detached HEAD", but that answer is not as useful as you might think.
In Mercurial, the current revision (known as ., vs the name HEAD in Git) is checked-out, and possibly modified, in much the same way as it would be in Git if you were using a Git "detached HEAD" (though with some important differences).  The index itself—the thing that exists and is exposed in Git, but does not exist in that form and is well-hidden in Mercurial—is not directly relevant.
The problem is that in Mercurial, the current branch is well-separated from the current revision.  In Git, the two are deeply intertwingled.  Clearly the current revision is on some branch: all revisions are on some branch, in Mercurial.  But in Mercurial, all revisions are on exactly one branch.  In Git, a revision—a commit—may be on many branches simultaneously: none, one, two, ten, or thousands.  While the commit is unchanging and permanent (in both Git and Mercurial), the set of branches that contain the commit is fixed and unchanging in Mercurial, but totally fluid in Git.
Git (deliberately1) discards the idea that a branch name is anything more than a temporary, ephemeral label.  The use of a branch name is just to identify one specific commit, for right now, mostly for humans to use, but also for use during git push and git fetch.
Therefore, since HEAD in Git contains the branch name—let's call this cb for Current Branch—and the branch name contains the commit ID, we will get in terrible trouble if we change the name-to-ID mapping in an unexpected manner.  If receiving a push updates cb, while we are (through HEAD) using it as our current revision, we will get confused: we will believe that our index and work-tree apply to the commit to which cb now points, instead of the commit to which cb used to point before the update.
Again, this is not a problem in Mercurial, because in Mercurial, the system knows which is the current revision.  Pushing new revisions (commits) into the branch does not affect our current revision, and in fact, if we make a new commit without updating, we just get a new commit that is a new head (lowercase, not Git's all-caps HEAD thing).  This new head will have no name, unless we're using bookmarks, but having heads with no name is an ordinary state in Mercurial.  We merely run hg heads to find these unnamed heads, and hg update -r to those revisions to work on them (such as to merge them, usually with other heads).
In Git, you can get precisely this state: it's that "detached HEAD".  A detached HEAD contains a commit ID directly, rather than a branch name.  Now that Git won't lose the current revision (or rather, commit hash ID), it's safe to push to this repository.
The problem is that when you have a detached HEAD, while you can make new commits, they're being remembered only by the name HEAD.  They are on no branches.  (If you prefer, you can call HEAD an "anonymous branch".  It has the name HEAD but HEAD is not actually a branch name, as all branch names semi-secretly start with refs/heads/, and HEAD does not.)  To make Git remember it more permanently, you must give this thing a branch name:
git checkout -b newbranch

which changes HEAD from "detached" to "attached", to the new branch newbranch.  The branch name newbranch now stores the commit hash ID and the name HEAD now stores the branch-name newbranch.
But now you can't push to newbranch!
So as long as HEAD is not "detached", there is some branch you cannot, or at least should not, push to ... and for HEAD to work well, it must eventually be re-attached to a branch, maybe a new branch.
Note that you can push to any other branch.  All the other branches are not in the index and not in the work-tree.
The new capability in Git 2.4.0 and later is that you can set receive.denyCurrentBranch to updateInstead.  When it is set this way, a Git on the receiving end of git push checks:

*

*Is the push going to the branch that is the current branch?  That is, does HEAD have the name of a branch in it, and if so, is the push going to update this branch name?

*If not (and all other tests pass), allow the update.

*If so, check receive.denyCurrentBranch:

*

*true or refuse: reject the push

*false or ignore: accept the push, leaving the index and work-tree alone, relying on whoever is using this repository to know what to do

*warn: accept the push, printing a warning to whoever is doing the push (ideally this is the same person who will know what to do, otherwise the warning is useless).

*updateInstead: check one more thing (see below).

In the updateInstead mode, things get complicated.  See the description in the git config documentation and the description of the push-to-checkout hook in the githooks documentation.  The short version is that if the index and work-tree are clean, the push will generally be allowed and the receiving repository will be updated to the new branch-tip.
In general, though, your best bet is the much simpler rule: just don't do it.2  Don't push to a repository that has humans working in it.  It's a bad idea.  Push only to repositories that never have humans working in them.  Configuring a Git repository as "bare" guarantees that no human can work in it, as it has no work-tree.

1This is either a wonderful idea, or a terrible idea, or perhaps both at the same time.  Either way, it's radically different.
2This might be called the anti-Nike rule. :-)

A: Git push does not modify the index.

A: While "Don't push to a repository that has humans working in it" in the other answer applies well to regular team collaboration, sometimes you need to distribute unfinished changes between private repositories and using bare repository at server is overkill for it. You can do it without having to deal with issues of pushing to current branch by pushing to a remote namespace:
push user@workstation:src/project 'refs/heads/*:refs/remotes/my-laptop/*'

so that when you return to the workstation, you can merge or cherry-pick changes from remote branches in the my-laptop/ namespace. It also indicates that that work has done in another repository, which should easier to navigate later.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MessageBox Bring to front in WPF tray icon app My app is in the tray icon and I want a messagebox to first appear on front but not stay on top.
If I click another window the messagebox should not stay on top.
Also I want to open several message boxes at the same time, so when the user overs the mouse on the taskbar they can see a preview of all the message boxes. This works with default messagebox but I can't bring it to front when it first appears.
I tried the win32 api with all the modes and also making new forms but nothing works for all the requirements...
C# MessageBox To Front When App is Minimized To Tray


text:
Q: Docker compose: How to invoke command in one container from another? I understand docker compose creates a network of containers.
Now, is there a way to provide a program implemented in a container_B and invoke it from within container A?
Consider this example:
version: "3.2"

services:
  container_A:
    image: 'alpine:latest'
    links:
      - container_B

  container_B:
    image: 'python:3.7.0a3-alpine3.7'

I would then like to use python from within container_A - be it interactively or from scripts I write.
Of course, this is just an over-simplified example, but I'd like to provide a container for any program, in this example python, but could be FFmpeg, or vim or you name it.
So the question is, whether there is a way to use containers not only over the network, but also invoke programs contained within them?
Help will be much appreciated.


text:
Q: Automated test of client/server application As the headline says, how would you test a client/server application, that is written in C/C++, that talks through a protocol over a network? Im a bit confused on how to do this. I have thought about making some mocking, but I have never tried mocking, so I dont know if this is the best way.
How should I do this? I have written many unit tests, but never tried to test something that interact over a network.

A: I use the command pattern in the unit test driver (client) to send test commands to the server. The advantage of this is that the test is coded in one place.
Example for testing a request timeout:
Client sends a sleep command to server and then the request. The request times out and the test case is passed.

A: Typically you'll want to use mocking to verify that each side reacts as required to messages from the other side (e.g., that when the client receives a response from the server that it processes that response correctly).
To test the network functionality itself, you can test both running on the same machine, and you can run one (or both) inside a virtual machine. If you have two network adapters, you can even dedicate each to a virtual machine so the network traffic actually goes out one, to a switch/router, and comes back in the other (particularly useful when/if you want to capture and verify packets).

A: I have some client/server code that I unit test through the loopback address. I use some mocks when I have to test error conditions. So, I test with the real code when I can and the mocks when I need to trigger very specific conditions.


text:
Q: How to add test method's comment sections from IntelliJ automatically? I am creating test classes from the IntelliJ automatically like following

This gives me the test class as following in the related module accordingly:
public class MyClassTest {
    @Test
    public void myMethod() {
    }
}

What I am looking for is that

Does IntelliJ can automatically insert Given When Then comment sections into test methods?

I am searching for something like following:
public class MyClassTest {
    @Test
    public void myMethod() {
        // Given
        // When
        // Then
    }
}

These sections are useful for the reader coming after some times passed but usually missed while writing test methods. I am looking for a solution to add this behavior to IDE.

A: Of course. Navigate to Settings - Editor - File and Code templates - JUnit Test Method


text:
Q: How To Put Container Over Extended Divs? This is best to describe in pictures! The box with the asldskd, i want to be where the red area is. I want to put a logo in the black area and then put seperate content into the green area. I basically want to have the black and green extensions, but i want the content to be inside a 900px container.
this is what i have now. i tried using z-index to do this. is there a way to force the black green bars outside the 900px container, or do i need to keep the container below it?

 laksjdf

 alskdjf

asdf

and here is the css:
#header {
width:100%;
height:70px;
background-color:black;
position:relative;
z-index:0;
 }

#subheader {
width:100%;
height:25px;
background-color:green;
position:relative;
z-index:1;
 }

#container {
width:900px;
margin:0 auto;
border:1px solid black;
position:relative;
z-index:1;
 }

A: Here you go, I made a codepen for you, tell me if it whats you wanted
http://codepen.io/anon/pen/yHzxd


text:
Q: How to ask permission (RunTime) again if the user deny for the first time I want to re ask the permission to the user in the situation if he/she deny for the first time. I have set the permission but my app runs even if I press deny option. I have a code which should do the things which I want to do but I get Cant resolve symbol Snackbar when I hit Alt+Enter it created another activity and remaining -make and -permision_available_camera gets red error.
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {

        if (requestCode == REQUEST_CAMERA) {
            // BEGIN_INCLUDE(permission_result)
            // Received permission result for camera permission.
            Log.i(TAG, "Received response for Camera permission request.");

            // Check if the only required permission has been granted
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Camera permission has been granted, preview can be displayed
                Log.i(TAG, "CAMERA permission has now been granted. Showing preview.");
                Snackbar.make(mLayout, R.string.permision_available_camera,
                        Snackbar.LENGTH_SHORT).show();
            } else {
                Log.i(TAG, "CAMERA permission was NOT granted.");
                Snackbar.make(mLayout, R.string.permissions_not_granted,
                        Snackbar.LENGTH_SHORT).show();

            }

A:
Try this

Basically here we are trying to read the content from the External Storage. For that, we have to ask the user for runtime permission. If the user allows it's fine, but if the user denies the permission it will display a second dialog/message box until the user accepts the permission

*

*Asking for permission

*If the user denies it will display the 'Permission Needed' dialog whenever the user launches the application

*If the user presses the OK button it will ask permission again.

 public class MainActivity extends AppCompatActivity {

        public static int REQUEST_PERMISSION=1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            permission_fn();

        }

        private  void requestStoragePermission()
        {
            if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE))
            {
                new AlertDialog.Builder(this)
                        .setTitle("Permission Needed")
                        .setMessage("Permission is needed to access files from your device...")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).create().show();
            }
            else
            {
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
            }
        }

        private void permission_fn()
        {
            if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED)
            {
                if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE))
                {

                }
                else
                {
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUEST_PERMISSION);
                }
            }
            else {

                requestStoragePermission();

            }
        }

        @Override
        public void onRequestPermissionsResult(int requestCode, String[] permissions,  int[] grantResults) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_PERMISSION) {

                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Thanks for enabling the permission", Toast.LENGTH_SHORT).show();

                    //do something permission is allowed here....

                } else {

                    Toast.makeText(this, "Please allow the Permission", Toast.LENGTH_SHORT).show();

                }
            }

        }

        }

Add user permission in AndroidManifest.xml file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

A: @Arjun Thakun Here is a way to manage the concept of ask permission again and deal with all the ways the user can answer when the app asks about permissions
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //.... write file into storage ...
            System.out.println("SDK > BuildVersion TRUE");
        } else {
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 666);  // Comment 26
            System.out.println("go to requestPermissions");
        }
    }
    onLoad();
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {

        case 666: // Allowed was selected so Permission granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Snackbar s = Snackbar.make(findViewById(android.R.id.content),"Permission Granted",Snackbar.LENGTH_LONG);
                View snackbarView = s.getView();
                TextView textView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);
                textView.setTextColor(Color.RED);
                textView.setTextSize(18);
                textView.setMaxLines(6);
                s.show();

                // do your work here

            } else if (Build.VERSION.SDK_INT >= 23 && !shouldShowRequestPermissionRationale(permissions[0])) {
                // User selected the Never Ask Again Option Change settings in app settings manually
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle("Change Permissions in Settings");
                alertDialogBuilder
                        .setMessage("" +
                                "\nClick SETTINGS to Manually Set\n"+"Permissions to use Database Storage")
                        .setCancelable(false)
                        .setPositiveButton("SETTINGS", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getPackageName(), null);
                                intent.setData(uri);
                                startActivityForResult(intent, 1000);     // Comment 3.
                            }
                        });

                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();

            } else {
                    // User selected Deny Dialog to EXIT App ==> OR <== RETRY to have a second chance to Allow Permissions
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {

                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                    alertDialogBuilder.setTitle("Second Chance");
                    alertDialogBuilder
                            .setMessage("Click RETRY to Set Permissions to Allow\n\n"+"Click EXIT to the Close App")
                            .setCancelable(false)
                            .setPositiveButton("RETRY", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    //ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Integer.parseInt(WRITE_EXTERNAL_STORAGE));
                                    Intent i = new Intent(MainActivity.this,MainActivity.class);
                                    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(i);
                                    }
                            })
                            .setNegativeButton("EXIT", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    finish();
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    alertDialog.show();
                }
            }
            break;
    }};


text:
Q: Could not send mail using SMTP In xampp in mac but it works well in windows Error as below:
SMTP -> ERROR: Failed to connect to server: (0)
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error:  Could not connect to SMTP host.


text:
Q: sbt build issue - IO error while decoding code.scala with UTF-8 I am trying to sbt assembly my code (script.scala) on my Windows 7 machine using cmd, and I am getting the above posted error.
I have also tried to set this on cmd
JAVA_TOOL_OPTIONS='-Dfile.encoding=UTF8' but it still does not help.
I am editing the file using Notepad++ and once the jar is built running it on my Hadoop cluster.


text:
Q: how to import Laravel 4.2 live project into locallhost i am importing a live Laravel 4.2 Web application and setup it into my localhost for development.
in the Laravel 5 we usually find the .env file in the root dictionary but in Laravel 4.2 i couldn't be able to find .env and another component and their dictionaries are also different.
can anybody tell me how to import my laravel 4.2 web app into the local host step by step?

A: All of the configuration files for the Laravel framework are stored in the app/config directory 1. You have to set everything directly there or build an own  .env.local.php file with default values like this:
<?php
//file: /.env.local.php
// return the configuration for the 'local' environment
return array(
    'db_host' => '127.0.0.1',
    'db_name' => 'DB_NAME', // specify database name
    'db_user' => 'DB_USER', // specify database username
    'db_pass' => 'DB_PASS', // specify database password
);


text:
Q: Multi Line Frame Title with Image in Beamer I'm wanting to try and make a header in beamer like the following (mockup from libreoffice, ignore the grid):

I've been trying to use a number of methods, but I just can't get it right. This is where I'm at at the moment code-wise (with framebox being a pre-defined beamercolor).
\setbeamertemplate{headline} {
  \begin{minipage}{.7\paperwidth}
    % Section Heading
    \vspace{5mm}
    {
      \noindent\hspace{5mm}\usebeamercolor[fg]{}\insertsection
    }
    \\
    % Slide Title
    \begin{beamercolorbox}[wd=\textwidth,ht=2ex,dp=1ex,left]{framebox}%
      \hspace{5mm}\usebeamerfont{section in head/foot}\insertframetitle\hspace*{2ex}
    \end{beamercolorbox}
  \end{minipage}
  \begin{tikzpicture}[remember picture, overlay]
    \node[anchor=north east] at ([yshift=-5mm, xshift=-5mm] current page.north east) {MY LOGO HERE}
  \end{tikzpicture}
}

This code gets it roughly in the right place on most slides (it's off for the table of contents), but the rest of the text is completely shifted off the frame and is no longer visible.
Update: Added Example Images
Before adding tikzpicture:

And after (creates a dozen of these slides):


text:
Q: HTML audio playback causing flickering in iPhone I'm trying to create a simple tuner built using Paper.js on top of a node.js stack.
The tuner works well in a desktop browser, but when in an iPhone or iPad, clicking on one of the six rectangles (or strings) causes an odd flickering of the screen:
http://morning-temple-9106.herokuapp.com/
I tried these css fixes that were related to general html flickering on the iphone, but no luck.
canvas {
    -webkit-backface-visibility: hidden;
    -webkit-transform: translate3d(0,0,0);
}

here is the JS that loads the audio -- I load the files before playNote is called for faster playback. the flicker occurs even if I load within playNote.
var audioPlayerE = new Audio();
audioPlayerE.src="strings/E.mp3"
audioPlayerE.load();
var audioPlayerA = new Audio();
audioPlayerA.src="strings/A.mp3"
audioPlayerA.load();
var audioPlayerD = new Audio();
audioPlayerD.src="strings/D.mp3";
audioPlayerD.load();
var audioPlayerG = new Audio();
audioPlayerG.src="strings/G.mp3";
audioPlayerG.load();
var audioPlayerB = new Audio();
audioPlayerB.src="strings/B.mp3";
audioPlayerB.load();
var audioPlayerElittle = new Audio();
audioPlayerElittle.src="strings/Elittle.mp3";
audioPlayerElittle.load();

playNote = function(index,count) {
    var noteStr;
    if(index-count==0) {audioPlayerE.play()}
    if(index-count==1) {audioPlayerA.play()}
    if(index-count==2) {audioPlayerD.play()}
    if(index-count==3) {audioPlayerG.play()}
    if(index-count==4) {audioPlayerB.play()}
    if(index-count==5) {audioPlayerElittle.play()}
}

Here is my github repo:
https://github.com/dannycochran/cs184

A: from:
iPad Safari: How to disable the quick blinking effect when a link has been hit
didn't realize it was just a blinking effect, adding this to the css fixed it:
-webkit-tap-highlight-color: rgba(0,0,0,0);


text:
Q: The example-runtime-bundle by Activiti cloud application don't work. Activiti cloud 7.1.0-M8 I try to start the example-runtime-bundleexapmple (https://github.com/Activiti/activiti-cloud-application.git) but the project dont't start.
The "java.lang.IllegalArgumentException: A default binder has been requested error, but there is no binder available" error is appeared and the application is crashed.
Anybody did run this project ? How can i run this project?

:: Spring Boot ::        (v2.2.8.RELEASE) :: Spring Boot ::        (v2.2.8.RELEASE)

2020-08-15 10:58:08.685  INFO [,,,] 91864 --- [           main]
o.a.c.runtime.RuntimeBundleApplication   : No active profile set,
falling back to default profiles: default 2020-08-15 10:58:09.293
INFO [,,,] 91864 --- [           main]
o.s.c.a.ConfigurationClassParser         : Properties location
[classpath:/activiti-audit-producer.properties] not resolvable: class
path resource [activiti-audit-producer.properties] cannot be opened
because it does not exist 2020-08-15 10:58:10.784  INFO [,,,] 91864
--- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=28b2cb7c-0c5f-3fb9-a7a6-b942747f204a 2020-08-15
10:58:10.885  INFO [,,,] 91864 --- [           main]
faultConfiguringBeanFactoryPostProcessor : No bean named
'errorChannel' has been explicitly defined. Therefore, a default
PublishSubscribeChannel will be created. 2020-08-15 10:58:10.892  INFO
[,,,] 91864 --- [           main]
faultConfiguringBeanFactoryPostProcessor : No bean named
'taskScheduler' has been explicitly defined. Therefore, a default
ThreadPoolTaskScheduler will be created.
........... ......... .........

.ApplicationContextException: Failed to start bean 'outputBindingLifecycle'; nested exception is
java.lang.IllegalArgumentException: A default binder has been
requested, but there is no binder available 2020-08-15 10:58:26.091
WARN [,,,] 91864 --- [           main]
o.s.b.f.support.DisposableBeanAdapter    : Invocation of destroy
method failed on bean with name 'tomcatMetricsBinder':
java.lang.NullPointerException 2020-08-15 10:58:26.106  INFO [,,,]
91864 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          :
Shutting down ExecutorService 'taskScheduler' 2020-08-15 10:58:26.107
INFO [,,,] 91864 --- [           main]
o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down
ExecutorService 'applicationTaskExecutor' 2020-08-15 10:58:26.108
INFO [,,,] 91864 --- [           main]
com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown
initiated... 2020-08-15 10:58:26.115  INFO [,,,] 91864 --- [
main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 -
Shutdown completed. 2020-08-15 10:58:26.117  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'auditProducer' 2020-08-15 10:58:26.117  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'integrationErrorsConsumer' 2020-08-15 10:58:26.117  INFO [,,,]
91864 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   :
Summary on shutdown: bean 'signalProducer' 2020-08-15 10:58:26.117
INFO [,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown: bean
'commandResults' 2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
nullChannel 2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'messageEvents' 2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'signalConsumer' 2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'asyncExecutorJobs' 2020-08-15 10:58:26.118  INFO [,,,] 91864 ---
[           main] o.s.i.monitor.IntegrationMBeanExporter   : Summary
on shutdown: bean 'commandConsumer' 2020-08-15 10:58:26.118  INFO
[,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown: bean
'errorChannel' 2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [
main] o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
bean 'integrationResultsConsumer' 2020-08-15 10:58:26.118  INFO [,,,]
91864 --- [           main] o.s.i.monitor.IntegrationMBeanExporter   :
Summary on shutdown:
org.springframework.cloud.stream.binding.StreamListenerMessageHandler@4e9b4e98
2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
org.springframework.cloud.stream.binding.StreamListenerMessageHandler@6e3f108c
2020-08-15 10:58:26.118  INFO [,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown: bean
'_org.springframework.integration.errorLogger.handler' for component
'_org.springframework.integration.errorLogger' 2020-08-15 10:58:26.118
INFO [,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
org.springframework.cloud.stream.binding.StreamListenerMessageHandler@1eba2b8d
2020-08-15 10:58:26.119  INFO [,,,] 91864 --- [           main]
o.s.i.monitor.IntegrationMBeanExporter   : Summary on shutdown:
org.springframework.cloud.stream.binding.StreamListenerMessageHandler@329b6556
2020-08-15 10:58:26.121  INFO [,,,] 91864 --- [           main]
o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2020-08-15 10:58:26.144  INFO [,,,] 91864 --- [           main]
ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report
re-run your application with 'debug' enabled. 2020-08-15 10:58:26.153
ERROR [,,,] 91864 --- [           main] o.s.boot.SpringApplication
: Application run failed
org.springframework.context.ApplicationContextException: Failed to
start bean 'outputBindingLifecycle'; nested exception is
java.lang.IllegalArgumentException: A default binder has been
requested, but there is no binder available   at
org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:185)
at
org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53)
at
org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360)
at
org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158)
at
org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122)
at
org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:895)
at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554)
at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
at
org.activiti.cloud.runtime.RuntimeBundleApplication.main(RuntimeBundleApplication.java:27)
Caused by: java.lang.IllegalArgumentException: A default binder has
been requested, but there is no binder available  at
org.springframework.util.Assert.notEmpty(Assert.java:549)     at
org.springframework.cloud.stream.binder.DefaultBinderFactory.doGetBinder(DefaultBinderFactory.java:157)
at
org.springframework.cloud.stream.binder.DefaultBinderFactory.getBinder(DefaultBinderFactory.java:140)
at
org.springframework.cloud.stream.binding.BindingService.getBinder(BindingService.java:379)
at
org.springframework.cloud.stream.binding.BindingService.bindProducer(BindingService.java:268)
at
org.springframework.cloud.stream.binding.BindingService.bindProducer(BindingService.java:291)
at
org.springframework.cloud.stream.binding.AbstractBindableProxyFactory.createAndBindOutputs(AbstractBindableProxyFactory.java:136)
at
org.springframework.cloud.stream.binding.OutputBindingLifecycle.doStartWithBindable(OutputBindingLifecycle.java:58)
at
java.base/java.util.LinkedHashMap$LinkedValues.forEach(LinkedHashMap.java:608)
at
org.springframework.cloud.stream.binding.AbstractBindingLifecycle.start(AbstractBindingLifecycle.java:57)
at
org.springframework.cloud.stream.binding.OutputBindingLifecycle.start(OutputBindingLifecycle.java:34)
at
org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:182)
... 14 common frames omitted


text:
Q: Prove sum of $\cos(\pi/11)+\cos(3\pi/11)+...+\cos(9\pi/11)=1/2$ using Euler's formula Prove that $$\cos(\pi/11)+\cos(3\pi/11)+\cos(5\pi/11)+\cos(7\pi/11)+\cos(9\pi/11)=1/2$$
using Euler's formula.
Everything I tried has failed so far.
Here is one thing I tried, but obviously didn't work.
$$\Re e \{e^{\frac{\pi}{11}i}(1+e^{\frac{2\pi}{11}i}+e^{\frac{4\pi}{11}i}+e^{\frac{6\pi}{11}i}+e^{\frac{8\pi}{11}i}) \}=\frac{1}{2}$$
$$\Re e \{e^{\frac{\pi}{11}i}(1+\sqrt[11]{e^{2\pi i}}+\sqrt[11]{e^{4\pi i}}+\sqrt[11]{e^{6\pi i}}+\sqrt[11]{e^{8\pi i}}) \}=\frac{1}{2}$$
$$\Re e \{e^{\frac{\pi}{11}i}(1+\sqrt[11]{1}+\sqrt[11]{1}+\sqrt[11]{1}+\sqrt[11]{1}) \}=\frac{1}{2}$$
$$\Re e \{5e^{\frac{\pi}{11}i} \}=\frac{1}{2}$$
$$5\cos(\frac{\pi}{11})=\frac{1}{2}$$
Which isn't true :D
Thanks in advance

A: Put $$S = \cos(π/11)+\cos(3π/11)+\cos(5π/11)+\cos(7π/11)+\cos(9π/11)$$
Then $$S = \cos(-π/11)+\cos(-3π/11)+\cos(-5π/11)+\cos(-7π/11)+\cos(-9π/11)$$ (because cos is even)
and of course $$ -1 = \cos (-11\pi/11)$$
Sum these all up and you get $$2S-1$$ as the sum of the real parts of the eleven eleventh-roots of unity, which is 0, and therefore $$S = 1/2$$

A: HINT:
First of all, $$e^x=1\iff x=2n\pi$$ where $n$ is some integer
$\sum_{r=0}^5\cos\frac{(2r+1)\pi}{11}$
=Re[$\sum_{r=0}^5\left(e^{\frac{\pi i}{11}}\right)^{2r+1}$]
Now  $\sum_{r=0}^5\left(e^{\frac{\pi i}{11}}\right)^{2r+1}$ is a Geometric Series

A: Sum of cosines of $n$ angles in Arithmetic Progression ( starting at $ \alpha$, common angle difference $\beta$ ) has a ready formula, with simple trig derivation/simplification:
$$ \cos \alpha + \cos ( \alpha + \beta )+  \cos ( \alpha + 2\beta) +  \cos ( \alpha + (n-1) \beta   = \dfrac { \sin (n \beta/2)} { \sin (\beta/2) }\cdot \cos ( \alpha + {(n+1)\beta/2} ).   $$
The same is likewise valid for sines, the quotient does not change.
$$ \sin \alpha + \sin ( \alpha + \beta )+  \sin ( \alpha + 2\beta) +  \sin ( \alpha + (n-1) \beta   = \dfrac { \sin (n \beta/2)} { \sin (\beta/2) }\cdot \sin ( \alpha + {(n+1)\beta/2} ).  $$
EDIT1:
Multiply second equation with $ i$ and add to the first one. Use  Euler's relation in a geometric series with constant ratio terms, common difference is in the exponent.


text:
Q: React-native: On reload app, user must remain in logged in status I have a login page, when I click on login button it renders me to a demo page that i created. I am trying to use AsyncStorage so that when i reload the app while i am on the demo page, it should not go back to the login page, it must retain on the demo page itself.
Here is my demo page where i used AsyncStorage:
'use strict';
var React = require('react-native');
var {
    AsyncStorage,
    StyleSheet,
    Text,
    View,
} = React;
var NavigationBar = require('react-native-navbar');
var Demo = React.createClass({

    getData: function()
    {
        AsyncStorage.getItem("isLogin").then((yes)=>{
            this.setState({"isLogin":yes});
        }).done();
    },

    storeData: function(yes)
    {
        AsyncStorage.setItem("isLogin", yes);
        this.setState({"isLogin":yes});
    },

    render: function()
    {
        let context = this;
        var leftButtonConfig = {
          title: 'Logout',
          handler: function onNext() {
            context.props.navigator.pop();
          }
        };

        var titleConfig = {
          title: 'Hello world page!',
        };
        return(
            <View style={{ flex: 1, }}>
      <NavigationBar
        title={titleConfig}
        leftButton={leftButtonConfig}
        style={{borderBottomWidth: 1 / React.PixelRatio.get(), borderBottomColor: 'rgba(0, 0, 0, 0.5)',}} />

            <View style={styles.container}>
        <Text style={styles.header}>
        Hello World
        </Text>
        </View>
        </View>
        );
    }
});
var styles = StyleSheet.create({
    container: {
        flex:1
    },
    header: {
        fontSize: 20,
        fontWeight: 'bold',
        textAlign: 'center'
    }
});

module.exports = Demo;

How can I call this AsyncStorage?

A: If you write React component in ES6 style, you can call getData in constructor, which would definitely be called before it first renders its content.
import React, {Component} from 'react';

class Demo extends Component {
    constructor(props) {
        super(props);
        getData();
    }
    getData(){
        AsyncStorage.getItem("isLogin").then((yes)=>{
            this.setState({"isLogin":yes});
        }).done();
    }
    render() {
        return (...);
    }
}

export default Demo;

This post below describes how to write React classes in ES6 style in detail.
https://toddmotto.com/react-create-class-versus-component/


text:
Q: java.net.SocketException: socket failed: EPERM (Operation not permitted) I am working on an Android Studio project with several activities. I am currently trying to read the output from a Java Servlet on localhost but it seems to be crashing due to a socket permission.
I've made a new project, used the exact same code and worked perfectly. So I dont understand why is not willing to work on my project.
public class LoginActivity extends AppCompatActivity {

String apiUrl = "http://10.0.2.2:8080/ProyectService/Servlet?action=login";
EditText username;
EditText password;
AlertDialog dialog;
Usuario session;

@Override
public void onCreate(Bundle savedInstanceState) {
    // Inicializacion de ventana
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    getSupportActionBar().hide();

    // Inicializacion de componentes
    username = findViewById(R.id.username);
    password = findViewById(R.id.password);

    // Inicializacion de funcionalidad de botones
    Button button= (Button) findViewById(R.id.login);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            UserLoginTask mAuthTask = new UserLoginTask();
            mAuthTask.execute();
        }
    });

    password = findViewById(R.id.password);
    createAlertDialog("Usuario o Contraseña Incorrectos");
    }

    private void createAlertDialog(String message){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(message)
            .setTitle("Error");
    dialog = builder.create();
    }

    // ASYNCRONUS NETWORK PROCESS

    public class UserLoginTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected String doInBackground(String... params) {

        // implement API in background and store the response in current variable
        String current = "";
        try {
            URL url;
            HttpURLConnection urlConnection = null;
            try {
                url = new URL(apiUrl);
                System.out.println(apiUrl);
                urlConnection = (HttpURLConnection) url
                        .openConnection();

                InputStream in = urlConnection.getInputStream();

                InputStreamReader isw = new InputStreamReader(in);

                int data = isw.read();
                while (data != -1) {
                    current += (char) data;
                    data = isw.read();
                    //System.out.print(current);

                }
                System.out.print(current);
                // return the data to onPostExecute method
                return current;

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return "Exception: " + e.getMessage();
        }
        return current;
        }
    }

    protected void onPostExecute(String success) {
        Log.i(success, "");
       //attemptLogin();
    }
}

I Expect it to read the data but it crashes at this line:
InputStream in = urlConnection.getInputStream();

This is the error output:
java.net.SocketException: socket failed: EPERM (Operation not permitted)
at java.net.Socket.createImpl(Socket.java:492)
at java.net.Socket.getImpl(Socket.java:552)
at java.net.Socket.setSoTimeout(Socket.java:1180)
at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:114)
at com.example.controller.LoginActivity$UserLoginTask.doInBackground(LoginActivity.java:93)
at android.os.AsyncTask$3.call(AsyncTask.java:378)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)

A: Your app needs additional permissions and/or to be reinstalled.
Add additional permissions to AndroidManifest.xml within the <manifest> section:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

To reinstall, uninstall the app from the emulator or physical connected device and then run it again.  (If adding permissions, make sure to reinstall afterwards.)

A: First of all you need change your android manifest .xml
But after this action you must uninstall application and run it again.
https://developer.android.com/training/basics/network-ops/connecting
and code here:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in AndroidManifest.xml

A: Set  android:usesCleartextTraffic="true" in the manifest file.
Add the permission INTERNET.
Uninstall app and then install again.

A: Set android:usesCleartextTraffic="true" in the manifest file. Add the permission INTERNET. Uninstall app and then install again.its work to me

A: If you are using a localhost server on your Mac then use the local IP address that is assigned for your machine as your API address. i.e. 192.168.x.x (find it in Settings -> Network) not localhost nor 127.0.0.1.
As they mentioned above, uninstall the app and then put these tags in your manifest:
in the application section:
android:usesCleartextTraffic="true"

Then in your manifest section:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.a.myapp">
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

A: Working solution.

*

*check if you have INTERNET permission and ACCESS_NETWORK_STATE permission, if not add these.

*uninstall the app and install again. If not try in different device. It will work 100%. I face same issue and solved this by using these steps.

A: If you forgot to add <uses-permission android:name="android.permission.INTERNET" /> to your Manifest.xml, do it now
If you already added it but the error persists, uninstall the app first then run i again.
More often than not I run into the same issue because I forgot <uses-permission android:name="android.permission.INTERNET" /> in my first installation.
The OS thought the app doesn't need Internet permission (which is dumb IMO) and would not check any permission update to the app (which is even dumber IMO).
The only way to tell the Android OS to check your updated permission requests is to uninstall the app first before installing again.
I think neither

*

*<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

*nor android:usesCleartextTraffic="true"
really matters here

A: I had to uninstall the app from the emulator and then everything started to work. I just needed the folowing permission on the AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

A: *

*Add ACCESS_NETWORK_STATE permission in manifest

*Reinstallation emulator

A: Just uninstall the app from the emulator then run again and it'll work. I had the same issue
To uninstall the app run your project when "the application had stopped" message appear click "app info" then uninstall.

A: I had the same issue in android emulator, even after adding
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

and
android:usesCleartextTraffic="true"

and reinstalling the app still had the issue on my emulator.

AVD Manager -> Right click -> Cold Boot now

solved my issue, looks like if we ran the app initially without adding internet permissions / clearTextTraffic we might need to cold boot as it store some cache.

A: If anyone still has this issue I encountered it when I used VPN and tried to connect to wifi while cellular was on. I was using Anyconnect VPN client.
Solution is to enable the allow bypass that will let you bind a socket to a specific network if this is what you are looking for.
AnyConnect only uses allowBypass if it's configured in its managed restrictions (by EMM), via this key: vpn_connection_allow_bypass.

A: I had to delete this
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

and keep this
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET" />

A: I am a little late to this but I encountered this problem and I found out that android:usesCleartextTraffic requires minimum API version of 23. Therefore, in the module gradle build file, switch the minimum version to 23 and it should work.


text:
Q: Azure Machine Learning, 1 web input with multiple outputs? Im trying to deploy a web app that takes 1 web input, then "Set Column In Dataset" a few times for each model , and then sends out a web output for each model.
Right now the way I have it setup is I have a few web inputs, then a model that runs for each, and then a web output for each.  It works for now, but it's a hassle because every time I want to add a new model to be predicted I have to add a bunch of stuff in both azure and my web application.  Just wondering if there is an easier way I'm missing.

A: I am not quite sure I understand the workflow you described. Can you provide more details on what are you trying to accomplish with your web app and your experiment? For example, what do you mean when you say "I have to add a bunch of stuff"?
Azure ML does support multiple web service inputs and outputs. Adding a new model to the experiment requires you to re-deploy your web service.


text:
Q: Change background color of View inside TabView having NavigationView and ScrollView in SwiftUI I want to build a TabView with 4 tabs having collection views in it. Below is my code of one tab named 'Gallery'.

 var body: some View {
        NavigationView {
            ScrollView {
                GridStack(rows: 3, columns: 2) { row, column, totalColumn in
                    CardView(card: self.cards[(row * totalColumn) + column])
                }.padding().background(Color.red)
            }
            .navigationBarTitle("Gallery")
        }
    }

When I give background color for ScrollView, scrolling is not working for NavigationView largeTitle. How can I achieve this, I want to give red color for full view's background? What if I need to achieve this same backgorund color for all tabs?

A: Here is possible approach (scroll view is not broken in such case)
NavigationView {
    GeometryReader { gp in
        ScrollView {
            ZStack(alignment: .top) {
                Rectangle().fill(Color.red) // << background

              // ... your content here, internal alignment might be needed

            }.frame(minHeight: gp.size.height)

        }
        .navigationBarTitle("Gallery")
    }
}


text:
Q: injected codes works for most webpages, but not youtube...? I wrote a simple extension to inject real-time clock on current web page. It works for most web pages, google.com, hulu.com, stackoverflow.com..., but not youtube.com, I don't know why.
Here is the manifest.json:
{
"name": "Insert Timestamp",
"version": "1.0",
"manifest_version": 2,
"description": "Insert Timestamp",
"icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

"permissions": ["tabs", "http://*/*", "https://*/*", "unlimitedStorage"],

"content_scripts" : [{
    "matches" : [ "http://*/*", "https://*/*"],
    "css" : ["show.css"],
    "js" : ["cbd.js", "ccc.js"]
}]
}

the cbd.js calls functions in ccc.js "onload" to get real-time and display the time in a div.
and show.css is also quite simple:
#showme {
    position: fixed;
    z-index: 999999999;
    top: 0;
    left:0;
}

I'm not familiar with web page stuff, just guessing: maybe youtube put something on top level which covers my clock?
----------------- java script codes added here ------------------
(1)cbd.js
window.onload = function() { startTime(); }

(2)ccc.js
var div = document.createElement("showme");
div.id = "showme";
document.body.appendChild(div);
  document.getElementById('showme').style.color = 'red';
  document.getElementById('showme').style.fontSize = '32pt';

function startTime()
{
    var today=new Date();
    var h=today.getHours();
    var m=today.getMinutes()
    var s=today.getSeconds();
    var w=today.getMilliseconds()%1000;

    h=checkTime(h);
    m=checkTime(m);
    s=checkTime(s);
    w=checkMS(w);

    document.getElementById('showme').innerHTML=h+":"+m+":"+s+":"+w;

    t=setTimeout('startTime()',1);
}

function checkTime(i)
{
    if (i<10)
    {i="0" + i;}
        return i;
}

function checkMS(i)
{
    if ((i>9)&&(i<100) )
        {i="0" + i;}
    else if(i<10)
        {i="00" + i;}
    else
        {}
    return i;
}


text:
Q: How to track down a "double free or corruption" error When I run my (C++) program it crashes with this error.

* glibc detected * ./load: double free or corruption (!prev):
  0x0000000000c6ed50 ***

How can I track down the error?
I tried using print (std::cout) statements, without success. Could gdb make this easier?

A: If you're using glibc, you can set the MALLOC_CHECK_ environment variable to 2, this will cause glibc to use an error tolerant version of malloc, which will cause your program to abort at the point where the double free is done.
You can set this from gdb by using the set environment MALLOC_CHECK_ 2 command before running your program; the program should abort, with the free() call visible in the backtrace.
see the man page for malloc() for more information

A: Are you using smart pointers such as Boost shared_ptr? If so, check if you are directly using the raw pointer anywhere by calling get(). I've found this to be quite a common problem.
For example, imagine a scenario where a raw pointer is passed (maybe as a callback handler, say) to your code. You might decide to assign this to a smart pointer in order to cope with reference counting etc. Big mistake: your code doesn't own this pointer unless you take a deep copy. When your code is done with the smart pointer it will destroy it and attempt to destroy the memory it points to since it thinks that no-one else needs it, but the calling code will then try to delete it and you'll get a double free problem.
Of course, that might not be your problem here. At it's simplest here's an example which shows how it can happen. The first delete is fine but the compiler senses that it's already deleted that memory and causes a problem. That's why assigning 0 to a pointer immediately after deletion is a good idea.
int main(int argc, char* argv[])
{
    char* ptr = new char[20];

    delete[] ptr;
    ptr = 0;  // Comment me out and watch me crash and burn.
    delete[] ptr;
}

Edit: changed delete to delete[], as ptr is an array of char.

A: There are at least two possible situations:

*

*you are deleting the same entity twice

*you are deleting something that wasn't allocated

For the first one I strongly suggest NULL-ing all deleted pointers.
You have three options:

*

*overload new and delete and track the allocations

*yes, use gdb -- then you'll get a backtrace from your crash, and that'll probably be very helpful

*as suggested -- use Valgrind -- it isn't easy to get into, but it will save you time thousandfold in the future...

A: You can use gdb, but I would first try Valgrind.  See the quick start guide.
Briefly, Valgrind instruments your program so it can detect several kinds of errors in using dynamically allocated memory, such as double frees and writes past the end of allocated blocks of memory (which can corrupt the heap). It detects and reports the errors  as soon as they occur, thus pointing you directly to the cause of the problem.

A: Three basic rules:

*

*Set pointer to NULL after free

*Check for NULL before freeing.

*Initialise pointer to NULL in the start.

Combination of these three works quite well.

A: You can use valgrind to debug it.
#include<stdio.h>
#include<stdlib.h>

int main()
{
 char *x = malloc(100);
 free(x);
 free(x);
 return 0;
}

[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
*** glibc detected *** ./t1: double free or corruption (top): 0x00000000058f7010 ***
======= Backtrace: =========
/lib64/libc.so.6[0x3a3127245f]
/lib64/libc.so.6(cfree+0x4b)[0x3a312728bb]
./t1[0x400500]
/lib64/libc.so.6(__libc_start_main+0xf4)[0x3a3121d994]
./t1[0x400429]
======= Memory map: ========
00400000-00401000 r-xp 00000000 68:02 30246184                           /home/sand/testbox/t1
00600000-00601000 rw-p 00000000 68:02 30246184                           /home/sand/testbox/t1
058f7000-05918000 rw-p 058f7000 00:00 0                                  [heap]
3a30e00000-3a30e1c000 r-xp 00000000 68:03 5308733                        /lib64/ld-2.5.so
3a3101b000-3a3101c000 r--p 0001b000 68:03 5308733                        /lib64/ld-2.5.so
3a3101c000-3a3101d000 rw-p 0001c000 68:03 5308733                        /lib64/ld-2.5.so
3a31200000-3a3134e000 r-xp 00000000 68:03 5310248                        /lib64/libc-2.5.so
3a3134e000-3a3154e000 ---p 0014e000 68:03 5310248                        /lib64/libc-2.5.so
3a3154e000-3a31552000 r--p 0014e000 68:03 5310248                        /lib64/libc-2.5.so
3a31552000-3a31553000 rw-p 00152000 68:03 5310248                        /lib64/libc-2.5.so
3a31553000-3a31558000 rw-p 3a31553000 00:00 0
3a41c00000-3a41c0d000 r-xp 00000000 68:03 5310264                        /lib64/libgcc_s-4.1.2-20080825.so.1
3a41c0d000-3a41e0d000 ---p 0000d000 68:03 5310264                        /lib64/libgcc_s-4.1.2-20080825.so.1
3a41e0d000-3a41e0e000 rw-p 0000d000 68:03 5310264                        /lib64/libgcc_s-4.1.2-20080825.so.1
2b1912300000-2b1912302000 rw-p 2b1912300000 00:00 0
2b191231c000-2b191231d000 rw-p 2b191231c000 00:00 0
7ffffe214000-7ffffe229000 rw-p 7ffffffe9000 00:00 0                      [stack]
7ffffe2b0000-7ffffe2b4000 r-xp 7ffffe2b0000 00:00 0                      [vdso]
ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0                  [vsyscall]
Aborted
[sand@PS-CNTOS-64-S11 testbox]$

[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck ./t1
==20859== Memcheck, a memory error detector
==20859== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20859== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20859== Command: ./t1
==20859==
==20859== Invalid free() / delete / delete[]
==20859==    at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859==    by 0x4004FF: main (t1.c:8)
==20859==  Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20859==    at 0x4A05A31: free (vg_replace_malloc.c:325)
==20859==    by 0x4004F6: main (t1.c:7)
==20859==
==20859==
==20859== HEAP SUMMARY:
==20859==     in use at exit: 0 bytes in 0 blocks
==20859==   total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20859==
==20859== All heap blocks were freed -- no leaks are possible
==20859==
==20859== For counts of detected and suppressed errors, rerun with: -v
==20859== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$

[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20899== Memcheck, a memory error detector
==20899== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20899== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20899== Command: ./t1
==20899==
==20899== Invalid free() / delete / delete[]
==20899==    at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899==    by 0x4004FF: main (t1.c:8)
==20899==  Address 0x4c26040 is 0 bytes inside a block of size 100 free'd
==20899==    at 0x4A05A31: free (vg_replace_malloc.c:325)
==20899==    by 0x4004F6: main (t1.c:7)
==20899==
==20899==
==20899== HEAP SUMMARY:
==20899==     in use at exit: 0 bytes in 0 blocks
==20899==   total heap usage: 1 allocs, 2 frees, 100 bytes allocated
==20899==
==20899== All heap blocks were freed -- no leaks are possible
==20899==
==20899== For counts of detected and suppressed errors, rerun with: -v
==20899== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$

One possible fix:
#include<stdio.h>
#include<stdlib.h>

int main()
{
 char *x = malloc(100);
 free(x);
 x=NULL;
 free(x);
 return 0;
}

[sand@PS-CNTOS-64-S11 testbox]$ vim t1.c
[sand@PS-CNTOS-64-S11 testbox]$ cc -g t1.c -o t1
[sand@PS-CNTOS-64-S11 testbox]$ ./t1
[sand@PS-CNTOS-64-S11 testbox]$

[sand@PS-CNTOS-64-S11 testbox]$ valgrind --tool=memcheck --leak-check=full ./t1
==20958== Memcheck, a memory error detector
==20958== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==20958== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==20958== Command: ./t1
==20958==
==20958==
==20958== HEAP SUMMARY:
==20958==     in use at exit: 0 bytes in 0 blocks
==20958==   total heap usage: 1 allocs, 1 frees, 100 bytes allocated
==20958==
==20958== All heap blocks were freed -- no leaks are possible
==20958==
==20958== For counts of detected and suppressed errors, rerun with: -v
==20958== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
[sand@PS-CNTOS-64-S11 testbox]$

Check out the blog on using Valgrind Link

A: With modern C++ compilers you can use sanitizers to track.
Sample example :
My program:
$cat d_free.cxx
#include<iostream>

using namespace std;

int main()

{
   int * i = new int();
   delete i;
   //i = NULL;
   delete i;
}

Compile with address sanitizers :
# g++-7.1 d_free.cxx -Wall -Werror -fsanitize=address -g

Execute :
# ./a.out
=================================================================
==4836==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
    #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
    #1 0x400b2c in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:11
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
    #3 0x400a08  (/media/sf_shared/jkr/cpp/d_free/a.out+0x400a08)

0x602000000010 is located 0 bytes inside of 4-byte region [0x602000000010,0x602000000014)
freed by thread T0 here:
    #0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
    #1 0x400b1b in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:9
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)

previously allocated by thread T0 here:
    #0 0x7f35b2d7a040 in operator new(unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:80
    #1 0x400ac9 in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:8
    #2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)

SUMMARY: AddressSanitizer: double-free /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140 in operator delete(void*, unsigned long)
==4836==ABORTING

To learn more about sanitizers you can check this or this or any modern c++ compilers (e.g. gcc, clang etc.) documentations.

A: In my case, I was linking my program against CUDA 10.0 while a dependency of my program was linked with CUDA 10.2 (cudart.10.2.so). The inconsistency caused "double free or corruption" for me.
You can use ldd <your program> to see if there are more than one version of CUDA libs in the dependencies.

A: I know this is a very old thread, but it is the top google search for this error, and none of the responses mention a common cause of the error.
Which is closing a file you've already closed.
If you're not paying attention and have two different functions close the same file, then the second one will generate this error.


text:
Q: Number of ways to write n as a sum of k numbers So I have this formula:
P(n, 1) = P(n, n) = 1

P(n + k, k) = P(n, 1) + P(n, 2) + ... + P(n, k)

But I do not understand it.
Did I write something wrong?
I do not understand why there is "n+k" in P(n + k, k)
Let's say that P is a function and I call P(6, 2). What does P(n + k, k) does? Will it transfrom to P(8, 2) or P(4 + 2, 2)...
I do not understand how it works, maybe if someone gives me an example, step by step...

A: The two formula lines are a mathematical definition, not a programming algorithm. And hopefully they provide enough information so that you can find out the value for any P(x,y).
As the first line effectively defines two different cases, I'd like to rewrite the formulas:
(A) P(n, 1) = 1

(B) P(n, n) = 1

(C) P(n + k, k) = P(n, 1) + P(n, 2) + ... + P(n, k)

So, if you want to apply them to P(6,2) then only (C) can match, as (A) only matches to things like P(6,1), and (B) to things like P(6,6).
The match of P(6,2) against P(n+k,k) means that k must be 2, and n+k must be 6, giving n=4.
Then the right-hand side of (C) expands to P(4,1) + P(4,2). Its first part matches against (A), and the second one against (C). So, the first part gives 1, and the second has to be expanded the same way as P(6,2). And so on...
If you were to implement a function computing P(x,y) values, the straightforward way would be to transform the definition formulas to a recursive computation.

A: Well, you have to apply formulas again and again:
   P(6, 2) = P(4 + 2, 2) = P(4, 1) + P(4, 2)

Now for P(4, 1) we have
   P(4, 1) = P(3 + 1, 1) = P(3, 1) = P(2 + 1, 1) = P(2, 1) = P(1 + 1, 1) = P(1, 1) = 1

With a help of induction we can prove that P(N, 1) = 1 when N >= 1
For P(4, 2) we have
   P(4, 2) = P(2 + 2, 2) = P(2, 2) + P(2, 1) = 1 + P(2, 1) =
           = 1 + P(1 + 1, 1) = 1 + P(1, 1) = 1 + 1 = 2

Finally
   P(6, 2) = P(4 + 2, 2) = P(4, 1) + P(4, 2) = 1 + 2 = 3

In general case (again induction) P(2 * N, 2) = N
Simplest C# implementation (doesn't work for some inputs like, say P(0, 1)):
private static Dictionary<Tuple<int, int>, int> s_Cached =
  new Dictionary<Tuple<int, int>, int>();

private static int P(int n, int k) {
  if (n == k)
    return 1;

  if (s_Cached.TryGetValue(new Tuple<int, int>(n, k), out var value))
    return value;

  int result = 0;

  for (int i = 1; i <= k; ++i)
    result += P(n - k, i);

  s_Cached.Add(new Tuple<int, int>(n, k), result);

  return result;
}

Test
Console.WriteLine(P(6, 2));


text:
Q: how to get transparent window in GNU Emacs on OSX? I'm on GNU Emacs in OSX Mavericks and I'm trying to make my background transparent but not the text.
There's an easy way to make the whole frame transparent:
(set-frame-parameter (selected-frame) 'alpha '(85 85))
(add-to-list 'default-frame-alist '(alpha 85 85))

But this makes the whole frame transparent/translucent, including the text. I want only the frame background to be transparent and the text to be a solid black. Someone on the Emacs Wiki said that such an implementation would have to be OS-specific. So, does anyone know how to do this for OSX?
With desired settings, Emacs would look like this:
.
Again, I want the window 100% transparent and the foreground text 100% opaque, and it should work in Emacs' full-screen mode.

A: The following are a few screen-shots and the different .emacs settings that were used.  I'm using Emacs Trunk built --with-ns on February 16, 2014, and the operating system is OSX Snow Leopard 10.6.8.

SETTING # 1:
(set-frame-parameter (selected-frame) 'alpha '(85 85))

(add-to-list 'default-frame-alist '(alpha 85 85))

(set-face-attribute 'default nil :background "black"
  :foreground "white" :font "Courier" :height 180)

SETTING # 2:
(set-frame-parameter (selected-frame) 'alpha '(85 85))

(add-to-list 'default-frame-alist '(alpha 85 85))

(set-face-attribute 'default nil :background "white"
  :foreground "black" :font "Courier" :height 180)

SETTING # 3:
(set-frame-parameter (selected-frame) 'alpha '(75 75))

(add-to-list 'default-frame-alist '(alpha 75 75))

(set-face-attribute 'default nil :background "white"
    :foreground "black" :font "Courier" :height 180)

SETTING # 4:
(set-frame-parameter (selected-frame) 'alpha '(0 0))

(add-to-list 'default-frame-alist '(alpha 0 0))

(set-face-attribute 'default nil :background "white"
    :foreground "black" :font "Courier" :height 180)

EDIT (February 24, 2014):  The following is a link to a related thread where the lead developer of Aquamacs (i.e., David Reitter) has suggested modifying nsterm.m as a potential solution:  http://comments.gmane.org/gmane.emacs.aquamacs.devel/836 -- "At a minimum, the changes would be to ns_clear_frame and ns_clear_frame_area.  Instead of filling the background with the background color, you could try * setting the alpha component of the NSColor object so that it is transparent * copying in the actual background of the window.  So, then you'd have the frame background transparent.  That doesn't take care of the frame UI elements, . . ."  [In other words, the potential solution would likely entail modifying the source code prior to building a custom version of Emacs.]


text:
Q: Display latest entry from different mysql table I have three tables products, events with same date of creation column 'creation'. But if any user add entry to any table, details should be displayed from that specific row on webpage.
Can you suggest me, how to do it?

A: SELECT *
FROM (SELECT col1, col2, date
      FROM table1
      ORDER BY date DESC
      LIMIT 1
      UNION
      SELECT col1, col2, date
      FROM table2
      ORDER BY date DESC
      LIMIT 1
      UNION
      SELECT col1, col2, date
      FROM table3
      ORDER BY date DESC
      LIMIT 1) u
ORDER BY date DESC
LIMIT 1


text:
Q: Relational database design with databases for status and types I am currently working with a database designed by someone else from my team and he uses a database design style I have not encountered before. I was wondering if the following design would be good practice since it seems kind of cumbersome to me.
There is a 'normal' database with user and business specific information. For the 'types' in this database, for example a user, there exists a table in two separate databases, namely status and types.
The status for a user is simply a name and a description (for example active or deleted).
The type for users is not really clear to me, but the table consists of a name, a description, a subset and a level field.
The cumbersome part would be the linking of these tables, since the they exist in different databases and the user table requires keys for both status and types (not enforceable via foreign keys).
Wouldn't it be better to have a simple boolean field to indicate whether the user is active and for types, if there will ever be any which is not likely, use inheritance?

A: such these users may be beginner, so you can decide if your user status checked in code, for example when you login if query have this: where status = 'active' or like this so in this case you don't need a table and user status is static values you can include in your source code, also you should consider the language for these status if your system support multi languages. the same with the type field.
but if you don't need to check these flags in your code so there is no problem to leave them in table, but it will be nice in this case to give the user ability to add types or status after that.

A: I think your question covers two different aspects:
1) data cohesion and integrity - referencing data from other tables which can or not be in the same database
2) normalization - do I need status and types in other tables or they can be incorporated in the same table?
1) If you are not working with huge data (at least tens of millions of records), I would recommend to replicate status and types tables in the "normal" database. This is particularly recommended, if data from there is rarely changed.
Doing this allows to apply referential constraints (FKs) and also have faster JOINs.
2) Although it adds some complexity (extra table, defining constraints etc.), having your data normalized may bring some important advantages:

*

*flexibility - if a status or type is added, it just mean a simple insert in a table

*smaller tables - users table stores only some ids for status and type, not strings or hard to guess values (e.g. 0 - inactive, 1 - active etc.)

*easier maintenance - a type name is changed? Just update a record in a table
Normalized structures usually speak for themselves if designed properly (PKs, FKs, check constraints etc.) and allow separation of concerns (maybe you implement a designer for user types in some point in the future)
Usually, database separation should be done based on the activity type:

*

*operational (lots of INSERTs, UPDATEs, DELETEs beside SELECTs)

*reporting (mainly SELECTs)

*ETL destination - heavy INSERTs, UPDATEs etc.


text:
Q: PHP str word count divide equal parts i have text file that have 100k word.php function str_word_count()  works and echo me 100k in text file.but i want divide 100k words into 4 equal parts.
$data=file_get_contents('100k.txt');
echo $count=str_word_count($data);

A: Use str_split() to split your string into parts. The second argument in str_split is the number of pieces you want to split the string into. The following will count the length of your string, then give you an array containing the string as four array items in the array $pieces.
$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque facilisis ultricies efficitur. Integer mattis tincidunt risus id interdum. Integer nulla tellus, imperdiet vitae dui et, sagittis tempus lorem. Maecenas aliquet volutpat purus, sed finibus turpis imperdiet sed. Aliquam erat velit, viverra in nisi vel, euismod porta metus. Vivamus id mi tellus. Fusce sodales dolor dignissim lorem vehicula malesuada. Fusce a tortor in massa viverra blandit. Mauris sit amet sem ligula. Nullam et ullamcorper mi. In porta semper purus a auctor. Cras eget ipsum ut sapien condimentum venenatis vitae ut sem.";

$length = strlen($text);
$pieces = str_split($text, ceil($length/4));

A: Without cutted words:
/**
 *  Splits a string with words in equal parts (PHP7)
 *
 *  @since    1.0 DP0
 *  @version  1.0 DP0
 *
 *  @param    string    words   String with words
 *  @param    int       parts   How many parts needed
 *
 *  @return   array             Parts as rec. Array
 */

function split_words_into_parts( string $words, int $parts ) {

      $words_array  = explode( ' ', $words );
      $words_cnt    = count( $words_array );
      $per_part   = max( round( $words_cnt / $parts ), 1 );

      $result     = [];

      /*---  Splitting full array  ---*/

      for( $i = 0; $i < $parts; $i++ )
          $result[] = array_slice( $words_array, $i * $per_part, $per_part );

      return $result;
}

/*---  Usage  ---*/

$v = 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.';

$result = split_words_into_parts( $v, 4 );

print_r( $result );


text:
Q: IIS web.config Issue I recently switched from LAMP on a dedicated server hosted on RackSpace to a Azure Webapp. I have a PHP application that was wrote in a way that doesn't always include the .php at the end of the redirects, and wants to hide the .php in the URL whenever possible.
Using a .htaccess to web.config convertor  I came up this, but I get an internal server error on ANY page i go to... .php or not. If I remove the web.config I can access the pages by forcing the .php in the url.
  <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
<rewrite>
    <rule name="hide php extension" stopProcessing="true">
        <match url="^(.*)/$" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
        </conditions>
        <action type="Rewrite" url="{R:1}.php" />
    </rule>
</rules>
</rewrite>
  </system.web>
</configuration>

Am I missing something? I would think that it would be easy, but clearly it is beyond my capabilities. I've played around with various rules posted here, but do not know enough about IIS yet to write my own rules.

A: You could try to add below rule in your web.config file:
 <rule name="Redirect .php extension" enabled="true" stopProcessing="false">
  <match url="^(.*).php$" ignoreCase="true" />
<conditions logicalGrouping="MatchAny">
  <add input="{URL}" pattern="(.*).php$" ignoreCase="false" />
</conditions>
  <action type="Redirect" url="{R:1}" redirectType="Permanent" />
</rule>

<rule name="hide .php extension" enabled="true" stopProcessing="true">
  <match url="^(.*)$" ignoreCase="true" />
<conditions>
  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  <add input="{REQUEST_FILENAME}.php" matchType="IsFile" />
</conditions>
  <action type="Rewrite" url="{R:0}.php" />
</rule>

Regards,
Jalpa


text:
Q: Setting UP Intellij to run apache spark with remote master I have a project setup with H2o. I am able to run the code with apache toree and I set the spark master as spark://xxxx.yyyy.zzzz:port.
It works fine and I can see the output in spark UI.
I am trying to run the same code as application in intellij with but I get error java.lang.ClassNotFoundException: org.apache.spark.h2o.utils.NodeDesc. but I see the application in Spark UI for a short amount of Time.
I tried running simple application with hello world and that worked as well as I am able to see the application in Spark UI,
import java.io.File

import hex.tree.gbm.GBM
import hex.tree.gbm.GBMModel.GBMParameters
import org.apache.spark.h2o.{StringHolder, H2OContext}
import org.apache.spark.{SparkFiles, SparkContext, SparkConf}
import water.fvec.H2OFrame

/**
  * Example of Sparkling Water based application.
  */
object SparklingWaterDroplet {

  def main(args: Array[String]) {

    // Create Spark Context
    val conf = configure("Sparkling Water Droplet")
    val sc = new SparkContext(conf)

    // Create H2O Context
    val h2oContext = H2OContext.getOrCreate(sc)
    import h2oContext.implicits._

    // Register file to be available on all nodes

    sc.addFile(this.getClass.getClassLoader.getResource("iris.csv").getPath)

    // Load data and parse it via h2o parser
    val irisTable = new H2OFrame(new File(SparkFiles.get("iris.csv")))

    // Build GBM model
    val gbmParams = new GBMParameters()
    gbmParams._train = irisTable
    gbmParams._response_column = 'class
    gbmParams._ntrees = 5

    val gbm = new GBM(gbmParams)
    val gbmModel = gbm.trainModel.get

    // Make prediction on train data
    val predict = gbmModel.score(irisTable)('predict)

    // Compute number of mispredictions with help of Spark API
    val trainRDD = h2oContext.asRDD[StringHolder](irisTable('class))
    val predictRDD = h2oContext.asRDD[StringHolder](predict)

    // Make sure that both RDDs has the same number of elements
    assert(trainRDD.count() == predictRDD.count)
    val numMispredictions = trainRDD.zip(predictRDD).filter( i => {
      val act = i._1
      val pred = i._2
      act.result != pred.result
    }).collect()

    println(
      s"""
         |Number of mispredictions: ${numMispredictions.length}
         |
         |Mispredictions:
         |
         |actual X predicted
         |------------------
         |${numMispredictions.map(i => i._1.result.get + " X " + i._2.result.get).mkString("\n")}
       """.stripMargin)

    // Shutdown application
    sc.stop()
  }

  def configure(appName:String = "Sparkling Water Demo"):SparkConf = {
    val conf = new SparkConf().setAppName(appName)
      .setMaster("spark://xxx.yyy.zz.aaaa:oooo")
    conf
  }
}

I also tried exporting jars as compile from the dependencies menu ,
is there anything I am missing from Intellij setup.?
It looks like the external libraries are not getting pushed to the master


text:
Q: Docker compose yml "volume" not working on Ubuntu OS I am running a simple Hello World world container with docker-compose.
There should be a mounted folder (with my files) at /root/sharedFolder but this folder is empty.
I am running Docker on Ubuntu OS (on top of my Windows server). And this works on a normal Ubuntu machine.
Any ideas?
docker-compose.yaml
version: '3'
services:
  web:
    build: .
    volumes:
    - ".:/root/sharedFolder"

Dockerfile:
#FROM - Image to start building on.
FROM ubuntu:14.04

#MAINTAINER - Identifies the maintainer of the dockerfile.
MAINTAINER ian.miell@gmail.com

#RUN - Runs a command in the container
RUN echo "Hello world" > /root/hello_world.txt

#CMD - Identifies the command that should be used by default when running the image as a container.
CMD ["sleep", "400"]

A: Instead of doing echo in RUN, do it in CMD or ENRTYPOINT. RUN happens during the image build phase where as CMD happens when your container is up and running with the volumes.

*

*RUN is done during image build step

*CMD specifies the command executed by default when you run a built
image.

You can also achieve the same with ENTRYPOINT
Google docker RUN vs CMD for more details.


text:
Q: How to reduce response time from Amazon S3? I have java method that gets last saved file from S3 bucket by getting list of all objects and sorting them by name (all files has timestamp in their name). The problem is that response time could be 13 seconds and up to 20, depends on how many objects in the bucket
I guess problem lies in call rout - client - cloudflare - loadbalancer - ingress controler - my service container  - ingress controler - loadbalancer - cloudflare - client, because when I call this method from localhost, response time is 1.5 ms in avarage
Is there a way to reduce response time?
Service method
public URL getLastSavedFile(Integer vehicleId) {
    try {
        S3ObjectSummary s3ObjectSummary = repository.downloadLastFile(String.valueOf(vehicleId));
        GeneratePresignedUrlRequest request = getPresignedUrl(s3ObjectSummary);
        log.info("Returned URL of last file from S3 storage, for vehicle - {}", vehicleId);
        return s3Client.generatePresignedUrl(request);
    } catch (IndexOutOfBoundsException e) {
        log.info("Failed to get last snapshot, the following - {} doesn't exist in storage", vehicleId);
        throw new RuntimeException(e);
    }
}

Repository
public S3ObjectSummary downloadLastFile(String vehicleId) {
    ObjectListing listing = s3client.listObjects( env.getProperty("INIT_S3_BUCKET"), vehicleId );
    List<S3ObjectSummary> objects = listing.getObjectSummaries();
    while (listing.isTruncated()) {
        listing = s3client.listNextBatchOfObjects (listing);
        objects.addAll (listing.getObjectSummaries());
    }
    objects.sort((o1, o2) -> o2.getKey().compareTo(o1.getKey()));
    return objects.get(0); //sorted list with most recent timestamp in the beginning
}

A: 1.5ms vs 15 seconds is A LOT :D
There are at least 2 approach to improve the response time of S3:

*

*Use Transfer Acceleration. Improves both uploads and downloads, uses edge locations to route your request trough AWS internal infrastructure.

*Use CloudFront. Improves just downloads, uses edge locations to cache your content.

A: FIXED!
It appers that all problems were due to the maven dependencies, I had old version 1.12.382 of aws-java-sdk and when I change it to version 1.12.415 of aws-java-sdk-s3 - it fixed the problem and now response time is 1-2 seconds


text:
Q: Different CRC32 checksum for the same file Basically, I have an application which imports a few DLLs and some Python libraries.
I did another application which calculates CRC32 for each of these files and I've added the list on my main application because I want to make it to check these files.
The problem is that sometimes the main application detects a DLL or a library modified even if it wasn't. It don't happens everytime and I am wondering why does that happens? What can determine the CRC32 checksum to differ? It's because my application loads these DLLs or is something external like viruses or anything else?
Here's the code for both main application and the application which does the CRC32 list:
#include "boost/crc.hpp"
#include "boost/filesystem/operations.hpp"
#include "boost/filesystem/path.hpp"
#include "boost/progress.hpp"
#include "boost/integer.hpp"

using namespace std;
namespace fs = boost::filesystem;

int CheckCRC32(LPCSTR szFileName, DWORD dwCRC32)
{
    if (!fs::exists(szFileName))
        return 1;

    DWORD dwResult = 0;
    boost::crc_32_type result;
    std::streamsize const buffer_size = 1024;
    ifstream file(szFileName, std::ios_base::binary);

    if (file)
    {
        do
        {
            char buffer[buffer_size];
            file.read(buffer, buffer_size);
            result.process_bytes(buffer, file.gcount());
        } while(file);
    }
    else
        return 1;

    dwResult = result.checksum();
    if (dwResult <= 0)
        return 1;

    if (dwResult != dwCRC32)
        return 2;

    return 0;
}

Also, if you have another solution for doing such things or if you have a solution for this method, please let me know.

A: I am not really trusting your 1024 bytes fixed buffer and the order of calls you chose. Either it is your intention to only use the first 1024 bytes of your files for the crc or this could already be the problem. On the other hand, if the files you crc are smaller than those 1024, it is up to the behavior of file.read() what happens.
Just to give you an option, here the code for a "low level" alternative. If the same crc values will be obtained with this version will depend on whether my initial crc value of 0 is "by the book" or if you need to use another start value.
#include <Windows.h>
#include <cstdint>
#include <string>
#include <vector>

static uint32_t crc32_tab[] = {
    0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
    0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
    0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
    0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
    0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
    0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
    0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
    0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
    0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
    0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
    0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
    0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
    0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
    0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
    0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
    0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
    0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
    0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
    0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
    0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
    0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
    0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
    0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
    0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
    0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
    0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
    0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
    0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
    0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
    0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
    0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
    0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
    0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
    0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
    0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
    0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
    0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
    0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
    0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
    0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
    0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
    0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
    0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
};

uint32_t
crc32(uint32_t crc, const void *buf, size_t size)
{
    const uint8_t *p = static_cast<const uint8_t*>(buf);

    crc = crc ^ ~0U;

    while (size--)
        crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);

    return crc ^ ~0U;
}

bool Crc32OfFile(const char * pathToFile, uint32_t &result)
{
    bool success = false;
    HANDLE hFile =
        ::CreateFileA
            ( pathToFile
            , GENERIC_READ
            , FILE_SHARE_READ
            , NULL
            , OPEN_EXISTING
            , FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN
            , NULL
            );
    if (INVALID_HANDLE_VALUE != hFile)
    {
        DWORD fileSize = ::GetFileSize(hFile, NULL);
        std::vector<uint8_t> buffer;
        buffer.resize(fileSize);
        DWORD bytesRead = 0UL;
        if (::ReadFile(hFile, &buffer[0], buffer.size(), &bytesRead, NULL))
        {
            if (bytesRead == fileSize)
            {
                result = crc32(0UL, &buffer[0], buffer.size());
                success = true;
            }
        }
        ::CloseHandle(hFile);
    }
    return success;
}