text:
Q: onClick() and AlertDialog onClick - Android Studio i am a new programmer using Android studio and I have the following in one of my activity's code:
@Override
protected void onCreate(Bundle savedInstanceState) { /* code */ }

@Override
public void onClick(View ButtonSelected)
{
   switch (ButtonSelected.getId())
   {
      case R.id.Button1:
      // code
      break;

      case R.id.Button2:
      // code
      break;

   }
}

public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

When I run the app, the app works normally. When it is needed to present the message box I get the error "Unfortunately, App has stopped"
When i go back to my code the .setPositiveButton and .setNegativeButton look like:
  .setPositiveButton("Yes", (arg0, arg1) -> {

                        // code for "Yes" case
                })

.setNegativeButton("No", (arg0, arg1) -> {
             // code for "No" case
})
I think is because there are more than one "onClick" functions.
I tried to avoid this but still did not managed to fix it.
Does anyone have a hint for this ?
Thank you :)

A: Change "this" in

new AlertDialog.Builder(this)

to "nameClass.this" (ex. MainActivity.this) and change the "id" in both

public void onClick(DialogInterface dialog, int id)

to "which"
public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

That's how I have it in my code, hope it works


text:
Q: What happens when database shut down before triggers executed? Assume I have table in PostgreSQL as follows:
CREATE TABLE A
(
  userid integer,
  productid integer,
  description citext,
  price numeric
)

and some triggers on it:
CREATE TRIGGER afterinsert
  AFTER INSERT
  ON A
  FOR EACH ROW
  EXECUTE PROCEDURE DoSomething1();

CREATE TRIGGER beforeinsert
  BEFORE INSERT
  ON A
  FOR EACH ROW
  EXECUTE PROCEDURE DoSomething2();

Now, if I do this:
Insert into A values (1,3,'some description',100.5)

What will happen is:

*

*beforeinsert run DoSomething2()

*the row is inserted to A

*afterinsert run DoSomething1()
My question is what happens if between 2 and 3 the database shuts down?
when it starts again... what will hapen? will it roll back both the inserted row and roll back beforeinsert trigger?
Basically I just don't understand what is considered the Atomic operation in this case. is it the Insert + triggers or just the row?

A: The triggers are part of the transaction, and it won't commit until they've finished running. If the database shuts down before the transaction commits, it'll be rolled back. The rollback affects all changes that were made in the transaction, including the changes made by the triggers.

A: If you do a soft shutdown (that is, tell the database to shutdown: pg_ctl -m fast), it will rollback all open transactions. This includes all changes made by any trigger so far.
If you kill the database (like a kill -9), the database has no chance to properly commit or rollback everything. Next time you start the database, it will run a recovery and rollback all the changes to the point of the last successful commit.
All triggers are part of the ongoing transactions, all changes are only committed once all AFTER triggers finish.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# dynamically change the value I am pretty new at C# and I had to make a really primitive neuron app.
It works pretty good, except some values that don't update dynamically.
The problem is that when I change some values in the numericUpDown I want the current function(selected in a comboBox) to recalculate and change the value in the richTextBox(the result box)
I am sure it's just an event thing, but I couldn't find it anywhere.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if(comboBox1.Text=="Suma")
    {
        decimal s = 0;
        decimal temp;
        for (int i = 0; i < numericUpDown1.Value; i++)
        {
            var currentNumUpDown =   this.panel1.Controls["numericUpDown" + (100 + i).ToString()] as NumericUpDown;
            var currentNumUpDown2 = this.panel1.Controls["numericUpDown" + (200 + i).ToString()] as NumericUpDown;
            temp = currentNumUpDown.Value * currentNumUpDown2.Value;
            s = s + temp;
        }
        richTextBox1.Text = s.ToString();
        Fin = s;
    }
    if (comboBox1.Text == "Produs")
    {
        decimal p = 1;
        decimal temp;
        for (int i = 0; i < numericUpDown1.Value; i++)
        {
            var currentNumUpDown = this.panel1.Controls["numericUpDown" + (100 + i).ToString()] as NumericUpDown;
            var currentNumUpDown2 = this.panel1.Controls["numericUpDown" + (200 + i).ToString()] as NumericUpDown;
            temp = currentNumUpDown.Value * currentNumUpDown2.Value;
            p = p * temp;
        }
        richTextBox1.Text = p.ToString();
        Fin = p;
    }
    if (comboBox1.Text == "Minim")
    {
        decimal minim = 2;
        decimal temp;
        for (int i = 0; i < numericUpDown1.Value; i++)
        {
            var currentNumUpDown = this.panel1.Controls["numericUpDown" + (100 + i).ToString()] as NumericUpDown;
            var currentNumUpDown2 = this.panel1.Controls["numericUpDown" + (200 + i).ToString()] as NumericUpDown;
            temp = currentNumUpDown.Value * currentNumUpDown2.Value;
            if (minim > temp)
                minim = temp;
        }
        richTextBox1.Text = minim.ToString();
        Fin = minim;
    }
    if (comboBox1.Text == "Maxim")
    {
        decimal maxim = -2;
        decimal temp;
        for (int i = 0; i < numericUpDown1.Value; i++)
        {
            var currentNumUpDown = this.panel1.Controls["numericUpDown" + (100 + i).ToString()] as NumericUpDown;
            var currentNumUpDown2 = this.panel1.Controls["numericUpDown" + (200 + i).ToString()] as NumericUpDown;
            temp = currentNumUpDown.Value * currentNumUpDown2.Value;
            if (maxim < temp)
                maxim = temp;
        }
        richTextBox1.Text = maxim.ToString();
        Fin = maxim;
    }
}

I can provide more code if you need it. Thank you in advance!

A: You also need an event for the NumericUpDown to recalculate the value.
try adding these events:
currentNumUpDown.ValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);
currentNumUpDown2.ValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);

Note that Object sender and EventArgs e will differ in the method, depending on which event called the method.

A: @FatTony
if(comboBox1.Text=="Suma")
        {
            decimal s = 0;
            decimal temp;
            for (int i = 0; i < numericUpDown1.Value; i++)
            {
                var currentNumUpDown = this.panel1.Controls["numericUpDown" + (100 + i).ToString()] as NumericUpDown;
                var currentNumUpDown2 = this.panel1.Controls["numericUpDown" + (200 + i).ToString()] as NumericUpDown;
                currentNumUpDown.ValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);
                currentNumUpDown2.ValueChanged += new EventHandler(comboBox1_SelectedIndexChanged);
                MessageBox.Show("executed");
                temp = currentNumUpDown.Value * currentNumUpDown2.Value;
                s = s + temp;
            }

A: void ValueChanged(object sender, EventArgs e)
    {
        string temp_id = ((NumericUpDown)sender).Name.Remove(0, 14);
        if(temp_id[0]=='0')
        {
            temp_id = temp_id.Remove(0, 1);
        }
        int id = Int32.Parse(temp_id);
        decimal v1, v2;
        var numericUpDown1 = this.panel1.Controls["numericUpDown" + (100+id).ToString()] as NumericUpDown;
        var numericUpDown2 = this.panel1.Controls["numericUpDown" + (200+id).ToString()] as NumericUpDown;
        var CurrentTextBox = this.panel1.Controls["Text" + (100+id).ToString()] as TextBox;
        if (numericUpDown1 != null && numericUpDown2 != null)
        {
            v1 = numericUpDown1.Value;
            v2 = numericUpDown2.Value;
            CurrentTextBox.Text = (v1 * v2).ToString();
        };

this is the custom event that creates the numericUpDown's taking the value form another numeriUpDown.


text:
Q: Flink SQL: Calculate number of new users in real time using login data I am using Flink-SQL 1.13. The target is to calculate number of new users in real-time.
Due to some constraints, I cannot directly use register events because the accounts created there like a platform pass. One account can login into multiple games and for each game, the user is new when it firstly enter that game. So I can only calculate this by checking whether this account has logined to this game before from the login log. The format of login log is like:
user_id  game_id  login_time
111        game1    2021-05-13 01:01:01
111        game3    2021-05-23 02:02:02

The question is the amount of login log increases significantly every day. Although I can save the log into HBase, one day it will still be too large...
Is there any other way to do this? Maybe I can put historical users into redis hyperloglog, but it seems Flink-SQL does not have a redis connector yet...Thanks for your help in advance...

A: INSERT INTO first_login_stream (user_id, first_login_time)
SELECT
  user_id,
  FIRST_VALUE(login_time) first_login_time
FROM login_log
GROUP BY user_id

Which goes back into your event system / kafka. Which you can read back in windows for some hourly stats (which you can save in HBase):
INSERT INTO hbase_stats
SELECT
  window_start,
  window_end,
  count(user_id) user_count
FROM TABLE(
  TUMBLE(
    TABLE first_login_stream,
    DESCRIPTOR(<kafka_ingestion_time>),
    INTERVAL '1' HOUR
  )
)
GROUP BY
  window_start,
  window_end

It has to be checkpointed/saved (otherwise you'll incur the full log processing on restart). The state size will only grow by the number or users and not logins (I think. You should validate that.).


text:
Q: Jquery - tell when the hash changes? I'm trying to make my site respond correctly to the back button.  I've saved that hash of what I want it to do, but I don't know the hook for jQuery to be able to tell when the hash changes.  It's not .ready(), because the page doesn't reload.  What do I use?
Edit for a bit of clarity:
I'm using an iframe, so I can't tell when someone clicks a link.  It's on the same subdomain, so i'm able to see it's filepath, and am saving it so you can bookmark.  Unfortunately by saving it as a hash, my back button now fails to reload, which fails to reload the iframe, so my back button is essentially broken.  If there was a way to tell when the URI changes, I could check it against the iframe address and change it if they don't match.
All I need is a way to check if the URI has changed.  Is there a .change() for the URI?  Something along those lines?

A: You can try History Event plugin.

A: After the document is ready, you examine the hash and alter the page appropriately.

I don't know the hook for jQuery to be able to tell when the hash changes

You can intercept your hash anchors' click events and respond appropriately as opposed to waiting for a "the hash has changed" event (which doesn't exist).
Some approaches create a "the hash has changed" event by inspecting window.location.hash on a timer.

A: Ben 'the cowboy' Alman wrote a cross platform plugin for hash changes
http://benalman.com/news/2010/07/jquery-hashchange-event-v13/
I dont know if your using it inside of the iframe or what, but if you were to use it outside the iframe it would be like
$(function(){
    $(window).hashchange(function(){
       //Insert event to be triggered on has change.
       changeIframeContent(window.location.hash);
    })
})

A: You should have a look at the solution of Ben Nadel which is in binding events to non-DOM objects.

A: There is'nt a buitin way to watch for hash changes, in firefox you could use watch method, but as far as I know it isnt default, so you can hack it writing something like (see below)
function setWatchHashChanges(functionObject)
{
    if(window.location.watch)
    {
        window.location.watch('hash', function(e){functionObject(e);return e;});
    } else {
        if(!setWatchHasnChanges.hash)
        {
            setWatchHasnChanges.hash = window.locaton.hash;
        } else {
            setInterval(function(){
            if(setWatchHasnChanges.hash!== window.locaton.hash)
            {
                setWatchHasnChanges.hash = window.locaton.hash;
                functionObject(setWatchHasnChanges.hash);
            }
        }, 100);
    }
}


text:
Q: localhost doesn't work after upgrade to Mountain Lion I just upgraded to Mountain Lion from Lion and everything is just like I had on Lion, except for localhost. I start apache from terminal and it starts fine. however, I can't get to localhost, it gives me the error "can't connect to server localhost".
I have checked my httpd.conf file and it is just like before when it used to work. The only difference after upgrade was the removal of username.conf from users folder in apache2 directory, which I recreated.
apache error log file doesn't show anything either. in fact, there is NO any log file in there.
Has anyone got a solution for that?


text:
Q: HTML5 web app, define routes via JSON, PHP or dynamically? I'm working on an HTML5 web app (with no specific MVC framework). I'm unsure how to define all possible routings.
Currently, I do it on the fly once any URL gets hit:
If a user calls domain.com/test the app will create a new Page('test'). The Page constructor will then get a handlebars template, create the view ect ect. This is done once (first visit of /test). On every subsequent visit, the already available view is inserted into the DOM.
This is obviously flawed, as visits to domain.com/thispagedoesntexist or any other URL that isn't available (as in, there is no handlebars template) will still create a Page object.
To fix this, I need predefined routings, correct? This means I need to define which pages, routes and templates are available in the first place (all others get a 404 then). Is there a right way to do that?
The only way that comes to my mind is to create a JSON file, JS object or PHP array with all the routes defined:
var routes = [
    {
        title: 'Home',
        slug: '/home',
        template: 'pages/home.hbs'
    },
    {
        title: 'Imprint',
        slug: '/imprint',
        template: 'pages/imprint.hbs'
    },
    {
        title: 'About us',
        slug: '/about',
        template: 'pages/about.hbs'
    }
];

and then match the current visited URL. If it isn't in this array, I'll return the 404 page.
Is this the way to do it? I'm not sure if there is THE right way and I'm sorry if I'm asking for best practises right now.
Let's ask it this way: what's the generally recommended way to define routes in an single-page web app?
If the way I posted above is actually the correct way to do it, is there a security risk of using it in a JSON or JS file, or should I rather do it in PHP?

A: It's quite a big question and it brings another one : will you have permission for each page and how will you manage them ?
Then, as far as you build a single page app, php routes can't be used.
At last, I would say that there's a lot of solutions available like page.js or crossroads you could use. Or do you need to do it yourself?


text:
Q: how secure is dreamweaver login? When we use dreamweaver to create an auto-generated Login Logout - How secure it is?
while doing this dreamweaver creates 3 folders:-
_mmServerScripts
_notes
Connections

and adds this on the login.php page:-
<?php require_once('../Connections/da.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
  session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['username'])) {
  $loginUsername=$_POST['username'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "../index.php";
  $MM_redirectLoginFailed = "index.php";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_da, $da);

  $LoginRS__query=sprintf("SELECT user_id, user_password FROM users WHERE user_id=%s AND user_password=%s",
    GetSQLValueString($loginUsername, "int"), GetSQLValueString($password, "text"));

  $LoginRS = mysql_query($LoginRS__query, $da) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {
     $loginStrGroup = "";

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;

    if (isset($_SESSION['PrevUrl']) && false) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form name="login" action="<?php echo $loginFormAction; ?>" method="POST" target="_self">
<input name="username" type="text" />
<input name="password" type="password" />
<input name="login_button" type="submit" />
</form>
</body>
</html>

Also it uses the mysql_pconnect for mysql connection:-
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_da = "localhost";
$database_da = "database";
$username_da = "root";
$password_da = "password";
$dacreint = mysql_connect($hostname_da, $username_da, $password_da) or trigger_error(mysql_error(),E_USER_ERROR);
?>

Is it 100% efficient and secure? And if not can we do some modifications to it to make it as secure as possible... Because this really makes things fast.

A:
Edit: The accepted answer to the dupe of this question (by the same author? Why?) points out two vulnerabilities that I missed: PHP_SELF is vulnerable to XSS, and falling back to mysql_escape_string() shouldn't be necessary (although that is not a real world concern either way.) rather than steal the points from MrCode, I encourage everyone to closevote this, and upvote MrCode's better answer :)

It's not very beautiful code, but security- and efficiency-wise, it looks pretty okay. It takes into consideration that magic quotes are phased out in PHP 6, it seems to escape all incoming form data properly, and tests for the presence of variables before accessing them.
The only thing that looks like it could cause problems is the superfluous line break here:
<?php require_once('../Connections/da.php'); ?>   <---- here
<?php

that will mess with the header redirect in certain situations. I would get rid of it and just do
<?php require_once('../Connections/da.php');
      if (!function_exists("GetSQLValueString")) {

also, instead of
  .... or die(mysql_error());

one could use
  ....  or trigger_error(mysql_error(), E_USER_ERROR);

to prevent SQL error messages from being shown in production environments.

A: This is maybe not such a great idea:
mysql_query($LoginRS__query, $da) or die(mysql_error());

This reveals the mysql error explanation to the client, possibly revealing details of the DB schema of your user table.


text:
Q: using multiple mapbox wmts baselayers with dififerent labels in QGIS composer I have created two basemap layers in mapbox.

*

*https://api.mapbox.com/styles/v1/akrystos/cjr1epzf905a32sqhkwvjl5i7.html?fresh=true&title=true&access_token=pk.eyJ1IjoiYWtyeXN0b3MiLCJhIjoiY2o0YWI5Ynh0MTJleTMzbGNiMmNycXJtMyJ9.usNtifL5jfkUdC0NgNvChQ#5.0/0.400000/37.850000/0

*https://api.mapbox.com/styles/v1/akrystos/cjr1f15ar91b72rpcgrgtzhb9.html?fresh=true&title=true&access_token=pk.eyJ1IjoiYWtyeXN0b3MiLCJhIjoiY2o0YWI5Ynh0MTJleTMzbGNiMmNycXJtMyJ9.usNtifL5jfkUdC0NgNvChQ#5.0/0.400000/37.850000/0
I am using basemap 1 in a main map in group 1 with my data layer.
I am using basemap 2 in an inset map in group 2.
The two maps appear in the composer correctly and are refreshed/locked. But, once I export the map to pdf, the labels in both maps revert to whatever is in the dataframe view of arcgis.
Any thoughts?
As a workaround, I exported the inset as an image and added it to the composer as a static image.
QGIS version 2.18.27
windows 10 pro
Amy
Please see the images of the data view, composer, and exported pdf below.
The composer and data view of the two maps

The composer and exported PDF of the two maps


text:
Q: Searching in Java collection. Why it's so hard? Is there a reasonable explanation, why searching an element in Java collection is so hard?
For example, let's say I have:
ArrayList<People> listPeople = new ArrayList<People>();

public class People
{
   public String name;
   public String age;
   //some other code here
}

You got the idea ... Now, if I want to get from list a Person with given name, let's say 'Anthares' I have to do so much work: Create a new Person with name 'Anthares', probably initiate it with some other data, predefine my equals method for Person class, then call listPeople.IndexOf(tempPerson) and finally get the returned int and make listPeople[idx]
Why is all this pain. For example, in C# I can make a linq expression, pass it to the proper method of my collection and that's it. One simple line of code.

A: No you don't - you can do:
Person found = null;
for (Person person : listPeople)
{
    if ("Anthares".equals(person.name))
    {
        found = person;
        break;
    }
}
// Check for found == null etc

Yes, it's still more work than LINQ, but that's basically because C# has closures in the form of lambda expressions. You could implement something similar in Java if you were willing to write:
Person person = FakeLinq.findFirst(listPeople, new Predicate<Person>() {
    @Override boolean matches(Person person) {
        return person.name.equals("Anthares");
    }
});

Most of the conciseness of the C# solution is just allowing you to express that predicate very simply.
Java 7 will (hopefully!) have something reasonably similar to lambda expressions, at which point this becomes feasible in Java too.

A: Look at the Apache Commons collection api, specifically CollectionUtils.find

A: for(Person p : listPeople) {
  if(p.name.equals("Anthares")) {
    found = p;
    break;
  }
}

You'll likely be able to do it pretty much like in C# with jdk7.

A: In my humble opinion, they made one silly mistake in the Java collections classes that complicates the problem. When you do a Collection.indexOf(want), they search the collection saying, basically "if (want.equals(collectionMember))" rather than "if (collectionMember.equals(want))".
I think the latter would have been better, because it would have enabled you to simply write a "MyObject.equals(String)" function or "MyObject.equals(Integer)", i.e. compare your custom object to a general object. Then you could implement it as, say ...
public boolean equals(String wantname)
{
  return this.name.equals(wantname);
}

But because it's actually implemented as "if (want.equals(collectionMember))", of course the Java String class doesn't have an "equals(MyObject)" function, so you can't just give it a string to search for. Instead, you have to create a dummy object to hold the value you want to find.
Yeah, as others posters have indicated, it's not a big deal to write a quick function to search a collection sequentially. But what if we're talking about a collection where a sequential search is not practical or efficient, like a HashMap or tree structure?

A: With lambdaj you can achieve that result as easily as it follows:
select(listPeople, having(on(Person.class).getName(), equalTo("Anthares"))

A: If you want to search, you should use HashMap/HashTable and hash on a person's name.
If you implement linq in Java, you won't need to :)

A: You could just use an iterator and then compare the name field to the name you are searching for (all of which just involves using the Java API)
Also, a HashMap would probably be a much better data structure to use seeing as how you are using name as a "key" in this example.
The problem isn't with java collections, its with your choice of data structure/implementation.


text:
Q: Rails select in scope with virtual attribute returns an empty ActiveRecord Relation In a Rails 4.1.2 app with MySQL I'm doing the following:
scope :popular, -> {
  select("images.*, SUM(likes_count + comments_count + reposts_count) as score").
  where("DATE(created_at) > DATE(?)", 4.weeks.ago).
  order('score DESC')
}

to get a recent set of "popular" images. The problem is that if there are no images that match this query, I get an ActiveRecord::Relation with all nil values, e.g...
#<ActiveRecord::Relation [#<Image id: nil, user_id: nil, image_uid: nil, image_name: nil>]>
This is causing problems as the collection is not empty. How would I get that scope to return 'nil' if no results, or just reject if the object is empty or something?
UPDATE
Image.popular.select {|i| i.id.present? }

kinda solves the problem, but to me this seems more like a workaround than a solution...

A: You could make sure you're not returning anything with a nil value for id. Perhaps something like:
scope :popular, -> {
  select("images.*, SUM(likes_count + comments_count + reposts_count) as score").
  where("DATE(created_at) > DATE(?) AND id IS NOT NULL", 4.weeks.ago).
  order('score DESC')
}

EDIT
An alternative approach would be to simplify your query by caching the score attribute on the model. Generate a migration and add your attribute to your model. Then, use a before_save callback:
before_save :cache_score

def cache_score
  self.score = likes_count + comments_count + reposts_count
end

Then you could make your query simpler:
scope :popular, -> { where("created_at > ?", 4.weeks.ago).order('score DESC') }


text:
Q: Python list comprehension: Skip elements that raise exception I want to apply a function in a list comprehension that does not "work" for certain values.
A simple example would be [1/x for x in [-2, -1, 0, 1, 2]].
I would like to write something that skips the 0 and returns the following list: [-0.5, -1.0, 1.0, 0.5].
My best shot so far was wrapping the division in a try statement:
def try_div(x):
    try:
        return 1/x
    except ZeroDivisionError:
        pass

result_with_none = [try_div(x) for x in [-2, -1, 0, 1, 2]]
result = [x for x in result_with_none if x is not None]

This seems a bit inconvenient. Can I rewrite try_div in a way that makes the list comprehension skip the 0 element?
Remark: In this simple example, I could of course write [try_div for x in [-2, -1, 0, 1, 2] if x !=  0]. This is not practicable in my actual use case, because it is not easy to check a priori which values will raise an exception.
Remark 2: In contrast to this question, I am fine with explicitly handling exceptions in a function (like try_div). My question is mostly about how I could combine the last two steps (result_with_none = ... and result = ...) into one.

A: I think your first solution is clear, and that's the most important thing in python. Alternatively, how about a generator instead of a comprehension?
def try_div_itr(itr):
    for elem in itr:
        try:
             yield 1 / elem
        except ZeroDivisionError:
             pass

result = list(try_div_itr([-2, -1, 0, 1, 2]))

You could even generalise this
def try_itr(func, itr, *exceptions, **kwargs):
    for elem in itr:
        try:
            yield func(elem, **kwargs)
        except exceptions:
            pass

x = [random.choice([0, 1]) for _ in range(100_000)]

%timeit [i for i in (try_div(i) for i in x) if i is not None]
42.6 ms ± 109 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [i for i in [try_div(i) for i in x] if i is not None]
36.3 ms ± 154 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit list(try_div_itr(x))
25.3 ms ± 85.1 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit list(try_itr(lambda i: 1/i, x, ZeroDivisionError))
34.7 ms ± 113 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# but expect generic method to be slower anyway

%timeit list(try_itr((1).__truediv__, x, ZeroDivisionError))
28.7 ms ± 118 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# remove lambda abstraction for speed


text:
Q: The term 'nodemon' is not recognized nodemon : The term 'nodemon' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of
the name, or if a path was included, verify that the path is correct and try again.
just trying to install nodemon globally but it is not recognizing.....
( node install nodemon-g )in terminal.enter image description here

A: Edit:
If the below steps do not work for you, check this answer as nodemon might not be added to the PATH after installation.

Nodemon is a Node Package that is managed by the Node Package Manager (NPM).
To install Node Packages, you need to use the following command,
npm i package-name    // This will install the package locally as a dependency
npm i -D package-name // This will install the package locally as a dev dependency
npm i -g package-name // This will install the package globally

And so, to install nodemon globally, you would do,
npm i -g nodemon      // For Windows or if you installed NodeJS using NVM on linux
sudo npm i -g nodemon // If you installed NodeJS from from apt or other linux package manager.

node install whatever is not a command and obviously won't work.


text:
Q: Fundamental difference between microcontroller and PLC I am a teaching assistant for a sophomore mechanical engineering laboratory course. One of our lab modules is focused on PLCs, and another uses Arduino micro controllers. One of my students asked why they are different and I found myself without a good answer.
They both have input and output pins, perform logical operations, and are programmed via regular computers. They can be used to control the same equipment, read the same sensors, and make the same logical decisions. The differences in programming languages and the fact that they look and feel very different seems superficial. Is there a fundamental difference between the two, or is a PLC just a micro-controller designed to work in an industrial environment? How can I explain this difference to a sophomore college student with no background in electronics?
A good answer will either answer my question or offer a useful frame challenge; I may be asking the wrong question entirely.

A: I would describe the difference between PLC and microcontroller as follows.
Yes, a PLC is a microcontroller "ruggedized and adapted for the control of manufacturing processes".
The difference is that a PLC usually has a user-friendly wrapper already built-in, which provides easy and  reliable access to various IO functions, ADCs and DACs, timers, alarms, etc. The programming interface is tailored to industrial control functions, and is not unnecessary overflexible as BASIC or C.
If I try to provide a smooth one-line formulation, PLC are microcontrollers with pre-compiled interface to standard I/O functions and control loops.

A: A PLC allows time to be saved with a higher level programming such as Relay Ladder Logic (RLL) or Stage programming.
If Engineering NRE time is billed at a $150 rate it is easy to see why a $100 PLC is chosen in a complex network over a $1 PIC uC or even a $25 Uno.
The result is reduced software development, no need to isolate EMI issues with shields,  free tools for Windows click changes and compile code and interoperability.
Saved time and improved reliability in harsh environments with proven specs.  The differences are significant to the experienced and unknown to the naive.
Any newbie who thinks they can do the same with any Arduino, either hasn't done it before or has a lot to learn (or both).  i.e. create an industrial SCADA with many PLC's and verified to every environmental stress in the spec. while conforming to every functional spec and demonstrate fault detection, correction and tolerance and have ease of maintenance.

A: A PLC has a specific set of functions that are designed for simple to medium complexity machine control and they do that well, are rugged, and are Lego like and as such need minimal development effort.
A micro is a level below that. It is a basic building block on which you can develop extremely complex control systems which include higher order data analysis and manipulation. However, that comes at a cost of development and portability.
Most modern PLCs do indeed have Micro inside them, some even have a whole embedded PC in there, with a wrapper of software that provides the expected functionality. As the technology has developed the functionality of PLCs has also advanced so the edges have become more blurred over time.

If you want a house, you can order one and it will arrive on the back of a truck or two and a crane will stick it on your LOT and you are good to go.
However, if you want a house with two and a half baths, a cathedral ceiling, and a long list of other fine details, you are going to need the truck to deliver lumber, bricks and mortar etc and have someone built it exactly the way you need it.
The same goes for PLCs vs Micros.
Further, if you want to go into the portable house building business, you general don't start out by buying someone else's prefabs.
The trick is to know when to use which.

A: Historically, the difference is significant. PLCs could be much dumber than microcontrollers, in principle they didn't necessarily have to have memory (although I reckon most of them had), or be Turing complete. They only had to have enough configurable logic gates to replace a bunch of relays.
But that also means that PLCs were faster than microcontrollers, for what that's worth, and also more reliable. Simplicity can have its own value. PLCs also have a user interface to set them up, microcontrollers don't.
Today, the differences are smaller and fewer. They're largely due to the history of the tech, and to the differences in usage. A modern PLC can have a microcontroller for a brain.
Relays/contactors comprise the outputs of a typical PLC, while the outputs of a microcontroller is a bunch of CMOS gates. This is a significant practical difference, as these outputs have very different electrical characteristics.
So in the sense of being able to turn outputs on and off based on inputs, there is no fundamental difference between a microcontroller connected to a user interface and a bunch of relays, and a PLC.
On the other hand, that's a bit like saying that there is no fundamental difference between a railway train and a motorcycle: After all, both have rotating wheels that let them transport stuff along the surface of the earth, they both have an engine, a driver, and they both consume fuel.
Whether or not the differences between them are fundamental depends very much on your definition of the word fundamental.

A: To me, your "superficial differences" are in fact the fundamental differences between a microcontroller and a PLC.
A PLC is a complete, ready to use, appliance.  It comes in a nice package, ready to be plugged into AC power and with suitable interfaces and easy connections to sense and control real-world devices.  It will have a fairly simple application-specific programming environment - typically "ladder logic".
A microcontroller is a programmable integrated circuit.  The user must build or provide a power supply and the necessary interfaces to real-world devices, and write a program using a general-purpose programming language like C.  The progammer will have to become inimately familiar with the internal workings of the microcontroller to write the program.  A microcontroller could be used as the "brains" of a PLC.


text:
Q: How to convert 32MB of PNG file to 200Kbs without losing its colors I have couple of images that are of 32MBs of size and I want to change their size from 32MBs to 100Kbs or any KBs of size without affecting its colours.
The commands I am trying are:
muhammad@muhammad-mohsin:~/scans$ find . -iname '*.png' -exec mogrify -format jpg "*.png" {} +

muhammad@muhammad-mohsin:~/$ find . -type f -iname \*.png -delete

muhammad@muhammad-mohsin:~/$ find . -iname '*.jpg' -exec mogrify -define jpeg:extent=300kb -strip -quality 90 -scale 90% *.jpg {} +

Here, first I convert a PNG to JPG that reduce its size from 32Mbs to 5.8Mbs and everything stays same but when I use 3rd command, it removes background color in image and making it grayscale sort of blurry.
However, the text is still readable but colors and background logo does not.
How I can achieve this with convert, mogrify or any other tool? I tried every possible thing so far.

A: It's because of how JPEG compression works. It attempts to round adjoining pixels that are similar to eachother to similar values. This causes loss of details, and blockyness.
This becomes more noticeable as you increase the compression level, which is exactly what you're doing. In addition you're doing it in two steps:

*

*Lossless (PNG) to lossy (JPEG) compression.

*Lossy to lossy compression.

You will probably get a better result by going lossless to lossy at final quality, thus only applying lossy compression once, e.g. using jpeg:extent=300kb -strip -quality 90 -scale 90% in the first conversion.
Furthermore, you say nothing about the size of the image and level of detail. It may not be feasible to get it down to 300kB and retain the desired quality.
To get rid of background blotches, you can try to apply thresholds to your document in some image editing software, forcing anything less than a certain shade of gray to be white, for instance.
However, no matter what you do, compressing from a 30MB lossless format to a 300kB lossy format will lead to visibly reduced quality.

A:
I am trying find . -iname '*.png' -exec convert -resize 60% -quality 60 "*.jpg" {} + but that does not work.

Ref. https://superuser.com/questions/71028/batch-converting-png-to-jpg-in-linux
$ ls -1 *.png | xargs -n 1 bash -c 'convert -quality 60 "$0" "${0%.*}.jpg"'

Converts my example 31MB.png to 1.4MB.jpg . ... You may have to repeat with e.g. $ ls -1 *.PNG | ... etc.
Ref. comment by @steeldriver : "slightly better is xargs -d '\n' -n 1 "


text:
Q: Using output from one ruby script in another I have written a ruby file that already does a series of work and prints out a ton of information, one sting per line (like "aa.bb:zz//"). Am I able to use that output via another script? I.E I want my next script to do the same exact thing with each line. To be more descriptive: Instead of
   $newscript.rb FIRSTLINE

I want the script to do it locally within itself.
Thanks!

A: One way to split up your code is to use two files and require 'first.rb' within the second. That way you have access to the methods within. Simply execute those new methods and walla you have the output to use.
This first script will print it's status.
#!/usr/bin/env ruby -w
# first.rb
# Author: Andy Bettisworth
# Description: Declare first script status

class FirstScript
  def status
    counter = 1
    puts "I'm number #{counter}"
    counter
  end
end

if __FILE__ == $0
  script = FirstScript.new
  script.status
  #=> I'm number 1
end

This second script will print both the first and second status.
#!/usr/bin/env ruby -w
# second.rb
# Author: Andy Bettisworth
# Description: Chime in after first

require_relative 'first.rb'

class SecondScript
  def status
    first    = FirstScript.new
    counter  = first.status
    counter += 1
    puts "I'm number #{counter}"
    return counter
  end
end

if __FILE__ == $0
  script = SecondScript.new
  script.status
  #=> I'm number 1
  #=> I'm number 2
end


text:
Q: Handling async errors in react redux application Sometime back Dan tweeted
"I cringe when I see
`.then(() => dispatch(...)).catch(...)`

in React projects. If a component throws during dispatch, you'll get into catch."
And says the solution is so simple. Just don't chain catch() after then() that renders UI. Instead pass error handler as second arg to then().
Can someone explain why this is the case.
In my case I am making an ajax call, so I assume I will get inside then for anything that is 200 as a server response and inside catch for anything that is not 200, i.e. error from server. Am I missing something here?

A: So what Dan means is that in a Async request, you would expect the success call to result in .then() being called, and since you are dispatching an action in .then() which in turn will update the redux store and thus the UI, so if there is any error in the UI update process, .catch() will also be called and whereas you would expect it to only be called when the server returns an error
the solution is to handle it like
.then(
function (){
    //handle success
    dispatch({...})
},
function () {
    //handle reject() and Error for Async request

})


text:
Q: Using an existing Photoshop Design file in Eclipse ADT Very new to UI development on Android apart from using the default buttons and so on from Eclipse ADT. I have a designer creating designs for different activities in Photoshop. How exactly can I take those .PSD files and use them in Eclipse to make this template/design fully functional in a Android app? So basically how can I take a PSD file and implement it onto an activity and add events handlers and so on to different layers/elements of the design file?
Like I said, I'm very new to this sort of UI development so I may not be on the right direction on how this process works.
Thanks

A: you can not implement psd file into android layout file.
You have to take different images from psd from your designer and you can set them according to the design.
for example if in psd background is some picture, you should use that picture file as background in your root element.
you should ask your designer for separate images from psd file....
Hope this helps :)


text:
Q: Socket.io emits message to all clients except the one that initially emitted the original message I have two or more clients connected to the Socket.io room, client #1 emits message like so:
export function appendChild({ item }){
  socket.emit(APPEND_CHILD, { item })
  return {
    type: APPEND_CHILD,
  }
}

this successfully sent message to the server which looks like this:
socket.on('APPEND_CHILD', async ({ item }) => {
  ...
  socket.in(socket.handshake.query.room).emit('APPEND_CHILD_AFTER_EFFECT', { payload: { log, parentLog }, socketId: socket.id })
})

Please note that to trigger this, I use one message type, and to ping all clients for the update, I use different message, which when sent, should be received by all clients and they shall all update their state.
Clients listen for incoming messages like this:
socket.on('APPEND_CHILD_AFTER_EFFECT', ({ payload, socketId }) => {
        console.log('test !')
        ...
      })

All clients except the active (the one that sent initial emit) received message.
Why didn't main client receive message and how to make it so?

A: as @guico33 from Discord have noticed I've used socket object rather than io when emitting to all clients.
io.on('connect', socket => {
    socket.on('event', message => {
        socket.in(room).emit(...)
    })
})

It should look like so:
  io.in(socket.handshake.query.room).emit(message, data)

rather than:
  socket.in(socket.handshake.query.room).emit(message, data)

Instead of socket.in(room).emit(...), I should've used io.in(room).emit(...) to send the response to everyone including the emitter.


text:
Q: How can a drag a tab into a new window with Java Swing? Is there a way that I can have a tabbed application, where if i drag a tab off the window, it opens that panel in a new frame?

A: Yes it is possible but you will have to post a bit of source code, to see what you have done so far. I found this link that maybe is interesting to you:
http://java-swing-tips.blogspot.com/2008/04/drag-and-drop-tabs-in-jtabbedpane.html
It explain how to drag and drop tabs, maybe you can apply the same principle to your idea.
Also in this forum there is a similar question, maybe you wanna have a look:
How to implement draggable tab using Java Swing?


text:
Q: Retrieving args from running a script via sagemaker processing: unrecognized arguments I am testing a job. For that, I run the script via notebook using the following code.
I want to be able to retrieve the value of the arg
"dataset" via "argparse". I don't understand what I am doing wrong here:
The notebook that runs the job:
from sagemaker.processing import Processor, ProcessingInput, ProcessingOutput
from sagemaker.network import NetworkConfig

netconfig = NetworkConfig(XXX)
dataset= 'A'
processor = Processor(image_uri='XXX',
                     role='XXX',
                     instance_count=1,
                     instance_type="XXX",
                     network_config=netconfig)

processor.run(inputs=[ProcessingInput(
                        source='s3://input-bucket/settings_dataset_A.json',
                        destination='/opt/ml/processing/input')],
                outputs=[ProcessingOutput(
                        source='/opt/ml/processing/output',
                        destination='s3://output-bucket')],
                arguments=["--verbose", "--dataset", dataset],
                wait=True,
                logs=True)

and the code in the script:
    parser = argparse.ArgumentParser()
    parser.add_argument('--verbose', help="verbose",action="store_true")
    parser.add_argument("--dataset", type=str, required =False)
    args = parser.parse_args()
    print('Arguments:', sys.argv)
    print(args.dataset)

It gives an error: "unrecognized argument" but it is able to print the correct value ! And then it just stops running the rest of the code.
Do you see anything wrong with the code above ? Thanks a lot


text:
Q: Understand Python swapping: why is a, b = b, a not always equivalent to b, a = a, b? As we all know, the pythonic way to swap the values of two items a and b is
a, b = b, a

and it should be equivalent to
b, a = a, b

However, today when I was working on some code, I accidentally found that the following two swaps give different results:
nums = [1, 2, 4, 3]
i = 2
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
print(nums)
# [1, 2, 4, 3]

nums = [1, 2, 4, 3]
i = 2
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
print(nums)
# [1, 2, 3, 4]

This is mind-boggling to me. Can someone explain to me what happened here? I thought in a Python swap the two assignments happen simultaneously and independently.

A: This is because evaluation -- specifically at the left side of the = -- happens from left to right:
nums[i], nums[nums[i]-1] =

First nums[i] gets assigned, and then that value is used to determine the index in the assignment to nums[nums[i]-1]
When doing the assignment like this:
nums[nums[i]-1], nums[i] =

... the index of nums[nums[i]-1] is dependent on the old value of nums[i], since the assignment to nums[i] still follows later...

A: To understand the order of evaluation I made a 'Variable' class that prints when sets and gets occur to it's 'value'.
class Variable:
    def __init__(self, name, value):
        self._name = name
        self._value = value

    @property
    def value(self):
        print(self._name, 'get', self._value)
        return self._value

    @value.setter
    def value(self):
        print(self._name, 'set', self._value)
        self._value = value

a = Variable('a', 1)
b = Variable('b', 2)

a.value, b.value = b.value, a.value

When run results in:
b get 2
a get 1
a set 2
b set 1

This shows that the right side is evaluated first (from left to right) and then the left side is evaluated (again, from left to right).
Regarding the OP's example:
Right side will evaluate to same values in both cases. Left side first term is set and this impacts the evaluation of the second term. It was never simultaneous and independently evaluated, it's just most times you see this used, the terms don't depended on each other. Setting a value in a list and then taking a value from the that list to use as an index in the same list is usually not a thing and if that's hard to understand, you understand it. Like changing the length of a list in a for loop is bad, this has the same smell. (Stimulating question though, as you may have guessed from me running to a scratch pad)

A: One way to analyze code snippets in CPython is to disassemble its bytecode for its simulated stack machine.
>>> import dis
>>> dis.dis("nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]")
  1           0 LOAD_NAME                0 (nums)
              2 LOAD_NAME                0 (nums)
              4 LOAD_NAME                1 (i)

              6 BINARY_SUBSCR
              8 LOAD_CONST               0 (1)
             10 BINARY_SUBTRACT
             12 BINARY_SUBSCR
             14 LOAD_NAME                0 (nums)
             16 LOAD_NAME                1 (i)
             18 BINARY_SUBSCR

             20 ROT_TWO

             22 LOAD_NAME                0 (nums)
             24 LOAD_NAME                1 (i)
             26 STORE_SUBSCR

             28 LOAD_NAME                0 (nums)
             30 LOAD_NAME                0 (nums)
             32 LOAD_NAME                1 (i)
             34 BINARY_SUBSCR
             36 LOAD_CONST               0 (1)
             38 BINARY_SUBTRACT
             40 STORE_SUBSCR

             42 LOAD_CONST               1 (None)
             44 RETURN_VALUE

I added the blank lines to make reading this easier.  The two fetch expressions are calculated in bytes 0-13 and 14-19.  BINARY_SUBSCR replaces the top two values on the stack, an object and subscript, with the value fetched from the object.  The two fetched values are swapped so that the first calculated is the first bound.  The two store operations are done in bytes 22-27 and 28-41.  STORE_SUBSCR uses and removes the top three values on the stack, a value to be stored, an object, and a subscript.  (The return None part is apparently always added at the end.)  The important part for the question is that the calculations for the stores are done sequentially in separate and independent batches.
The closest description in Python of the CPython calculation requires introduction of a stack variable
stack = []
stack.append(nums[nums[i]-1])
stack.append(nums[i])
stack.reverse()
nums[i] = stack.pop()
nums[nums[i]-1] = stack.pop()

Here is the disassembly for the reversed statement
>>> dis.dis("nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]")
  1           0 LOAD_NAME                0 (nums)
              2 LOAD_NAME                1 (i)
              4 BINARY_SUBSCR

              6 LOAD_NAME                0 (nums)
              8 LOAD_NAME                0 (nums)
             10 LOAD_NAME                1 (i)
             12 BINARY_SUBSCR
             14 LOAD_CONST               0 (1)
             16 BINARY_SUBTRACT
             18 BINARY_SUBSCR

             20 ROT_TWO

             22 LOAD_NAME                0 (nums)
             24 LOAD_NAME                0 (nums)
             26 LOAD_NAME                1 (i)
             28 BINARY_SUBSCR
             30 LOAD_CONST               0 (1)
             32 BINARY_SUBTRACT
             34 STORE_SUBSCR

             36 LOAD_NAME                0 (nums)
             38 LOAD_NAME                1 (i)
             40 STORE_SUBSCR

             42 LOAD_CONST               1 (None)
             44 RETURN_VALUE

A: This happens according to the rules:

*

*The right hand side is evaluated first

*Then, each value of the left hand side gets its new value, from left to right.

So, with nums = [1, 2, 4, 3], your code in the first case
nums[2], nums[nums[2]-1] = nums[nums[2]-1], nums[2]

is equivalent to:
nums[2], nums[nums[2]-1] = nums[nums[2]-1], nums[2]

nums[2], nums[nums[2]-1] = nums[3], nums[2]

nums[2], nums[nums[2]-1] = 3, 4

and as the right hand side is now evaluated, the assignments are equivalent to:
nums[2] = 3
nums[nums[2]-1] = 4

nums[2] = 3
nums[3-1] = 4

nums[2] = 3
nums[2] = 4

which gives:
print(nums)
# [1, 2, 4, 3]

In the second case, we get:
nums[nums[2]-1], nums[2] = nums[2], nums[nums[2]-1]

nums[nums[2]-1], nums[2] = nums[2], nums[3]

nums[nums[2]-1], nums[2] = 4, 3

nums[nums[2]-1] = 4
nums[2] = 3

nums[4-1] = 4
nums[2] = 3

nums[3] = 4
nums[2] = 3
print(nums)
# [1, 2, 3, 4]

A: From python.org

Assignment of an object to a target list, optionally enclosed in parentheses or square brackets, is recursively defined as follows.
...

*

*Else: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

So I interpret that to mean that your assignment
nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]

is roughly equivalent to
tmp = nums[nums[i]-1], nums[i]
nums[i] = tmp[0]
nums[nums[i] - 1] = tmp[1]

(with better error-checking, of course)
whereas the other
nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]

is like
tmp = nums[i], nums[nums[i]-1]
nums[nums[i] - 1] = tmp[0]
nums[i] = tmp[1]

So the right-hand side is evaluated first in both cases. But then the two pieces of the left-hand side are evaluated in order, and the assignments are done immediately after evaluation. Crucially, this means that the second term on the left-hand side is only evaluated after the first assignment is already done. So if you update nums[i] first, then the nums[nums[i] - 1] refers to a different index than if you update nums[i] second.

A: On the left hand side of your expression you are both reading and writing nums[i], I dunno if python gaurantees processing of unpacking operations in left to right order, but lets assume it does, your first example would be equivilent to.
t = nums[nums[i]-1], nums[i]  # t = (3,4)
nums[i] = t[0] # nums = [1,2,3,3]
n = nums[i]-1 # n = 2
nums[n] = t[1] # nums = [1,2,4,3]

While your second example would be equivilent to
t = nums[i], nums[nums[i]-1]  # t = (4,3)
n = nums[i]-1 # n = 3
nums[n] = t[0] # nums = [1,2,4,4]
nums[i] = t[0] # nums = [1,2,3,4]

Which is consistent with what you got.

A: It seems to me that this would only happen when the contents of the list is in the range of list indexes for the list.  If for example:
nums = [10, 20, 40, 30]

The code will fail with:
>>> nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

So definitely, a gotcha. Never Ever Use the Contents of a list as an index into that list.

A: Thierry did give a good answer, let me be more clear. Be aware that if nums = [1, 2, 4, 3],
in this code:
nums[nums[i]-1], nums[i]

*

*i is 2,

*nums[nums[i]-1] is nums[4-1], so nums[3], (value is 3)

*nums[i] is nums[2], (value is 4)

*the result is: (3, 4)

in this code:
nums[i], nums[nums[i]-1]

*

*nums[i] is nums[2] becomes 3, (=>[1, 2, 3, 3])

*but nums[nums[i]-1] is not nums[4-1] but nums[3-1], so nums[2] too, becomes (back to) 4 (=>[1, 2, 4, 3])

Perhaps the good question concerning a swap, was using:
nums[i], nums[i-1] = nums[i-1], nums[i] ?
Try it:
>>> print(nums)
>>> [1, 2, 4, 3]
>>> nums[i], nums[i-1] = nums[i-1], nums[i]
>>> print(nums)
>>> [1, 4, 2, 3]

ChD


text:
Q: Mule and java.lang.reflect.Method cannot be cast to java.lang.String in flow-ref I have a sub-flow to invoke a soap service (req:String , response:String)
<sub-flow name="vinculaValidaServiceClienteFlow" doc:name="vinculaValidaServiceClienteFlow">
    <cxf:jaxws-client operation="vinculaServicioIngreso" serviceClass="...VinculaValidaService"  doc:name="SOAP"/>
    <http:outbound-endpoint exchange-pattern="request-response" method="POST" address="http://localhost:8070/pic/vinculaValidaService" doc:name="HTTP"/>
</sub-flow>

I have a simple service that I'm calling from a test flow. This service can be invoked well with MuleClient:
<flow name="vinculacionFlow2" doc:name="vinculacionFlow2">
    <vm:inbound-endpoint exchange-pattern="request-response" path="test2" doc:name="VM"/>
    <logger level="INFO" doc:name="Logger"/>
    <flow-ref name="vinculaValidaServiceClienteFlow" doc:name="Flow Reference"/>
</flow>

When I include the flow-ref in a main flow, can not be invoked, although the unit test was successful.
<flow name="vinculaServiceFlow" doc:name="vinculaServiceFlow">
    <http:inbound-endpoint exchange-pattern="request-response"   doc:name="vinculaServiceHTTP" ref="vinculaServiceHTTPEndpoint"/>
    <logger level="INFO" doc:name="Logger" message="luna es #[payload]"/>
    <cxf:jaxws-service doc:name="vinculaServiceSOAP" serviceClass="...service.VinculaService"/>
    <byte-array-to-string-transformer doc:name="Byte Array to String"/>
    <logger message="marte es #[payload]" level="INFO" doc:name="printpayload"/>
    <set-variable variableName="cedula" value="#[message.payload]" doc:name="Variable"/>
    <logger message="jupiter es #[flowVars['cedula']]" level="INFO" doc:name="printVar"/>
    <set-payload value="#[message.payloadAs(java.lang.String)]" doc:name="Set Payload"/>
    <logger message="sol es #[payload]" level="INFO" doc:name="printpayload"/>
    <flow-ref name="vinculaValidaServiceClienteFlow" doc:name="Flow Reference"/>
    <scripting:transformer doc:name="Groovy">
        <scripting:script engine="Groovy"><![CDATA[import   ec.gob.presidencia.tecnologia.pic.vincula.service.VinculaResponse def responseVincula = new VinculaResponse("54545366644","12063139", "se puede vincular") return responseVincula ]]>
        </scripting:script>
    </scripting:transformer>
    <catch-exception-strategy doc:name="Catch Exception Strategy">
        <set-payload value="Error durante el procesamiento del servicio de vinculacion" doc:name="Set mensejae error"/>
    </catch-exception-strategy>
 </flow>

The resulting exception is:
Exception stack is:
1. java.lang.reflect.Method cannot be cast to java.lang.String(java.lang.ClassCastException)
  org.mule.module.cxf.CxfOutboundMessageProcessor:338 (null)
2. java.lang.reflect.Method cannot be cast to java.lang.String. Failed to route event via endpoint: org.mule.module.cxf.CxfOutboundMessageProcessor. Message payload is of type: String (org.mule.api.transport.DispatchException)
  org.mule.module.cxf.CxfOutboundMessageProcessor:150 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transport/DispatchException.html)

Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to service.VinculaResponse
    at ec.gob.presidencia.tecnologia.pic.vincula.service.jaxws_asm.VinculaServicioIngresoResponse_WrapperTypeHelper1.createWrapperObject(Unknown Source)
    at org.apache.cxf.jaxws.interceptors.WrapperClassOutInterceptor.handleMessage(WrapperClassOutInterceptor.java:100)
    ... 97 more

This exception can not understand it, since the payload into a string before invoking the service (flow-ref). Could give me an idea to identify where this point at correcting?
Thanks.

A: Could be a duplicate of this? Mule method cannot be cast to string
You might also want to consider using proxying if your purpose is to map inbound SOAP calls to outbound SOAP calls: http://www.mulesoft.org/documentation/display/current/Proxying+Web+Services+with+CXF


text:
Q: Effects com jquery Galera estou tendo uma dúvida, uso efeitos em jQuery assim:
$("#elemento").toggle(2000);

Dei uma olha na documentação mas não estou achando a forma correta de fazer isso, preciso de um evento onde começa da direita para esquerda. E com 'toggle' eu tenho esse efeito, porém a div começa do topo paras baixo também.
Bom quero aplicar esse efeito:
Menu
No menu que estou montando:
Menu que estou montando

A: Seria isso que você quer:
$("#elemento").animate({left: "200px"}, 2000, function(){
        $(this).toggle();
        });

Exemplo no JSfiddle

A: Se tiver a possibilidade de usar bootstrap, faça dessa meneira.

$( ".toggle-effect" ).click(function() {
  $( ".demo-toggle" ).toggle( "fast" );
});
* {
  padding: 0;
  margin: 0;
}

.toggle-effect {
  font-size: 16px;
  background-color: #3498db;
  float: left;
  padding: 20px;
  writing-mode: vertical-rl;
  white-space: nowrap;
  display: block;
  cursor: pointer;
  -webkit-transform: rotate(180deg);
  -moz-transform: rotate(180deg);
  -o-transform: rotate(180deg);
  -ms-transform: rotate(180deg);
  transform: rotate(180deg);
}

.demo-toggle {
  display: none;
  padding: 10px;
  float: left;
}

Clique Aqui

Oi, eu sou seu toggle bem mais simples.

A: Resolvi o problema assim:
$("#mySidenav").animate({width: 'toggle'});


text:
Q: method overriding with wrapper class public class A
{
    public void display(int i)
    {
        System.out.println("Inside A");
    }
}

public class B extends A
{
    public void display(Integer i)
    {
        System.out.println("Inside B");
    }
}

public class starter
{
    public static void main (String args[])
    {
        A a = new B();
        a.display(5);
        System.out.println("So now you know or not");
    }
}

Output : Inside A
Can somebody explain this output? Normally child method should be called. How does Java behave here when we have a wrapper class and a primitive class using inheritance?

A: B#display does not override A#display, as the signature is different.
The fact ints can be boxed into Integers is not relevant here.
You could easily verify this by using the @Override annotation.
Since the reference type of a is A, the method is resolved with the exact match for a literal integer (your given 5 argument), which is int, therefore A#display is invoked.
You can still force the invocation of B#display by using this idiom (not for production code):
((B)a).display(new Integer(5));
This casts your a variable as a B type, hence allowing visibility of B's display method within context.
It also passes an Integer rather than an int, thus employing the signature of B's display method and allowing resolution to that method.


text:
Q: Sails.js not applying model scheme when using MongoDB I'm going through the (excellent) Sails.js book, which discusses creating a User model User.js in Chapter 6 like so:
module.exports = {
    connection: "needaword_postgresql",
    migrate: 'drop',
    attributes: {
        email: {
            type: 'string',
            email: "true",
            unique: 'string'
        },

        username: {
            type: 'string',
            unique: 'string'
        },

        encryptedPassword: {
            type: 'string'
        },

        gravatarURL: {
            type: 'string'
        },

        deleted: {
            type: 'boolean'
        },

        admin: {
            type: 'boolean'
        },

        banned: {
            type: 'boolean'
        }
    },
    toJSON: function() {
      var modelAttributes  = this.toObject();
      delete modelAttributes.password;
      delete modelAttributes.confirmation;
      delete modelAttributes.encryptedPassword;
      return modelAttributes;
    }
};

Using Postgres, a new record correctly populates the boolean fields not submitted by the login form as null, as the book suggests should be the case:

But I want to use MongoDB instead of PostgreSQL. I had no problem switching the adaptor. But now, when I create a new record, it appears to ignore the schema in User.js and just put the literal POST data into the DB:

I understand that MongoDB is NoSQL and can take any parameters, but I was under the impression that using a schema in Users.js would apply to a POST request to the /user endpoint (via the blueprint routes for now) regardless of what database was sitting at the bottom. Do I need to somehow explicitly tie the model to the endpoint for NoSQL databases?
(I've checked the records that are created in Postgres and MongoDB, and they match the responses from localhost:1337/user posted above)

A:
I understand that MongoDB is NoSQL

Good! In sails the sails-mongo waterline module is responsible for everything regarding mongodb. I think I found the relevant code: https://github.com/balderdashy/sails-mongo/blob/master/lib/document.js#L95 So sails-mongo simply does not care about non existent values. If you think this is bad then feel free to create an issue on the github page.
A possible workaround might be using defaultsTo:
banned : {
    type : "boolean",
    defaultsTo : false
}

A: You can configure your model to strictly use the schema with this flag:
module.exports = {
  schema: true,
  attributes: {
    ...
  }
}

A: I eventually settled on performing the validations inside my controller.
// a signup form
create: async (req, res) => {
    const { name, email, password } = req.body;
    try {
      const userExists = await sails.models.user.findOne({ email });
      if (userExists) {
        throw 'That email address is already in use.';
      }
}


text:
Q: Como usar scrapy em páginas asp.net Bom pessoal, minha dúvida é a seguinte:
Tenho que baixa o arquivo excel do produto que contem a descrição "Maíz", Tipo de producto "Los Démas. En grano." e Comercialização "A granel con hasta un 15 % embolsado", desse  Site
Usando as libraries requests e beautifulsoup eu estava conseguindo extrair as informações da Grid, porém, não estava conseguindo fazer oq eu queria, que é justamente clicar no segundo botão "Exporta informacion Diária".
Analisando a aba "Network" da DeveloperTools ele faz duas chamadas, sendo uma delas criando um link temporário e então, esse link temporário redireciona para o arquivo .xls.

Após não conseguir com fazer o que eu queria com libraries Requests e BeautifulSoup, parti então para o famoso Scrapy.
Já consegui extrair dados de diversas páginas com Scrapy, mas ainda sim, não tive nenhum êxito em extrair a página em asp.net.
Enfim, apenas queria que alguém me apontasse para a direção certa, sem necessidade de códigos.
Por acaso eu tenho que enviar um Post Request com as informações que eu quero? Se sim, como eu poderia fazer isso e então baixar o arquivo .xls?
Agradeço desde já.

A: Scrapy é um módulo que combina o twisted.web para baixar as páginas e o BeautifulSoup ou o lxml para parseá-las.
O seu problema é que o botão que você quer clicar, provavelmente, na verdade não existe mesmo na página! É bem provável que as páginas do site que você quer usar, assim como muitas outras na internet, são disponibilizadas incompletas, sem todos os elementos, e só depois esses elementos são colocados na página através de código feito em javascript que é executado em seu navegador após o carregamento.
Portanto, ao inspecionar o código da página usando o seu navegador, o javascript já terá executado e completado os elementos de forma dinâmica, por isso você encontrará o botão lá. Como nem BeautifulSoup e nem lxml executam javascript, na página que eles parsearam na memória ao rodar o script o botão não existe.
Isso é muito comum nas páginas da web hoje em dia, que são bastante dinâmicas. Te deixando com duas opções:

*

*Analisar o código javascript da página e descobrir onde ele cria o botão. Ou então analisar o que o botão faz. Você pode ir lendo e acompanhando o código javascript manualmente até encontrar uma forma de imitar o que ele faz ao clicar nesse botão, quais parâmetros passar, etc. Em seguida escreva código em python para simular essas ações. Não é uma tarefa fácil mas o código ficaria bastante otimizado pois seria código python sem precisar abrir um navegador de verdade, que seria a segunda opção:

*Utilizar um navegador de verdade, que rode javascript. A biblioteca Selenium permite que você abra e controle uma janela de navegador real através do seu script. Como a página abrirá em um navegador verdadeiro, o javascript vai funcionar e você consegue clicar no botão. O lado negativo é que abrir um navegador é pesado e lento, além de carregar vários elementos e imagens desnecessárias ao processo, portanto, não seria tão eficiente quanto acessar diretamente a fonte.


text:
Q: pageToken while scraping Youtube comments in R I am trying to generate a dataset of comments from a Youtube video and am having trouble looping over the pageToken using the Google API.  Below is a snippet of code.  Why doesn't the 'while' loop work?
base_url <- "https://www.googleapis.com/youtube/v3/commentThreads/"
data = "list"

 api_opts <- list(
  part = "snippet",
  maxResults = 100,
  textFormat = "plainText",
  videoId = "N708P-A45D0", # This is an example of a video id
  key = "google developer key goes here",
  fields = "items,nextPageToken",
  orderBy = "published")

init_results <- httr::content(httr::GET(base_url, query = api_opts))
data <- init_results$items
api_opts$pageToken <- init_results$nextPageToken
api_opts$pageToken <- gsub("\\=", "", init_results$nextPageToken)
print(api_opts$pageToken)

while (api_opts$pageToken != "") {
        print(api_opts$pageToken)
        next_results <- httr::content(httr::GET(base_url, query = api_opts))
        data <- c(data, next_results$items)
        api_opts$pageToken <- gsub("\\=", "", next_results$nextPageToken)
}

organize_data = function(){

    sub_data <- lapply(data, function(x) {
          data.frame(
            Comment = x$snippet$topLevelComment$snippet$textDisplay,
            User = x$snippet$topLevelComment$snippet$authorDisplayName,
            ReplyCount = x$snippet$totalReplyCount,
            LikeCount = x$snippet$topLevelComment$snippet$likeCount,
            PublishTime = x$snippet$topLevelComment$snippet$publishedAt,
            CommentId = x$snippet$topLevelComment$id,
            stringsAsFactors=FALSE)
        })
}

sample <- organize_data()
L <- length(sample)
sample <- data.frame(matrix(unlist(sample), nrow=L, byrow=T))
colnames(sample) <- c("Comment", "User", "ReplyCount", "LikeCount", "PublishTime", "CommentId")
head(sample)

A: Thanks for looking, in case anyone else has this problem in the future, below is what I did to fix this problem.  I still can't get the replies to the replies.
####
# NEW TRY
# Note: according to YouTube "YouTube currently supports replies only for top-level comments. However, replies to replies may be supported in the future."

####

rm(list=ls())
data = "list"

# Initialize
init_results <- httr::content(httr::GET("https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2C+replies&maxResults=100&textFormat=plainText&videoId=N708P-A45D0&fields=items%2CnextPageToken&key=[my google developer key]"))
data <- init_results$items
init_results$nextPageToken
print(init_results$nextPageToken)

# Begin loop
while (init_results$nextPageToken != ""){
    # Make the page token URL encoded
    api_opts_pageToken <- gsub("=", "%3D", init_results$nextPageToken)
    # Write the call with the updated page token
    get_call <- gsub("api_pageToken", api_opts_pageToken, "https://www.googleapis.com/youtube/v3/commentThreads?part=snippet%2C+replies&maxResults=100&pageToken=api_pageToken&textFormat=plainText&videoId=N708P-A45D0&fields=items%2CnextPageToken&key==[my google developer key]")
    # Pull out the data from this page token call
    next_results <- httr::content(httr::GET(get_call))
    # Update the datafile
    data <- c(data,next_results$items)
    # Update the page token
    print(next_results$nextPageToken)
    init_results$nextPageToken <- next_results$nextPageToken
}

organize_data = function(){

    sub_data <- lapply(data, function(x) {
          data.frame(
            Comment = x$snippet$topLevelComment$snippet$textDisplay,
            User = x$snippet$topLevelComment$snippet$authorDisplayName,
            ReplyCount = x$snippet$totalReplyCount,
            LikeCount = x$snippet$topLevelComment$snippet$likeCount,
            PublishTime = x$snippet$topLevelComment$snippet$publishedAt,
            CommentId = x$snippet$topLevelComment$id,
            stringsAsFactors=FALSE)
        })
}

sample <- organize_data()
L <- length(sample)
sample <- data.frame(matrix(unlist(sample), nrow=L, byrow=T))
colnames(sample) <- c("Comment", "User", "ReplyCount", "LikeCount", "PublishTime", "CommentId")
head(sample)
dim(sample)


text:
Q: How can I execute something only if the function has been called once in the past 5 seconds? I have a function called zoomed that executes anytime a user zooms in on part of the screen.  So it can execute several times in a matter of seconds as the user zooms.  I want to log 'done zooming' the last time the function is called.  What is the best way to achieve this?
function zoomed() {
  console.log('called');
  // If this has only been called once in past
  // 5 seconds, user is done zooming
  // console.log('done zooming')
}

A: Something like this would work:
var doneZooming = true; //Global variable to store the current "state" of zooming
var zoomTimeout = null; //Variable to store our 5-second timer

function zoomed() {
   resetZoomTimer();
   console.log("zooming");
}

function resetZoomTimer() {
   doneZooming = false;
   clearTimeout(zoomTimeout); //End current timer
   zoomTimeout = setTimeout(zoomComplete, 5000); //Reset the timer to 5 seconds
}

function zoomComplete() {
   doneZooming = true;
   console.log("zooming complete");
}

Here is an example of this code in use. Keep an eye on console.

The zoomComplete() function acts as a callback that will fire when the user is finished zooming.
If this isn't necessary, you can probably eliminate some of the functions here - I broke it out for readability. On that same note, you could simply move the functions within resetZoomTimer() into your zoomed() function if you're looking to consolidate, but again, personal preference.

A: What you're looking for is commonly called debouncing. It's used regularly in scenarios like yours.
It's not hard to write the function yourself, but utility libraries like lodash have good implementations.
widget.on('zoom', _.debounce(zoomed, 5000, { trailing: true }));

What this does is start listening when zooming happens, then after a 5 second pause in zooming, call the zoomed() function.
See https://lodash.com/docs/4.17.4#debounce

A: I would personally have a global variable (accessible by all instances of the function) that is assigned a setTimeout function at the end of the function execution. This creates a timer that would only execute if it wasn't cleared by another instance of the function.
e.g.
var zoomTimer;

function zoomed() {
    console.log('called');
    // Clears the timeout associated with the variable
    clearTimeout(zoomTimer);
    // Sets the 5 second timeout
    zoomTimer = setTimeout(function() { console.log('done zooming'); }, 5000);
};


text:
Q: "TypeError: Cannot read property 'fulfillmentMessages' of undefined" I am trying to integrate Dialogflow to React Native and I followed this tutorial
However, I am encountering this error.
Below is my handleGoogleResponse that causes the error
handleGoogleResponse(result) {
    let text = result.queryResult.fulfillmentMessages[0].text.text[0]; //error
    this.sendBotResponse(text);
  }

I hope you could help me with this. Thank you so much.

A: its say that the queryResult is undefined,
check if you configured firebase currectly.
show intire code


text:
Q: Issue using certbot with nginx I'm actually working on a webapp, I use Reactjs for the frontend and Golang for the backend. Those 2 programs are hosted separately on 2 VMs on Google-Compute-Engine. I want to serve my app through https so I choose to use Nginx for serving the frontend in production. Firstly I made my config file for Nginx:
#version: nginx/1.14.0 (ubuntu)
server {
     listen 80 default_server;
     listen [::]:80 default_server;

     root /var/www/banshee;
     server_name XX.XXX.XX.XXX; #public IP of my frontend VM

     index index.html;

     location / {
       try_files $uri /index.html =404;
     }
   }

For this part everything works as expected but after that I want to serve my App over https following this tutorial. I installed the packages software-properties-common,python-certbot-apache
 and certbot but when I tried
sudo cerbot --nginx certonly
I get the following message:
gdes@frontend:/etc/nginx$ sudo certbot --nginx certonly
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Could not choose appropriate plugin: The requested nginx plugin does not appear to be installed
The requested nginx plugin does not appear to be installed

I made some searches on Google and here and I still can't figure out which plugin is missing or an other way to fix this.
Does someone have an idea tohelp me ?
Thanks a lot :)

A: You can install the Certbot nginx plugin with the following commands:
add-apt-repository ppa:certbot/certbot
apt update
apt install python-certbot-nginx

A: You have to re-install a python3 version of Lets Encrypt's certbot.
Run
sudo apt-get install python3-certbot-nginx

A: You will need to replace
apt install python-certbot-nginx

by
apt install python3-certbot-nginx

A: I was trying to create Let's Encrypt certificate using certbot for my sub-domain and had the following issue.
Command:

ubuntu@localhost:~$ certbot --nginx -d my_subdomain.website.com -d my_subdomain2.website.com

Issue:

The requested Nginx plugin does not appear to be installed

Solution:
Ubuntu 20+

ubuntu@localhost:~$ sudo apt-get install python3-certbot-nginx

Earlier Versions

ubuntu@localhost:~$ sudo apt-get install python-certbot-nginx

A: On Debian 10, certbot returns a "could not find a usable nginx binary" issue because, "/usr/sbin" is missing from the PATH. Add /usr/sbin to the PATH
export PATH=/usr/sbin:$PATH

Then certbot can make a certificate for nginx
certbot --nginx -d <server name> --post-hook "/usr/sbin/service nginx restart"

As explained on the debian wiki page for letsencrypt.


text:
Q: Is it possible in Common Lisp to disable return values for specified functions? I would like to know whether or not it's possible to disable return values for specified functions. I am using compiler SBCL. I am asking this, because it takes a while to print the return value, and I don't even need it. Any ideas?
OK, it does the job:
(progn
  (...)
  t)

Also, thanks for *print-length*.

A: I find it useful to limit the amount of data printed to my reply by setting the *print-length* variable to a relatively low value in my lisp startup file, like so:
(setf *print-length* 20)

That way, I do not have to worry too much about functions that return a large number of elements.

A: Using the function values it is possible to return zero (or several) values from a function.
values returns all it's arguments. Thus a function having (values) as it's last form will not return anything, while a function ending with (values val1 val2 val3) will return three values. When calling a function returning several values, only the first one (the primary return value) is available in the normal way, while the other ones may be captured using e.g. multiple-value-bind See the section on Return Values in the Hyperspec for further details
If you want to limit the output from a function that you can not modify, you can call it like this:
(progn
   (function-returning-much-data)
   (values))


text:
Q: What dimensions are required in an IOAPI NetCDF file? When I do an ncdump -h on some old I/O API NetCDF files, I always get the same dimensions:
dimensions:
    TSTEP
    DATE-TIME
    LAY
    VAR
    ROW
    COL

Are these exact dimensions and names always required in an I/O API NetCDF file? (If this is the convention, why does it require TSTEP and DATE-TIME? They sound redundant.)

A: Most recent documentation seems to be included in https://github.com/cjcoats/ioapi-3.2
And there is a section called FILES: Variables, Layers, and Time Steps where You can read that "There are eight types of data currently supported by the I/O API." Without knowing Your files exactly, I cannot tell what format they should precisely correspond to.


text:
Q: How to structure a static list of options for a dropdown that is coupled to your code? In the past, all my lists were put in the database. I did not know better and it seemed to me like data... so I put them in the database.
For some lists (e.g. countries), it is the right way to do it.  But for others like options that triggers a different behaviour in your code, it is not.
For instance, let's say I have a User object and this object has a property called Status. The Status is tightly coupled to behavious in my code:

*

*Active: you can access the application.

*Banned: you cannot access the application and can never reset your account.

*Inactive: You did not use your acccess for X months, you can fill a form to reactivate your account.

The old me would have created a table in the database called UserStatus with
3 rows in it. The table would have looked like this:
+----+----------+
| Id |   Code   |
+----+----------+
|  1 | ACTIVE   |
|  2 | BAN      |
|  3 | INACTIVE |
+----+----------+

Then, Code column would have been used in my code to "bind" the user status to the right behaviour (and to the right 'display string' according to the language).  That said, editing the Code would have screwed everything. And adding new status in the database would have no effect as you need to add data in the database AND add code to handle the status.  This seems like the wrong way of doing things.
Then, I thought about using an enum.  Now, I don't have the database + code issue.  I handle everything from the code and it makes more sense as, in my opinion, it's not data that should be in a database.  But with enum comes this problem: in fact hey are an int but I need to use them as string.
I also thought about setting constants in the User object:
public const string Active = "ACTIVE";
public const string Ban = "BAN";
public const string Inactive = "INACTIVE";

But now that I have figured the right way to handle it in the code, I must display the list in the UI. It can be done with the enum but it requires some hacking. Samething with the constants as the list needs to be handled manually. Using the database would make that so easy... damn!
In the end, my question becomes: What is the right structure for these "static" lists that are tightly coupled with your code but also need to be displayed ?
Update:
Each user has one (and only one) Status and that Status can be changed.

A: I've contemplated the same question many, many times over the years.  Here are some [perhaps] insights that I've learned.
First, some clarification.  I assume that each user will have a Status attribute and that the value can change for each user.  In other words, the value belongs in the DB and it must be associated with each user.
My favorite approach in this case - store a string in the User table
My favorite approach is to create a Status column on the user table.  Since each user can only have 1 status, it makes sense to just store this detail in the User table.  Doing so has the advantage of making queries easier to write.  The reason I'd choose to store it as a string are 2:

*

*It makes perusing the DB easier.  While debugging and just viewing raw data in the db, it's easy for developers new to the project to understand what the Status column is at a glance and it's easy to figure out the the Status of any given User row at a glance.  Making values easy to understand is of the utmost importance in my opinion when making software easy to develop/modify.

*I assume that duplicating this string won't become a performance/storage problem.  Now, if you have millions and millions (maybe even hundreds of millions) of user rows, then you may want to shrink the size of this column.

And one other thing I like to do is to make sure that I use a file of constants (like what you described) and only use those constants when interacting with the DB table (for inserts/updates, that is).  That's the perfect use case for constants, and you can create easy little utility functions that ensure the value you are about to insert are in that list of constants.
Caveats that could change my answer, and alternative solutions

*

*You have hundreds of millions of Users.

*

*In this case, you may need to shrink the size of the column to save space.  You can either use an enum of some sort in the DB and limit the field to be a small varchar type of some sort or use a small int of some sort to represent the Status.  I'd still put that column on the User record to prevent extra join's in large queries.  And if you went the int route, I would handle the translation of that int into a string in the code and in project documentation.  Lookup tables that translate 1 to "Active" really aren't any more helpful than a file of constants in your code that does the same thing, in my opinion.  And it just adds a join to every query that you write.  Looping through result rows in your code is generally going to be so fast that there is no performance hit either way. This caveat probably isn't even worth mentioning, but I have run into it on rare occasions.

*Each user can have multiple statuses.  Well, in this case you'd need a join table of some sort.  I'd probably make the join table look like this, if possible:

+--------+----------+
| UserId |   Code   |
+--------+----------+
|  1     | ACTIVE   |
|  2     | BAN      |
|  3     | INACTIVE |
|  1     | BAN      |
+--------+----------+

Now I realize that your use-case doesn't really make sense for a one-to-many relationship like this.  BUT, in other use-cases where you're debating where to stick constants like this, you may run into this situation.  In these cases, I STILL like to put a string in the DB when possible.  Unless I'm really worried about saving the bits and bytes, I'll use a string.  And 99% of the time, a column like this isn't the place you're worried about saving space.  It just makes perusing the DB and learning the DB so much easier.
Anyway, just some thoughts from my experiences, hope you find them helpful!


text:
Q: Unable to install TeX package in Ubuntu 18.04 I am using Pop!_os 18.04 LTS (which is based on Ubuntu 18.04) and I am trying to get program to run which makes heavy use of LaTeX. I am using the MiKTeX package manager to install the TeX packages that the program requires. I am stuck on trying to get this package dsfont to install. According to this answer, installing texlive-fonts-extra should have fixed it. I tried using sudo apt-get install texlive-fonts-extra and it installs correctly but the error still stands.
The same thread also explains how dstroke is the distribution package name in MiKTeX for dsfont. However, I cannot find a package named dstroke in MiKTeX. The search returns an empty list. The had suggested that a package named doublestroke was being used in TeX live for getting dstroke. So I tried searching for that in MiKTeX just in case and I was able to find it and install it. But that also did not fix the error. I cannot find any other pointer to installing this. Please help.
OS: Pop!_OS 18.04 (Similar to Ubuntu 18.04)
Python: 3.7.1
MiKTeX: MiKTeX Package Manager 2.9.7043 (MiKTeX 2.9.7050)

TeX error Log -
This is pdfTeX, Version 3.14159265-2.6-1.40.20 (MiKTeX 2.9.7050) (preloaded format=latex 2019.7.21)  21 JUL 2019 22:41
entering extended mode
**./media/Tex/f4fdd6aabf2e43a0.tex
(media/Tex/f4fdd6aabf2e43a0.tex
LaTeX2e <2018-12-01>
(/home/ananda/.miktex/texmfs/install/tex/latex/standalone/standalone.cls
Document Class: standalone 2018/03/26 v1.3a Class to compile TeX sub-files stan
dalone
(/home/ananda/.miktex/texmfs/install/tex/latex/xkeyval/xkeyval.sty
Package: xkeyval 2014/12/03 v2.7a package option processing (HA)
(/home/ananda/.miktex/texmfs/install/tex/generic/xkeyval/xkeyval.tex (/home/ana
nda/.miktex/texmfs/install/tex/generic/xkeyval/xkvutils.tex
\XKV@toks=\toks14
\XKV@tempa@toks=\toks15
(/home/ananda/.miktex/texmfs/install/tex/generic/xkeyval/keyval.tex))
\XKV@depth=\count80
File: xkeyval.tex 2014/12/03 v2.7a key=value parser (HA)
))
\sa@internal=\count81
\c@sapage=\count82
(/home/ananda/.miktex/texmfs/install/tex/latex/standalone/standalone.cfg
File: standalone.cfg 2018/03/26 v1.3a Default configuration file for 'standalon
e' class
) (/home/ananda/.miktex/texmfs/install/tex/latex/base/article.cls
Document Class: article 2018/09/03 v1.4i Standard LaTeX document class
(/home/ananda/.miktex/texmfs/install/tex/latex/base/size10.clo
File: size10.clo 2018/09/03 v1.4i Standard LaTeX file (size option)
)
\c@part=\count83
\c@section=\count84
\c@subsection=\count85
\c@subsubsection=\count86
\c@paragraph=\count87
\c@subparagraph=\count88
\c@figure=\count89
\c@table=\count90
\abovecaptionskip=\skip41
\belowcaptionskip=\skip42
\bibindent=\dimen102
) (/home/ananda/.miktex/texmfs/install/tex/latex/preview/preview.sty
Package: preview 2017/04/24 11.91 (AUCTeX/preview-latex)
(/home/ananda/.miktex/texmfs/install/tex/latex/preview/prtightpage.def
\PreviewBorder=\dimen103
)
\pr@snippet=\count91
\pr@box=\box27
\pr@output=\toks16
)) (/home/ananda/.miktex/texmfs/install/tex/generic/babel/babel.sty
Package: babel 2019/07/19 3.33 The Babel package
(/home/ananda/.miktex/texmfs/install/tex/generic/babel/switch.def
File: switch.def 2019/07/19 3.33 Babel switching mechanism
) (/home/ananda/.miktex/texmfs/install/tex/latex/babel-english/english.ldf
Language: english 2017/06/06 v3.3r English support from the babel system
(/home/ananda/.miktex/texmfs/install/tex/generic/babel/babel.def
File: babel.def 2019/07/19 3.33 Babel common definitions
\babel@savecnt=\count92
\U@D=\dimen104
(/home/ananda/.miktex/texmfs/install/tex/generic/babel/txtbabel.def)
\bbl@dirlevel=\count93
)
\l@british = a dialect from \language\l@english
\l@UKenglish = a dialect from \language\l@english
\l@american = a dialect from \language\l@english
\l@canadian = a dialect from \language\l@american
\l@australian = a dialect from \language\l@british
\l@newzealand = a dialect from \language\l@british
)) (/home/ananda/.miktex/texmfs/install/tex/latex/amsmath/amsmath.sty
Package: amsmath 2018/12/01 v2.17b AMS math features
\@mathmargin=\skip43
For additional information on amsmath, use the `?' option.
(/home/ananda/.miktex/texmfs/install/tex/latex/amsmath/amstext.sty
Package: amstext 2000/06/29 v2.01 AMS text
(/home/ananda/.miktex/texmfs/install/tex/latex/amsmath/amsgen.sty
File: amsgen.sty 1999/11/30 v2.0 generic functions
\@emptytoks=\toks17
\ex@=\dimen105
)) (/home/ananda/.miktex/texmfs/install/tex/latex/amsmath/amsbsy.sty
Package: amsbsy 1999/11/29 v1.2d Bold Symbols
\pmbraise@=\dimen106
) (/home/ananda/.miktex/texmfs/install/tex/latex/amsmath/amsopn.sty
Package: amsopn 2016/03/08 v2.02 operator names
)
\inf@bad=\count94
LaTeX Info: Redefining \frac on input line 223.
\uproot@=\count95
\leftroot@=\count96
LaTeX Info: Redefining \overline on input line 385.
\classnum@=\count97
\DOTSCASE@=\count98
LaTeX Info: Redefining \ldots on input line 482.
LaTeX Info: Redefining \dots on input line 485.
LaTeX Info: Redefining \cdots on input line 606.
\Mathstrutbox@=\box28
\strutbox@=\box29
\big@size=\dimen107
LaTeX Font Info:    Redeclaring font encoding OML on input line 729.
LaTeX Font Info:    Redeclaring font encoding OMS on input line 730.
\macc@depth=\count99
\c@MaxMatrixCols=\count100
\dotsspace@=\muskip10
\c@parentequation=\count101
\dspbrk@lvl=\count102
\tag@help=\toks18
\row@=\count103
\column@=\count104
\maxfields@=\count105
\andhelp@=\toks19
\eqnshift@=\dimen108
\alignsep@=\dimen109
\tagshift@=\dimen110
\tagwidth@=\dimen111
\totwidth@=\dimen112
\lineht@=\dimen113
\@envbody=\toks20
\multlinegap=\skip44
\multlinetaggap=\skip45
\mathdisplay@stack=\toks21
LaTeX Info: Redefining \[ on input line 2844.
LaTeX Info: Redefining \] on input line 2845.
) (/home/ananda/.miktex/texmfs/install/tex/latex/amsfonts/amssymb.sty
Package: amssymb 2013/01/14 v3.01 AMS font symbols
(/home/ananda/.miktex/texmfs/install/tex/latex/amsfonts/amsfonts.sty
Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support
\symAMSa=\mathgroup4
\symAMSb=\mathgroup5
LaTeX Font Info:    Overwriting math alphabet `\mathfrak' in version `bold'
(Font)                  U/euf/m/n --> U/euf/b/n on input line 106.
))

! LaTeX Error: File `dsfont.sty' not found.

Type X to quit or <RETURN> to proceed,
or enter new name. (Default extension: sty)

Enter file name:
! Emergency stop.
<read *>

l.7 \usepackage
               {setspace}

Here is how much of TeX's memory you used:
 2175 strings out of 494858
 28788 string characters out of 3178198
 96215 words of memory out of 3000000
 5854 multiletter control sequences out of 15000+200000
 3640 words of font info for 14 fonts, out of 3000000 for 9000
 0 hyphenation exceptions out of 8191
 34i,0n,56p,244b,36s stack positions out of 5000i,500n,10000p,200000b,50000s

No pages of output.

A: It is recommended that do not install TeXLive from Ubuntu repository. Get latest TexLive 2019 from CTAN repository and install it. First remove previous installed packages and MikTex.
sudo apt-get remove texlive-*

Go to the folder which you downloaded, and run the following command:
sudo perl install-tl --gui=perltk

A: As a MiKTeX package it is known as doublestroke. Furthermore, it may happen that you have to launch updmap to refresh the type 1 fonts database:


text: Q: LMA count not being updated by CMA One of my clients purchased an additional license 4 days ago but it is still not available in the LMA. In the CMA correctly shows the license count, but I can't figure out how to get the LMA to update. I'm unable to do it manually as it's a Salesforce provisioned license. I've opened a case w/ Salesforce, but last time I did that it took them almost two weeks to answer me so I'm hoping there may be a fix or workaround someone here knows. Thanks.


text:
Q: Problems Connecting to Active Directory Using Devise I have been tasked at work to authenticate my "rails 3 app" with our Active Directory(Windows 2003), before accessing certain pages.
I decided to use "devise_ldap_authenticatable", but can't seem to get it to work properly.
I keep getting redirected to the login page with the following error message showing in the logs.
"Completed 401 Unauthorized in 3ms"
Do I have to change the devise email field to a user-name in order for it to connect successfully?
Has anyone got a working config I could can look at?
My ldap.yml consists of the following:
development:
  host: myip
  port: 389
  attribute: sAMAccountName
  base: cn=Users,dc="mydomain",dc=uk,dc=com
  admin_user: user
  admin_password: password
  ssl: false

my devise.rb consists of the following:
config.ldap_logger = true
config.ldap_config = "#{Rails.root}/config/ldap.yml"
config.ldap_use_admin_to_bind = true
config.ldap_ad_group_check = false
require 'devise/orm/active_record'
config.authentication_keys = [ :email ]
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true

my routes.rb consists of the following:
resources :posts
   devise_for :users
   root :to => 'posts#index'
   match ':controller(/:action(/:id))(.:format)'


text:
Q: Three.js - What's the most effective way to render a WebGLRenderTarget texture? Problem
I've gotten to a point in my project where I'm rendering to WebGLRenderTargets and using them as a textures in my main scene. It works, but it seems like I'm having it do a lot more work than it needs to. My generated textures only need to be 64x64, but because I'm using my main renderer (window width by window height) for both, it's unnecessarily rendering the WebGLRenderTargets at a much larger resolution.
I may be wrong, but I believe this increases both the processing required to draw to each RenderTarget and the processing required to then draw that large texture to the mesh.
I've tried using a second renderer, but I seem to get this error when trying to use a WebGLRenderTarget in renderer A after drawing to it from renderer B:
WebGL: INVALID_OPERATION: bindTexture: object not from this context
Example
For reference, you can see my abstracted page here (Warning: Due to the very issue I'm inquiring about, this page may lag for you). I'm running a simplex function on a plane in my secondary scene and chopping it up into sections using camera placement, then applying the segments to tile pieces via WebGLRenderTarget so that they're fluent but individual pieces.
Question
Am I correct in my assumption that using the same renderer size is much less efficient than rendering to a smaller renderer would be? And if so, what do you think the best solution for this would be? Is there currently a way to achieve this optimization?

A: The size parameters in renderer.setSize() are used by the renderer to set the viewport when rendering to the screen only.
When the renderer renders to an offscreen render target, the size of the texture rendered to is given by the parameters renderTarget.width and renderTarget.height.
So the answer to your question is that it is OK to use the same renderer for both; there is no inefficiency.