text:
Q: JavaScript Inheritance with Prototypes -- 'constructor' property? I've seen a lot of stuff like this, and am looking for the proper solution to basic JavaScript inheritance:
function Food(){}  // Food  constructor (class)
function Bread(){} // Bread constructor (class)

var basicFood = new Food();    // Food classes will inherit from this basicFood instance.

Bread.prototype = basicFood; // Bread now inherits from Food.

var bread = new Bread();     // We create some bread!
bread.constructor == Food;  // Though, now we feel very uneasy about how
                           // the constructor is wrong,

Bread.prototype.constructor = Bread; // So we explicitly set the prototype's constructor
bread = new Bread();                // and when we create our new bread,
bread.constructor == Bread;        // we feel much better as the constructor appears correct.

// The issue? Suppose we have another food item,
 // like in a real inheritance situation:

function Sushi(){};                    // We might be
Sushi.prototype = basicFood;          // tempted to do
Sushi.prototype.constructor = Sushi; // the same thing
var sushi = new Sushi();            // again

sushi.constructor == Sushi;  // Before we realize
bread.constructor == Sushi; // that we've ruined our bread.

basicFood.constructor != Food; // More importantly, we've really ruined all our basicFood,
                              // because while it's a prototype,
                             // it's also an object in its own right,
                            // and deserves an accurate constructor property.

Who is constructor supposed to really be?
And does constructor have anything to do with the results of instanceof?
I find myself wondering, what is correct? I understand that many would choose to give each food class (Bread, Sushi, etc) a new instance of Food, rather than giving them all the same basicFood instance.. I want this more optimal solution (not making unneeded instances).
Given our Food, Bread, Sushi, and basicFood:
function Food(){}
function Bread(){}
function Sushi(){}
var basicFood = new Food();

I figured I could create an instancing helper, which would define a non-enumerable non-writable non-configurable property 'constructor' on the new instance:
Bread.prototype = basicFood; // We still simply inherit from basicFood
Sushi.prototype = basicFood;

// But we use this helper function when we make instances
function reconstructify(target, Constructor){
  return Object.defineProperty(target, 'constructor', {
    enumerable:   false,
    configurable: false,
    writable:     false,
    value:        Constructor
  });
}

var bread = reconstructify(new Bread(), Bread); // Like so
var sushi = reconstructify(new Sushi(), Sushi);

In testing this, I realized instanceof is not behaving the way I thought it might:
// True expressions for testing -- all good
basicFood.constructor == Food;
bread.constructor     == Bread;
sushi.constructor     == Sushi;

basicFood instanceof Food; // good also
bread instanceof Food;
sushi instanceof Food;

sushi instanceof Bread; // uh oh, not so good that this is true
bread instanceof Sushi; // why is this?

Looking into it more, I can't seem to get instanceof to work the way I'd assume at all:
function Food(){}
function Bread(){}
function Sushi(){}

var basicFood = new Food();

Bread.prototype = basicFood;
Sushi.prototype = basicFood;

var bread = new Bread();
var sushi = new Sushi();

sushi instanceof Bread; // why true?
bread instanceof Sushi; // why true?

I want bread and sushi to both be instances of Food -- not each other.
How can I achieve JavaScript inheritance while maintaining the expected behavior for the constructor property as well as the instanceof operator?

A: Your only problem in your logic was setting the same object basicFood to both Bread.prototype and Sushi.prototype. Try to do something like this:
Bread.prototype = new Food();
Bread.prototype.constructor = Bread;

Sushi.prototype = new Food();
Sushi.prototype.constructor = Sushi;

Now the instanceof bread and sushi will be Food but the constructors will be Bread and Sushi for each of them in particular;

A: This is my personal solution, which I have developed from the combined wisdom nuggets of @thefourtheye, @FelixKling, @SeanKinsey, and even the antics of @helly0d:

Simplest Solution:
/** Food Class -- You can bite all foods **/
function Food(){ this.bites = 0 };
Food.prototype.bite = function(){ console.log("Yum!"); return this.bites += 1 };

/** All Foods inherit from basicFood **/
var basicFood = new Food();

/** Bread inherits from basicFood, and can go stale **/
function Bread(){
  Food.apply(this); // running food's constructor (defines bites)
  this.stale = false;
};
Bread.prototype = Object.create( basicFood );
Bread.prototype.constructor = Bread; // just conventional
Bread.prototype.goStale = function(){ return this.stale = true };

/** Sushi inherits from basicFood, and can be cooked **/
function Sushi(){
  Food.apply(this);
  this.raw = true;
};
Sushi.prototype = Object.create( basicFood );
Sushi.prototype.constructor = Sushi;
Sushi.prototype.cook = function(){ return this.raw = false };

Advanced Methodology:
It's better because it makes the constructor prototype property a non-enumerable.
/** My handy-dandy extend().to() function **/
function extend(source){
  return {to:function(Constructor){
    Constructor.prototype = Object.create(source);
    Object.defineProperty(Constructor.prototype, 'constructor', {
      enumerable:   false,
      configurable: false,
      writable:     false,
      value:        Constructor
    });
    return Constructor;
  }}
};

function Food(){ this.bites = 0 };
Food.prototype.bite = function(){ console.log("Yum!"); return this.bites += 1 };
var basicFood = new Food();

var Bread = extend(basicFood).to(function Bread(){
  Food.apply(this);
  this.stale = false;
});
Bread.prototype.goStale = function(){ return this.stale = true };

var Sushi = extend(basicFood).to(function Sushi(){
  Food.apply(this);
  this.raw = true;
});
Sushi.prototype.cook = function(){ return this.raw = false };

Both methodologies above yield the same test results:
var food  = new Food();
var bread = new Bread();
var sushi = new Sushi();

console.log( food instanceof Food );   // true
console.log( food instanceof Bread );  // false
console.log( food instanceof Sushi );  // false

console.log( bread instanceof Food );  // true
console.log( bread instanceof Bread ); // true
console.log( bread instanceof Sushi ); // false

console.log( sushi instanceof Food );  // true
console.log( sushi instanceof Bread ); // false
console.log( sushi instanceof Sushi ); // true

console.log( food.constructor );       // Food
console.log( bread.constructor );      // Bread
console.log( sushi.constructor );      // Sushi

A very special thanks to @FelixKling, whose experience helped hone my understanding in the chat outside of this thread -- also to @thefourtheye, who was the first to show me the correct way -- and also to @SeanKinsey, who highlighted the usefulness of being able to run the parent constructor within the context of the children.
I community wiki'd this answer -- please let me know or edit yourself if you find anything in this answer's code which is suspect :)

A: Lets examine your code a little bit.
function Food(){}
function Bread(){}
function Sushi(){}
var basicFood = new Food();
Bread.prototype = basicFood;
Sushi.prototype = basicFood;

Note: When you set the same object as the prototype of two objects, augmentation in one prototype, will reflect in the other prototype as well. For example,
Bread.prototype = basicFood;
Sushi.prototype = basicFood;
Bread.prototype.testFunction = function() {
    return true;
}
console.log(Sushi.prototype.testFunction()); // true

Lets get back to your questions.
var bread = reconstructify(new Bread(), Bread);
var sushi = reconstructify(new Sushi(), Sushi);
console.log(sushi instanceof Bread);    // Why true?
console.log(bread instanceof Sushi);    // Why true?

As per the instanceof docs from MDN,

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

So when we do something like
object1 instanceof object2

JavaScript will try to find if the prototype of the object2 is in the prototype chain of object1.
In this case, it will return true only when the Bread.prototype is in the prototype chain of sushi. We know that sushi is constructed from Sushi. So, it will take Sushi's prototype and check if it is equal to Bread's prototype. Since, they both point to the same basicFood object, that returns true. Same case for, bread instanceof Sushi as well.
So, the right way to inherit would be, like this
function Food()  {}
function Bread() {}
function Sushi() {}

Bread.prototype = Object.create(Food.prototype);
Bread.prototype.constructor = Bread;
Sushi.prototype = Object.create(Food.prototype);
Sushi.prototype.constructor = Sushi;

var bread = new Bread();
var sushi = new Sushi();

console.log(sushi instanceof Bread);  // false
console.log(bread instanceof Sushi);  // false
console.log(sushi.constructor);       // [Function: Sushi]
console.log(bread.constructor);       // [Function: Bread]
console.log(sushi instanceof Food);   // true
console.log(bread instanceof Food);   // true
console.log(sushi instanceof Sushi);  // true
console.log(bread instanceof Bread);  // true

A: What you are doing wrong is to reuse the basicFood object for multiple child 'classes'. Instead, new up a new one. That way, as you add members to the prototype (new instance of the parent), you're adding it to an instance that is not shared among other inheriting classes.
Now, there's one thing that your code is lacking, and that is constructors without side effects. Many constructors requires arguments, and will throw without them - but how can you construct a prototype for a new descending class without new'ing up a parent? Well, we're not actually interested in the parent function, only in the parents prototype. So what you can do is
function Parent() { /*some side effect or invariant */ }
Parent.prototype.foo = ...
function Child() { Parent.call(this); }

// the next few lines typically go into a utility function
function F() {} // a throw-away constructor
F.prototype = Parent.prototype; // borrow the real parent prototype
F.prototype.constructor = Parent; // yep, we're faking it
Child.prototype = new F(); // no side effects, but we have a valid prototype chain
Child.prototype.bar = ... // now continue adding to the new prototype


text:
Q: Models and Pivot Tables I have a custom written solution, which I'm porting over to Phalcon. This is my first run with Phalcon, and, though it's easy to use and well documented, I can't seem to find anything about linking models that are linked through a pivot table.
Here's the run down:
I have users. Users have stats. The two are linked with a table called users_stats. The table contains two columns: a user ID and a stat ID. I created a third class called Users_Stats to model after the pivot table.
User Model:
<?php
class Users extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany('stat_id', 'Users_Stats', 'user_id', array('foreignKey' => true));
    }
}

Stats Model:
<?php
class Stats extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->belongsTo('stat_id', 'Users_Stats', 'id');
    }
}

Users_Stats Model:
<?php
class Users_Stats extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany('user_id', 'Users', 'id');
        $this->hasMany('stat_id', 'Stats', 'id');
    }
}

I just want to be able to gather the stats based on users. I am not sure if all I'm missing is that each of the models needs to belong and hasMany (Stats has many User_Stats && User_Stats has many Stat; etc.). I know I'm missing something though.
Any help would be appreciated! Thanks!

A: Try this (source):
User Model:
<?php
class Users extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany(
            'stat_id',
            'Users_Stats',
            'user_id',
            array('foreignKey' => true)
        );
    }
}

Stats Model:
<?php
class Stats extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany('stat_id', 'Users_Stats', 'id');
    }
}

Users_Stats Model:
<?php
class Users_Stats extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->belongsTo('user_id', 'Users', 'id');
        $this->belongsTo('stat_id', 'Stats', 'id');
    }
}

User 1->many Users_Stats many<-1 Stats

A: After some playing around, and some great help from Nikolaos Dimopoulos, here's something things I found out.

*

*Classes can't have underscores.

*A lookup table's model must belong to each of the classes, as well as must have many of those same classes.

*Each class belonging to a lookup table's model must belong to the lookup table's model, as well as must have many of the lookup table's model.

User Model:
<?php
class Users extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->belongsTo('id', 'UserStats', 'user_id');

        $this->hasMany('user_id', 'UserStats', 'id');
    }
}

Stat Model:
<?php
class Stats extends \Phalcon\Mvc\Model {
    public function initialize() {
        $this->hasMany('stat_id', 'UserStats', 'id');

        $this->belongsTo('stat_id', 'UserStats', 'id');
    }
}

UserStats Model:
<?php
class UserStats extends \Phalcon\Mvc\Model {
    /**
     * Set database name as there is no UserStats DB
     *
     * @return string
     */
        public function getSource() {
        return 'user_stats';
    }

    public function initialize() {
        $this->belongsTo('user_id', 'Users', 'id');
        $this->belongsTo('stat_id', 'Stats', 'id');

        $this->hasMany('id', 'Users', 'user_id');
        $this->hasMany('id', 'Stats', 'stat_id');
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does anyone know how to format the Jquery Datepicker Does anyone know how to format the Jquery datepicker? I want it to display it like dd/mm/yyyy and that is the only way I want to display it, but at the moment it is displaying it like mm/dd/yyyy.
I tried this but it didn't work:
   $(function() {
        $( "#datepicker" ).datepicker({format("dd/mm/yyyy")});
    });

Does anyone have an idea?

A: The key you want is dateFormat:
$(function() {
  $( "#datepicker" ).datepicker({dateFormat: "dd/mm/yyyy"});
});


text:
Q: Propensity score matching: using alternative methods to create a distance measure I would like to use a greedy nearest neighbour method to do propensity score matching. Though I've little experience here, it seems that the distance measure used is generally a propensity score generated from a logistic regression. My question is: why logistic regression? Why not a random forest, SVM or another method? Is there some logic to suggest this would be unfruitful?
My plan is currently to use the MatchIt package in R and input my own distance measure calculated off the back of a random forest (you can input your own propensity score into the argument distance of the matchit function).
I'm deterred by the fact that modern propensity scoring packages such as
PSAboot don't have built in facility to do this for nearest neighbour methods. They do use party and rpart but only to match using strata (additionally they only use single trees).
I'm intrigued that methods with (typically) greater predictive power than logistic regression do not appear to be harnessed to create a 'better' propensity score for one-to-one matching. Is there someone out there that can shed some light on this?
Linked question: Propensity Score

A: Logistic regression is mostly likely used because of historic convenience, well studied convergence properties, relative data-frugality in comparison with other ML learners as well as being readily available pretty much everywhere. Also the resulting probabilities are usually "well-calibrated" out-of-the-box and this is helpful as it does not lead to under-/over-estimation of the probability to receive treatment as well as makes the occurrence of "extreme probabilities" (near 0 or 1) less likely. GBMs specifically, do not give very well-calibrated probabilities out of the box, I provided relevant material and commentary in this CV.SE tread on: Biased prediction (overestimation) for xgboost. Similarly simply using a tree would not be strongly advisable as it would lead to discontinuities and non-strictly monotonic probabilities that could mess up ordering because of the ties. Finally SVMs are a bit of red-herring as strictly speaking they do not provide probabilities natively but we need to use Platt scaling to get a similar output. This brings us to the last point: we can always post-process our output to make it better calibrated. The success of that step will be crucial but to avoid getting it "very wrong" logistic regression presents a safe bet. I recently read A tutorial on calibration measurements and calibration models for clinical prediction models by Huang et al. and I found it very informative if you want to explore that point further.


text:
Q: storing the difference of values as changes I want to store the differences and no differences in values into another dataframe when minusing one dataframe from the other.
For example, given this dataset:
> change
   water water2
1      1      1
2      1      2
3      1      2
4      1      1
5      2      2
6      6      4
7      5      4
8      7      5
9      8      9
10     5      5
11     4      2
12     5      5
13     3      3
14     3      3
15     0      2
16     0      0
17     0      0

when performing this calculation:
water2-water

When there is a negative difference, such that water > water2, assign the value -1. When there is a positive difference, such that water < water2 assign the value 1. Otherwise, if there's no difference, then assign the value 0.
Although, I prefer this to be done when the two dataframes are separate and not in a single data, such that:
y2010 <- water2
y2019 <- water

I'm working with a larger dataframe, and would prefer to perform a calculation like above and store those differences in a new dataframe.
reproducible example:
y2010 <- structure(list(water = c(1, 1, 1, 1, 2, 6, 5, 7, 8, 5, 4, 5,
3, 3, 0, 0, 0)), class = "data.frame", row.names = c(NA, -17L
))

y2019 <- structure(list(water2 = c(1, 2, 2, 1, 2, 4, 4, 5, 9, 5, 2, 5,
3, 3, 2, 0, 0)), class = "data.frame", row.names = c(NA, -17L
))

A: You can use the sign function. If the difference is positive it returns 1, it it's negative it returns -1, and if it's 0 it returns 0:
df <- data.frame(change = sign(y2019$water2 - y2010$water))

 change
1       0
2       1
3       1
4       0
5       0
6      -1
7      -1
8      -1
9       1
10      0
11     -1
12      0
13      0
14      0
15      1
16      0
17      0

A: You can also try:
#Code
ydiff <- y2019$water2-y2010$water
index <- y2010$water>y2019$water2
index2 <- y2010$water<y2019$water2
ydiff[index]<--1
ydiff[index2]<-1
ydiff[!index & !index2]<-0
#Dataframe
df3 <- data.frame(ydiff=ydiff)

Output:
df3
   ydiff
1      0
2      1
3      1
4      0
5      0
6     -1
7     -1
8     -1
9      1
10     0
11    -1
12     0
13     0
14     0
15     1
16     0
17     0


text:
Q: Passing data between an iOS app on different devices I'm looking for the best and efficient way to pass a Nested Array [[String]], from my app to the same app on another iPhone.
If let say for example, I have this Array saved on my app:
let array = [["John", "27", "First", "Castle"],["Tom", "25", "Second", "Boat"]]

I want to add a Share Button on my App that will allow this array to be shared via Bluetooth/Airdrop/Any Convenient Way between 2 iPhones.
Ideally click share, via airdrop, other user click accepts and clicks open with the app. And data is loaded. What is the best approach In order to achieve this. I looked at Share Extension and UIActivityViewController but can't see what are the differences about them and what is best for my case to simply send data and receive data from and to my app.

A: One option (and probably the easiest) is to use iCloud, specifically the NSUbiquitousKeyValueStore.
More information here :
https://developer.apple.com/documentation/foundation/nsubiquitouskeyvaluestore

A: Based on what you have said,
You could just use the UIActivityViewController to export your data to AirDrop (or etc)
and using the exported UTI, your app could open it once it detected.
for Sharing, you will have to use a custom data format (or file) and you can refer to this post, Sending custom data via UIActivityViewController
and for reading your custom file, here is a good tutorial of how to implement the Exported UTI https://www.raywenderlich.com/8413525-universal-type-identifiers-tutorial-for-ios-importing-and-exporting-app-data
Cheers,
Kel

A: use UIActivityViewController to export your data using AirDrop. You can read the same in your app on other phone when it detects the exported UTI.


text:
Q: Can the tehniques of higher level mathematics solve most of Olympiad level math problems through straighforward applications? Working through many Olympiad math problems(pre-undergrad) I've found that simple applications of undergrad math will solve many of them. Does this trend go on? Can it be that Putnam problems are straightforward applications of math studied at grad level?
For those who still may not know to what I'm referring to, take the example of solving euclidean geometrical problems using Cartesian geometry. In this case you could say that the Descartes's theory replaced the "tricky" challenge of finding the right combinations of axioms to solve a euclidean geometrical problem.
Are there nice counterexamples to this?
Ultimately, could theory building replace "tricky problem solving"?


text:
Q: Intersect with 2 EntityCollections via custom IEqualityComparer Not to repeat this question too much, but I already did a search and came up empty on a result.  So I have two EntityCollections of type T and I would like to find the common items in each.  The catch?  All fields except one must match.  So for example, if type T is a type CustomSet, and CustomSet includes fields F1, F2, F3 and a FK field OtherId, F1, F2 and F3 must match (they could be strings, ints, anything really) and the OtherId will never match.  My current implementation:
var intersections = source.Intersect(destination).ToList();

will never yield any results because that OtherId column will never match in any other collection, even though the fields F1, F2 and F3 may match.  So I'm proposing a custom implementation of IEqualityComparer which looks like this:
var intersections = source.Intersect(destination, new EntityCollectionComparer<T>()).ToList();

public class EntityCollectionComparer<T> : IEqualityComparer<T>
{
    #region IEqualityComparer<T> Members

    public bool Equals(T x, T y)
    {
        if (x.Equals(y))
            return true;
        else
            return false;
    }

    public int GetHashCode(T obj)
    {
        if (obj is CustomSet)
        {
            CustomSet temp = obj as CustomSet;

            return (temp.F1.GetHashCode() ^ temp.F2.GetHashCode() ^ temp.F3.GetHashCode());
        }
        return obj.GetHashCode();
    }

Now, I'm only testing this so the obj getting passed in is of type CustomSet, I will add the necessary if statements for my other types if I can get this to function properly.  I know that the Intersect extension uses the GetHashCode instead of the Equals to compare items which is why I really don't care what's in my equals as this class will never be called but for the Intersect extension on EntityCollections.  The thing is, this doesn't work.  On my test set, I know I have 28 items in my 'source' collection, and 28 items in my 'destination' collection, and all the fields match (obviously except for the OtherId field).  I stepped through the GetHashCode code as it looped 56 times and was able to match up hash codes on all 28 items from each set yet the 'intersections' yielded 0 count.  Is there something I'm doing wrong, or missing?  Thanks.
    }

A: This is your problem:

I know that the Intersect extension uses the GetHashCode instead of the Equals to compare items which is why I really don't care what's in my equals as this class will never be called but for the Intersect extension on EntityCollections.

That's simply not true. GetHashCode is used as a first "quick" way of bucketing values, but Equals will still be called for any items with the same hash, otherwise you can't know they're equal.
That's the way hash tables etc always work: the hashes should be different for unequal values where feasible for performance reasons, but are allowed to collide.


text:
Q: How to interact with a windows GUI through CLI to use custom parameters/arguments? I have a windows native application that I'm porting to a web based service and have no access to the code.
The windows application requires the user to input an executable file (into the windows application) then set parameters through it via the GUI (such as check-boxes) and obtain a different output based on the new parameters the windows application has set.

*

*User uploads Bob.exe via website with parameters

*Website pushes that to windows back-end with parameters

*Windows server processes the request (and Bob.exe) with the new parameters)

*Windows server uploads new, modified Bob.exe to front web UI.

*Completed.

The native windows application has no CLI functionality and it requires GUI interaction to set the parameters. We need to automate this function. in order to port the native windows application to a web based service.
How do we archive this? I did quite a bit of research and came up with nothing!
Thank you stackoverflow.

A: One possibility is installing a VNC server on the windows computer, and use ruby-vnc from your web server to connect and control input. You would ideally rely purely on keystrokes, but you can also control the pointer if needed. See this article for reference.


text:
Q: Cost (%CPU) around the same after denormalization? Using SQL Oracle. I create a query to find the total counts of orders for food.
EXPLAIN PLAN FOR
SELECT FOOD.F_NAME, COUNT(ORDERS.O_ORDERID)
FROM ORDERS
INNER JOIN CUSTOMER ON O_CUSTID = C_CUSTID
INNER JOIN FOOD ON C_FOODKEY = F_FOODKEY
GROUP BY FOOD.F_NAME;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

This returns cost (%CPU) of 3250 at row ID 0 in the plan table output.
I learnt that denormalization will speed up the query and reduce the cost. In this case, I copied the food name from my table FOOD to ORDERS to avoid the INNER JOIN. I should get a better cost (%CPU) usage.
I used this query next
EXPLAIN PLAN FOR
SELECT ORDERS.F_NAME, COUNT(ORDERS.O_ORDERID)
FROM ORDERS
GROUP BY ORDERS.F_NAME;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

The cost (%CPU) did not change much at all - the value is 3120 at row ID 0 in the plan table output.
Isn't denormalization and removal of the INNER JOIN suppose to improve my cost? The improvement is so insignificant in my case. What's the issue here?

A: This is too long for a comment.  You would have to study the execution plan.  However, joins on primary keys are often not particularly expensive.
What is expensive is the GROUP BY, because this requires moving data around.  You could try adding an index on F_NAME in the second query.
Your data model is also unusual.  It is unclear why a column called FOOD would be stored at the CUSTOMER level.

A: C_FOODKEY should be most likely O_FOODKEY to make sense
You do not need denormalization. What you are doing is - you explode all the rows by joins and then you group them together. Do not do this in the first place and try something like this
SELECT FOOD.F_NAME,
      (SELECT COUNT(*)
       FROM ORDERS
       WHERE O_FOODKEY = F_FOODKEY) AS fCount
FROM FOOD


text:
Q: How do I delete multiple rows I have a large file
A sample portion of my file

The goal is to create a separate file containing only the rows from the original file where type=1 (this is column 1). I have attached the code that I have, It's creating a completly blankfile which is not what I need  need. I feel like I am close but I am missing something.
import csv
with open('Test.csv') as f, open('Temp.csv', 'w') as f2:
reader = csv.reader(f)
writer = csv.writer(f2)
for row in reader:
    if row in reader:
        if Typedata not in row:
            writer.writerow(row)

A: Well, I'd like to use just str.split() as I'm not familiar with csv module.
Please check this code.
f = open('test.csv')
d = f.read()
f.close()
n = '\n'.join([x for x in d.splitlines() if x.split(',')[1] == '2'])

You can save n with a new file opened with 'w' option.

A: Problem is if row in reader which has to get all data from file to check if row is in reader. And later it has nothing to read, and nothing to write.
You can see it if you put print(row) between lines.
I use in_file = text.splitlines() only to test it. You should use open().
import csv

text = '''FKEY,TYPE,EFF,DATA
34787,2,Y,2022.03.20,1088825
14787,1,Y,2022.03.20,1088825
34787,2,Y,2022.03.20,1088825
14787,1,Y,2022.03.20,1088825
14787,1,Y,2022.03.20,1088825
34787,2,Y,2022.03.20,1088825
14787,1,Y,2022.03.20,1088825
14787,1,Y,2022.03.20,1088825'''

typedata = '2'

#with open('d:/Python/testfile.csv') as in_file, open('d:/Python/Data.csv', 'w') as out_file:
in_file = text.splitlines()
reader = csv.reader(in_file)
#writer = csv.writer(out_file)
for row in reader:
    if typedata not in row:
        print(row)
        #writer.writerow(row)

Result:
['FKEY', 'TYPE', 'EFF', 'DATA']
['14787', '1', 'Y', '2022.03.20', '1088825']
['14787', '1', 'Y', '2022.03.20', '1088825']
['14787', '1', 'Y', '2022.03.20', '1088825']
['14787', '1', 'Y', '2022.03.20', '1088825']
['14787', '1', 'Y', '2022.03.20', '1088825']


text:
Q: Catch all errors and display the type of error and message I'm trying to make a generic error handler, something like "when others" in Oracle. The examples that I can find all involve catching a specific expected error.
Try:
    some_function()
Except: #I don't know what error I'm getting
    show_me_error(type_of_error_and_message)

A: This is very well-documented. But may be you just need Sentry?
try:
    1/0
except Exception as e:
    print('%s' % type(e))

>>>
integer division or modulo by zero (<type 'exceptions.ZeroDivisionError'>)

A: To print the exception using Python 3, you'll want to use type(e). Example below:
try:
    1/0
except Exception as e:
    print(type(e))

>>> <class 'ZeroDivisionError'>

And then you can catch the exception with:
try:
    1/0
except ZeroDivisionError:
    print('Cannot divide by 0')
except Exception as e:
    print(type(e))

>>> Cannot divide by 0

A: import traceback

try:
    some_function()
except Exception as e:
    message = traceback.format_exc()
    print(message)

A: To print an exception in Python 3:
try:
    # your code
except Exception as e:
    print(e)


text:
Q: ANTLR4 parse rule to match open/close brackets I'm parsing a language that has a statement 'code' followed by '{', followed by a bunch of code that I have no interest in parsing, followed by '}'. I'd ideally like to have a rule like:
skip_code: 'code' '{' ~['}']* '}'
..which would simply skip ahead to the closing curly brace. The problem is that the code being skipped could itself have pairs of curly braces. So, what I essentially need to do is run a counter and increment on each '{' and decrement on each '}', and end the parse rule when the counter is back to 0.
What's the best way of doing this in ANTLR4? Should I skip off to a custom function when 'code' is detected and swallow up the tokens and run my counter, or is there some elegant way to express this in the grammar itself?
EDIT: Some sample code, as requested:
class foo;
  int m_bar;
  function foo_bar;
     print("hello world");
  endfunction
  code {
     // This is some C code
     void my_c_func() {
        printf("I have curly braces {} in a string!");
     }
  }
  function back_to_parsed_code;
  endfunction
endclass

A: I'd use something like:
skip_code: CODE_SYM block;
block: OPEN_CURLY (~CLOSE_CURLY | block)* CLOSE_CURLY;

CODE_SYM: 'code';
OPEN_CURLY: '{';
CLOSE_CURLY: '}';

A: I'd handle these code blocks in the lexer. A quick demo:
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.Token;

public class Main {

    public static void main(String[] args) {

        String source = "class foo;\n" +
                "  int m_bar;\n" +
                "  function foo_bar;\n" +
                "     print(\"hello world\");\n" +
                "  endfunction\n" +
                "  code {\n" +
                "     // This is some C code }}} \n" +
                "     void my_c_func() {\n" +
                "        printf(\"I have curly braces {} in a string!\");\n" +
                "     }\n" +
                "  }\n" +
                "  function back_to_parsed_code;\n" +
                "  endfunction\n" +
                "endclass";

        System.out.printf("Tokenizing:\n\n%s\n\n", source);

        DemoLexer lexer = new DemoLexer(new ANTLRInputStream(source));

        for (Token t : lexer.getAllTokens()){
            System.out.printf("%-20s '%s'\n",
                    DemoLexer.VOCABULARY.getSymbolicName(t.getType()),
                    t.getText().replaceAll("[\r\n]", "\\\\n")
            );
        }
    }
}

If you run the class above, the following will be printed:
Tokenizing:

class foo;
  int m_bar;
  function foo_bar;
     print("hello world");
  endfunction
  code {
     // This is some C code }}}
     void my_c_func() {
        printf("I have curly braces {} in a string!");
     }
  }
  function back_to_parsed_code;
  endfunction
endclass

ID                   'class'
ID                   'foo'
ANY                  ';'
ID                   'int'
ID                   'm_bar'
ANY                  ';'
ID                   'function'
ID                   'foo_bar'
ANY                  ';'
ID                   'print'
ANY                  '('
STRING               '"hello world"'
ANY                  ')'
ANY                  ';'
ID                   'endfunction'
ID                   'code'
BLOCK                '{\n     // This is some C code }}} \n     void my_c_func() {\n        printf("I have curly braces {} in a string!");\n     }\n  }'
ID                   'function'
ID                   'back_to_parsed_code'
ANY                  ';'
ID                   'endfunction'
ID                   'endclass'

A: You can use modes for your purpose. Take attention on two modes for CODE section. Yoy can not properly close CODE section with only one mode.
Lexer
lexer grammar Question_41355044Lexer;

CODE: 'code';
LCURLY: '{' -> pushMode(CODE_0);
WS:    [ \t\r\n] -> skip;

mode CODE_0;

CODE_0_LCURLY: '{' -> type(OTHER), pushMode(CODE_N);
RCURLY: '}' -> popMode;     // Close for LCURLY
CODE_0_OTHER: ~[{}]+ -> type(OTHER);

mode CODE_N;

CODE_N_LCURLY: '{' -> type(OTHER), pushMode(CODE_N);
CODE_N_RCURLY: '}' -> type(OTHER), popMode;
OTHER: ~[{}]+;

Parser
parser grammar Question_41355044Parser;

options { tokenVocab = Question_41355044Lexer; }

skip_code: 'code' LCURLY OTHER* RCURLY;

Input
code {
   // This is some C code
   void my_c_func() {
      printf("I have curly braces {} in a string!");
   }
}

Output tokens
CODE LCURLY({) OTHER(   // Th...) OTHER({) OTHER(      pr...)
OTHER({) OTHER(}) OTHER( in a st...) OTHER(}) OTHER() RCURLY(}) EOF

The same approach is used for ANTLR grammar parsing itself: https://github.com/antlr/grammars-v4/tree/master/antlr4
But runtime code LexerAdaptor.py is used there instead of two-level modes.


text:
Q: Embed google photo sphere in website i'm using code to embed google maps streetview photo in website. I take the code from the guide:
function initialize() {
panorama = new google.maps.StreetViewPanorama(
  document.getElementById('street-view'),
  {
    position: {lat: myLat, lng: myLng},
    pov: {heading: 165, pitch: 0},
    zoom: 1
  });
}

In place of myLat and myLng i put latitude and longitude that i take from photo url. Now this work for all type of photo that i found (streetview photo, "see inside" photo) except one "PHOTO SPHERE", i found that there are two type of photo sphere see here
Now, google recently update google maps and i think that "PHOTO SPHERE" are the new one, and "photo sphere" the oldest, but if i put latitude and longitude of the second, the code works, with the new one it doesn't work, how can i fix?
Example: if i take this url: http://www.google.com/maps/@0.5676777,37.527536,3a,75y,272.82h,93.02t/data=!3m5!1e1!3m3!1st4o4xj2l6HRAma2KT52brg!7i13312!8i6656 with 0.5676777 as myLat and 37.527536 as myLng, the photo is displayed in the website
if i take this: http://www.google.it/maps/@35.91208,14.498901,3a,89.9y,2.16h,87.34t/data=!3m8!1e1!3m6!1s-bkrM3HFU1vg%2FVhjysw39NSI%2FAAAAAAAAAPk%2F2PLOjiwhbh4!2e4!3e11!6s%2F%2Flh3.googleusercontent.com%2F-bkrM3HFU1vg%2FVhjysw39NSI%2FAAAAAAAAAPk%2F2PLOjiwhbh4%2Fw203-h101-n-k-no%2F!7i10000!8i5000
35.91208: myLat, 14.498901: myLng
The code not works and no photo is displayed

<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Street View</title>


text:
Q: Lie algebras to classify Lie groups What does the classification of Complex Semi-simple Lie algebras buy us in terms of classifying Lie groups? Certainly it classifies complex semi-simple lie groups but can we get any better? I know we can take compact real forms of the semi-simple algebras and there are several theorems about topological similarities for Lie groups with the same Lie algebra. How far can we take this? What is the biggest class of Lie groups we can rope in by this method?

A: Here is an answer from a different point of view : every connected Lie group is almost a semidirect product of a semisimple Lie group (Levi factor) and a connected solvable normal Lie subgroup (its solvalble radical). See Onishchik and Vinberg's Lie Groups and Lie Algebras III for a more precise statement. In that sense, the classification of real Lie groups is reduced to that of semisimple and solvable ones. Although somewhat crude, this classification helps for example in the study of unitary representations. (See papers by M. Duflo on the orbit method.)
Another subtle issue with the classification of semisimple Lie groups is that over
$\mathbb C$, the simply connected group corresponding to a semisimple Lie algebra is always linear, whereas over $\mathbb R$, this is not the case. For example, the simply connected Lie group corresponding to $\mathfrak{sl}_2(\mathbb C)$ is $\mathrm{SL}_2(\mathbb C)$, but the simply connected Lie group
corresponding to $\mathfrak{sl}_2(\mathbb R)$ is an infinite-sheeted covering of $\mathrm{SL}_2(\mathbb R)$. In other words, $\pi_1(\mathrm{SL}_2(\mathbb C))=\{e\}$ whereas
$\pi_1(\mathrm{SL}_2(\mathbb R))=\mathbb Z$. (Here $\pi_1$ means the first fundamental group.)

A: The point is, if $G$ is a real semisimple Lie group, then its Lie algebra $\mathfrak{g}$ is also semisimple and so is the complexification $\mathfrak{g} \otimes \mathbb{C}$.  Or, given a complex $\mathfrak{g}$, any real form  $\mathfrak{g}_\mathbb{R}$ (meaning, a pre-complexification) integrates to a real semisimple Lie group.  The real forms have been classified and they are described by Satake diagrams, which are Dynkin diagrams with an extra decoration to describe the real form.  So together with finding the real forms, the complex classification "buys" you everything about semi-simple real Lie groups.  The great Élie Cartan not only reorganized the complex classification, he also did the real classification.
See also the Wikipedia page for real forms.  As it points out, there are always two special real forms, the compact form and the completely split form, and often also others.


text:
Q: Return JavaScript Function Value outside the scope Im trying to get a function returned value out from it.
function startFilter(callback) {
    $.getJSON('services/hoteljson.php', callback);
}
var data =  startFilter(function(json) {
    json= jQuery.grep(json, function(element, index){
        var productNameSearch = new RegExp('Hot' , "gi");
        return element.prodname.match(productNameSearch);
    });
    return json;
});

I've tired few options but nothing seems to be wokring
i wanted to use data anywhere i wish.
what will be the best method to do so?
Review:
The duplicate question doesn't give the answer what i seek, just some showoff stuff.


text:
Q: MySQL One result from two queries in same table I'm having a little trouble getting my head around this. I have one table of transactions containing both income and expenses and can happily use the following queries to get monthly summaries.
SELECT month(`Transaction Date`) as month, ROUND(SUM(`Credit` - `Debit`),2) as revenue
FROM `TABLE 1` WHERE `Account Group` = 'Income' AND `Transaction Date` BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY month

Gives:

month
revenue

1
100.00

2
50.00

3
400.00

etc
etc

And
 SELECT month(`Transaction Date`) as month, ROUND(SUM(`Credit` - `Debit`),2) as cost
    FROM `TABLE 1`
    WHERE `Account Type` = 'cost' AND `Transaction Date` BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY month

Gives:

month
cost

1
53.00

2
20.00

3
9.99

etc
etc

I can't figure out a query to combine the data into one result as below. I've used JOINs in the past but this is all in one table.

month
cost
revenue

1
53.00
100.00

2
20.00
50.00

3
9.99
400.00

etc
etc
etc

Any help would be greatly appreciated. Many thanks.

A: Try this:
SELECT
    month(`Transaction Date`) as month
    , ROUND(SUM(CASE
                   WHEN `Account Group` = 'Income' THEN `Credit` - `Debit`
                   ELSE 0
                END),2) as revenue
    , ROUND(SUM(CASE
                   WHEN `Account Type` = 'cost' THEN `Credit` - `Debit`
                   ELSE 0
                END),2) as cost
FROM `TABLE 1`
WHERE (`Account Group` = 'Income' OR  `Account Type` = 'cost')
     AND `Transaction Date` BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY month

A: You can use the conditional aggregation but in better way as follows:
SELECT month(`Transaction Date`) as month,
       ROUND(SUM(CASE WHEN `Account Group` = 'Income' THEN `Credit` - `Debit` END),2) as revenue,
       ROUND(SUM(CASE WHEN `Account Type` = 'cost' THEN `Credit` - `Debit` END),2) as cost
FROM `TABLE 1`
WHERE `Account Group` IN ('Income','cost')
 AND `Transaction Date` BETWEEN '2019-01-01' AND '2019-12-31'
GROUP BY month


text:
Q: Vim and Xdebug issue Ok so I am having an issue.  I am on an old system ubuntu 9.04 so I don't have the ability to do an apt-get on vim, so I went to the vim site and downloaded the latest version of vim.
Same thing goes for Xdebug, it is all installed and it shows up in the output of my phpinfo() call so that is all good, have the debugger.py and debuger.vim in my /etc/vim/plugin folder, did have it in .vim/plugin but that wasn't working either.
So I run the vim command in my terminal with the file name I want to debug, vim opens it fine but when I open it in the browser and then hit 5 on vim, it doesn't do anything.  No messages what so ever from vim, I added feature&XDEBUG_SESSION_START=1 to my url and tried again, still nothing from vim at all, any ideas what the issue could be?
UPDATE
So I copied these files into /usr/local/vim/vim64/plugin directory since thats where all the plugins seem to be stored on my system and i am now getting this error when starting Vim.  I am using vim 6.4, maybe the this plugin is for an older version?
Error detected while processing /usr/local/share/vim/vim64/plugin/debugger.vim:
line    1:
E488: Trailing characters: # -*- c--oding: ko_KR.UTF-8 -*-
line    2:
E488: Trailing characters: # remote PHP debugger : remote debugger interface to DBGp protocol
  1
line    4:
E488: Trailing characters: # Copyright (c) 2003-2006 ActiveState Software Inc.
  1
line    6:
E488: Trailing characters: # The MIT License
  1
line    8:
E488: Trailing characters: # Permission is hereby granted, free of charge, to any person obtaining
line    9:
E488: Trailing characters: # a copy of this software and associated documentation files
line   10:
E488: Trailing characters: # (the
line   11:
E488: Trailing characters: # including without limitation the rights to use, copy, modify,
line   12:
E488: Trailing characters: # merge, publish, distribute, sublicense, and/or sell copies of the
line   13:
E488: Trailing characters: # Software, and to permit persons to whom the Software is furnished
line   14:
E488: Trailing characters: # to do so, subject to the following conditions:
  1
line   16:
E488: Trailing characters: # The above copyright notice and this permission notice shall be included
line   17:
E488: Trailing characters: # in all copies or substantial portions of the Software.
  1
line   19:
E488: Trailing characters: # THE SOFTWARE IS PROVIDED
line   20:
E488: Trailing characters: # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
line   21:
E488: Trailing characters: # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
line   22:
E488: Trailing characters: # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
line   23:
E488: Trailing characters: # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
line   24:
E488: Trailing characters: # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
line   25:
E488: Trailing characters: # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  1
  1
line   28:
E488: Trailing characters: # Authors:
line   29:
E488: Trailing characters: #    Seung Woo Shin <segv <at> sayclub.com>
line   30:
E488: Trailing characters: #    Sam Ghods <sam <at> box.net>
line   33:
E492: Not an editor command: ^Idebugger.py -- DBGp client: a remote debugger interface to DBGp protocol
line   35:
E492: Not an editor command:     Usage:
line   36:
E492: Not an editor command:         Use with the debugger.vim vim plugin
line   38:
E492: Not an editor command:     This debugger is designed to be used with debugger.vim,
line   39:
E488: Trailing characters: ^Ia vim plugin which provides a full debugging enviroVim:     Caught deadly signal SEGV

Vim: Finished.
Segmentation fault

A: It looks like your old Vim 6.4 is sourcing the plugin/debugger.py file, as it complains about the Python # comments, instead of feeding this to the Python interpreter. The XDebug plugin page lists the minimum required Vim version as 7.0; if that is right, you probably have to upgrade your Vim version (which would be beneficial for many other reasons, too, and compiling your own Vim version isn't so difficult on Ubuntu), or heavily hack the plugin (e.g. try moving the debugger.py file elsewhere and adapt the paths in debugger.vim).


text:
Q: H.264 Encoding by copying RGB buffer into Media Buffer has alignment issues I'm working on real-time video Streaming using hardware accelerated h.264 encoding, decoding and I'm able to make it work using Windows Media Foundation .
I created IMFSample from IMFMediaBuffer which I got from ID3D11Texture2D using MFCreateDXGISurfaceBuffer and encoded to h.264 using Hardware MFT and it rendered properly after decoding.
The Goal is to get RGB buffer using BitBlt and create an IMFSample to provide as input to h.264 encoder.
Now, The issue is when I try to create IMFMediaBuffer by storing RGB buffer in it using GetDIBits and create IMFSample to provide h.264 encoder, I am getting the below image rendered after decoding.

I also tried an approach to create IMFMediaBuffer by copying Data Buffer from ID3D11Texture2D using D3D11_MAPPED_SUBRESOURCE and copy to IMFMediaBuffer instead of MFCreateDXGISurfaceBuffer and created IMFSample. It gave the same result from the image.
I cannot understand why h.264 encoder has no problems encoding when getting Media Buffer using MFCreateDXGISurfaceBuffer directly from Texture and has problems when copying the RGB buffer into Media Buffer using both BitBlt and D3D11_MAPPED_SUBRESOURCE.
Any help to solve this issue is appreciated. Thanks in advance.

A: This is a pretty typical problem, which you have not supplied with sufficient detail to get a good hint. The problem is essentially this: you did something wrong with data on video encoder input (or even earlier) and you are encoding wrong data. The encoder accepts the data because it is formally correct, in terms of having expected properties: resolution, media type, texture format, and it does not validate the pixel data itself. You have encoder output compliant to H.264 specification and you can play the video as the encoder correctly encoded wrong input data. Posted code could have been of some help.


text:
Q: Caused by: java.lang.ClassNotFoundException: scala.ScalaObject I am running a spark code and facing below issue during running job in eclipse.
Exception in thread "main" java.lang.NoClassDefFoundError: scala/ScalaObject
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.apache.spark.serializer.SerializerManager.<init>   (SerializerManager.scala:36)
at org.apache.spark.SparkEnv$.create(SparkEnv.scala:266)
at org.apache.spark.SparkEnv$.createDriverEnv(SparkEnv.scala:165)
at org.apache.spark.SparkContext.createSparkEnv(SparkContext.scala:259)
at org.apache.spark.SparkContext.<init>(SparkContext.scala:423)
at org.apache.spark.api.java.JavaSparkContext.<init>(JavaSparkContext.scala:58)
at GroupBy.SparkDataSets.main(SparkDataSets.java:70)
Caused by: java.lang.ClassNotFoundException: scala.ScalaObject
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 19 more

I have spark version 2.0.0 and i am using scala-library version is 2.11.8 .
Please see the jar files included in eclipse.
jars
Please find the code below that i am running in eclipse.
public class SparkDataSets {
private static SparkConf conf;
private static JavaSparkContext sc;
private static SQLContext sqlsc;
private static void run(String path) {
    JavaRDD<Employee> rdd = sc.textFile(path).map((t) -> {
        String[] values = t.split(",", -1);
        Employee emp = new Employee();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-yy");
        Date startdate = dateFormat.parse(values[1]);
        Date Enddate = dateFormat.parse(values[5]);
        long start = startdate.getTime();
        long end = Enddate.getTime();
        emp.setId(Integer.parseInt(values[0]));
        emp.setStart_Date(new Timestamp(start));
        emp.setFirstName(values[2]);
        emp.setLastName(values[3]);
        emp.setGender(values[4]);
        emp.setEndDate(new Timestamp(end));
        emp.setDepartMent_id(values[6]);
        return emp;
    });
    Dataset<Employee> set = sqlsc.createDataset(rdd.rdd(),Encoders.bean(Employee.class));
    set.createOrReplaceTempView("Employee");
    Dataset<Row> filterset = sqlsc.sql("select * from Employee where lastName='Facello'");
    filterset.show();
    Dataset<Employee> bean = sqlsc.createDataset(rdd.rdd(),Encoders.bean(Employee.class));
    bean.show();
}
public static void main(String... args) {
    conf = new SparkConf().setMaster("local").setAppName("GroupBy");
    sc = new JavaSparkContext(conf);
    sqlsc = new SQLContext(sc);
    run("data/input/Employee.txt");
}

}

I have added all the required versions of Spark and scala with the exactly same in eclipse still facing the issue.Let me know the exact version of scala which i can use to resolve this.


text:
Q: How to get the price of all simple products assigned to configurable products in magento 2 listpage? I referred the link :
stackexchange but I am not getting any results.
I have used following code in Magento_Catalog/templates/product/list.phtml
$configurableOptions = $_product->getConfigurableAttributesData();

    foreach ($configurableOptions['matrix'] as $option) {
       echo $option['price'];
    }

I got an error like :
Warning: Invalid argument supplied for foreach() in Magento_Catalog/templates/product/list.phtml

A: try this
$_children = $_product->getTypeInstance()->getUsedProducts($_product);
                    foreach ($_children as $child){
                        echo $child->getPrice();
                    }


text:
Q: Zip my folder but do not overwrite existing one in C# I am using third party FastZip to zip my folder, when i zip new folder with already existing file let say abc.zip, Fast Zip overwite this old abc.zip, delete old files and zip only new files.
Any one knows the solution.
EDIT-> I managed to do that by myself, Here is a solution if some one need.
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;

string zipfilename = "abc.zip"; // Your required zip file
string fdrname = "abc";

if (!File.Exists(zipfilename)) // If file zip does not exists
{
    Directory.CreateDirectory(fdrname); // Create folder with same name
    FastZip fz = new FastZip();         // using FastZip dll
    fz.CreateZip(zipfilename, fdrname, true, null); // create zip file (ofcourse its empty)
}
if (Directory.Exists(fdrname)) // delete folder which you have created (optional)
    Directory.Delete(fdrname);

    try
    {
        ZipFile zip = new ZipFile(zipfilename); // by Using ZipFile dll
        zip.BeginUpdate();
        zip.Add(pathtofile); // add file path which you want to zip in abc.zip
        zip.CommitUpdate();
        zip.Close();
    }
    catch (Exception e)
    {
        Console.WriteLine((e.ToString());
    }
}

A: You can always manually test for file existence before zipping:
if (!File.Exists(filename))
    fastZip.CreateZip(filename, @"C:\SourceDirectory", recurse, filter);
else
    //exception or message


text:
Q: Flashplugin-installer errors I have installed flashplugin-installer through Synaptic and before have tried sudo apt-get install flashplugin-installer in LXTerminal, and whenever I load Google Chrome/Chromium and navigate to a site with ANYTHING flash I get an error message saying "Could not load Shockwave Flash." Any help? (I'm running Lubuntu 12.10 when I get these error messages. They didn't appear for me when using Ubuntu 12.04 LTS before I switched to Lubuntu for performance reasons.)

A: You may try: install FIREFOX browser and FLASH-AID plugin. Then run Flash-aid and it will install the software. Hope this works.


text:
Q: Find minimum of single-variable function I have a Matlab question:
What expression is calculated by the following command in Matlab?
Code:
fminbnd(@(x) (sin(x).^2-1),0,pi)
Minimum of:
(a) f(x)=1-sin x^2 or (b)1-sin^2x.
I am not really sure. I have pluged the x values into both of my options and the one that returns the matching y value is the correct function. BUt for both equations i get 1, so i don't know what is right a) or b)?

A: Function evaluations have higher precedence than raising to a power. So
sin(x).^2-1

is the same as
(sin(x)).^2-1

I.e., you do the sin(x) first, then square this result.
Which is not the same as
sin(x.^2)-1


text:
Q: SQL Query to Delete Text Within a Cell That Begins and Ends with Specific Text I need to delete data from a column that begins and ends with specific text.
I have 800 records, the data between the text I want to remove is different in all the 800 records.
For example:
This house is big /br/br link img src house.png /br
I want to delete everything between the /br/br and the /br.
How would I write this query?

A: Try something like this:
update t
set s = concat (
        substr(s, 1, locate('/br/br', s) + 5),
        substr(s, length(s) - locate('rb/', reverse(s)) - 1)
        )
where s like '%/br/br%br%';

Used locate to find the index of the point to find substrings and then use concat to join the desired parts together.
It deletes everything between first /br/br and last /br


text:
Q: Performance Testing with pytest fixtures- yielf related error I am trying to implement a very basic simple performance testing using pytest, and modular fixtures.
I already have a fixture for time tracking:
@pytest.fixture
def time_tracker():
    tick = datetime.now()
    yield
    tock = datetime.now()
    diff = tock - tick
    print(f"\n runtime: {diff.total_seconds()}")
    return diff

I tried doing something like:
@pytest.fixture
def performance_testing(time_tracking):
    diff = time_tracking
    if diff > timedelta(seconds=30):
       raise ValueError("test is taking too long")

But I am having problems with the yield.
I think that when I am yielding from time_tracker then context goes back to the calling function which is performance_testing and not the test function itself.
My error:
@pytest.fixture
def performance_testing(time_tracker):
    diff = time_tracker

>       if diff > timedelta(seconds=30):
E       TypeError: '>' not supported between instances of 'NoneType' and 'datetime.timedelta'

I know I can easly implemnt this with duplicating the code and adding my if diff > timedelta(30) logic, however I want to use modular fixtures.
Is this possible? if not, is there an elegant "pytest" way of doing this?
Also, I am not intersted in downloading pytest plugins.

A: yield is like return and can take an argument. Just write yield tick instead of just yield.


text:
Q: Disagreement between OpenSSL asn1parse and asn1Editor I am trying to implement a SCEP service, my experience with cryptography++ is quite limited so this has been an uphill battle. Currently I am accepting a certificate request from a client, and I am working de interpret the request. The certificate request should be in the form of a CMS/PKCS#7, however I am having great difficulties interpreting it:

*

*When using the ASN.1 edtor at http://lipingshare.com/Asn1Editor/ I just get "Failed to read data".

*When using 'openssl asn1parse -inform DER < bytes' on Linux I get something which seems quite sensible. The application should run on Windows .NET so the detr into linux was mainly one of despair.

*Trying to decode in .NET fails:
byte[] data = Convert.FromBase64String( input_message );
SignedCms signerInfo = new SignedCms();
EnvelopedCms contentInfo = new EnvelopedCms();
signerInfo.decode(data);
contentInfo.Decode( signerInfo.ContentInfo.Content );
contentInfo.Decrypt();[*]
[*]: This fails with a CryptographicException and message: "Cannot find object or property".

*Trying to decode with BouncyCastle .NET classes fails:
byte[] data = Convert.FromBase64String( input_message );
Org.BouncyCastle.Cms.CmsSignedData signedData = new CmsDignedData( data );
Org.BouncyCastle.Cms.CmsEnvelopedData ed = new CmsEnvelopedData( signedD.ContentInfo);[*]
[*] This fails with "ArgumentException" and message: "unknown object in factor: BerTaggedObject".
I realize this does not satisfy StackOverflows requirements of a clear and concise question; but I guess that just reflects the lack of clearness on my side :-( Basically I would be very grateful for any tips on how to to interpret a SCEP message (CMS/PKCS#7) in .NET, using either standard Windows classes or the BouncyCastle API; but to conclude with some concrete questions:

*

*Can I infer something from the fact that asn1parse on Linux seems to handle my message, whereas the Lipingshare Asn.1 editor fails?

*The SCEP standards says that the CMS message should be BER encoded; whereas the asn1parse programs takes a '-inform DER' switch (and still works...), and the BouncyCastle class seems to complain about a BERTaggedObject.

Grateful for any ideas, thoughts or suggestions.
Joakim


text:
Q: Group action under homotopy equivalence. Suppose $\bar{X}$ is homotopy equivalent to $\bar{Y}$. Suppose the map $f_1:\bar{X}\rightarrow \bar{Y}$ and $f_2:\bar{Y}\rightarrow \bar{X}$ gives the homotopy equivalence. Suppose $G$ is a group acting discontinuously on $\bar{Y}$ and the quotient space is $Y$. Now we can define the action of $G$ on $\bar{X}$ as follows. Let $x\in \bar{X}.$ Then for $g\in G$ define $g(x)=f_2gf_1(x).$ Suppose under this action of $G$ on $\bar{X}$ the quotient space is $X$.
Is this action will be discontinuous?
If so:
Is $X$ is homotopy equivalent to Y.
If not
Is there any condition (like properly discontinuous action) of the action will ensure the above facts to be true?

A: This is not a group action.  In particular, $f_2f_1(x)$ need not equal $x$, so the identity element of $G$ doesn't act trivially.  Indeed, the only obvious case where you get an action is if $f_1$ and $f_2$ are an inverse pair of homeomorphisms.
Instead, the homotopy equivlance induces a group action on $\overline{X}$ up to homotopy.  That is, each element of $G$ corresponds to a homotopy class of maps $\overline{X}\to\overline{X}$.  Unfortunately, this isn't good enough to let you construct a quotient $X$.


text:
Q: Code inspection highlight: cannot set different highlight style for Info and Weak Warning severities In Android Studio 2.1.2 I'm having trouble setting the highlight style for the Info severity level (as determined by my code inspections profile). It shows up using the Weak Warning style instead.
I followed the instructions from the official docs here but I don't see an entry for Info, only for Weak Warning. It feels like a bug in the IDE because when I click on the "Edit|Colors & Fonts" button, I'm taken to the last item I had selected in that section rather than to the correct item, ie "Info" (or perhaps that's because no such "Info" item exists).
I haven't been able to figure out how to add a new item for "Info" to the list under Colors & Fonts either.

A: The INFO severity is deprecated as stated in a comment to the issue IDEA-137974 Cannot change the color of the "info" severity:

"INFO" level is deprecated since 2011 but it seems users don't know
  about it. I removed this severity from settings (will be available in
  2016.3). If you want to have an additional severity you can always create it.
BTW in 2016.3 you will have INFORMATION severity. Particularly, this
  severity has no highlighting.

So you can create your own severity with your favorite colors via Severity -> Edit severities... and use this one instead.


text:
Q: Arduino 4N35 input I trying to interface the arduino digital pins through an optoconnector attached to an LED of a consumer electronic device. I have bought the recommended component for this.
Before I would even get to the point of hooking up to the device's led to the 4N35 I already have a serious problem.
I tried to emulate the device here with standard +5V LAB supply.
Once the 4N35 opens it gets stuck in that state, even after removing the external power the arduinos pin is still pulled down to the GND like the switch would be closed.
Obviously I could use relays for this input detection but I rather not since the device will be usually providing +5V (aka being on).
Any help appreciated!

A: No it was NOT correct, @transistor was absolutely right with his answer.

With this reverse schematic the arduino is pulled to low constantly by the 10k unless the opto connector is on and closes the switch.
Whoever made that first wrong circuit diagram it should be removed from google because it can mislead a lot of people.
Unfortunately regardless all the hassle to get this to work, when it is connected to the actual consumer device it makes that circuit malfunction having the 2N35 opto attached to the LED inputs.
When I connect it (with or without the 330 Ohm resistor on 1-2 legs) it causes the device to blink once then not to react to anything (like the power on button) until I remove the attached 2N35.
Maybe it takes up too much load and the circuit misbehaves. Can somebody share ideas regarding this? Is there a component similar to the 2N35 with lower resistance which will be invisible for the host device and does not cause it to malfunction? I assume that is the problem here.
One ugly hack I could do for this is to glue a foto-resistor in front of the LED but since this is a multicolor LED in the consumer device it could not determine whether it is Green or Red.


text:
Q: Scala Webserver get URL from InputStream I am writing a small HTTP Server in Scala.
I have the following code to read from the Sockets Inputstream
val input = Source.fromInputStream(s.getInputStream).mkString

unfortunately this blocks my thread when I try to access the server with wget localhost:8008 because I think that the stream is not getting closed.
How can I extract the URL from the HTTP Request that f.e. wget sends to the server from the socket inputstream correctly and without blocking the whole thread?

A: For now I am using this solution
   var list: List[Byte] = Nil

   while(s.getInputStream.available() != 0){
     list = s.getInputStream.read.toByte  :: list
   }

   val byteArray = list.reverse.toArray

   val inputString = new String(byteArray)

If somebody has a better answer please post.

A: This one works for me very well:
val client = socket
val in = new BufferedReader(new InputStreamReader(client.getInputStream)).readLine
println("Server received:" + in)


text:
Q: CONCATENATE to ignore blank results if one cell is missing How can I do a Concatenate/Textjoin to output blank results if just one cell value is missing (I need all cell values to be present)? This condition goes for N1388, P1388, K1388, and L1388.
=CONCATENATE( "Valued Customer, your Map(s) request is ready at this link. ",
              "Please retrieve within 7 days. ",
              N1388, " ",
              "map(s) will be billed for ",
              P1388, ". "
              K1388, " ",
              L1388, ". ",
              "Please contact a service planner if necessary."
)

A: This formula should do what you require, I have also tidied up some of the unnecessary text joins used for the spaces.
=IF(OR(ISBLANK(N1388),ISBLANK(P1388),ISBLANK(K1388),ISBLANK(L1388)),"",CONCATENATE("Valued Customer, your Map(s) request is ready at this link. Please retrieve within 7 days. ",N1388," map(s) will be billed for ",P1388,". ",K1388," ",L1388,". Please contact a service planner if necessary."))

A: =IF(OR(N1388="",P1388="",K1388="",L1388=""),"",CONCATENATE("Valued Customer, your Map(s) request is ready at this link. Please retrieve within 7 days. ",N1388," map(s) will be billed for ",P1388,". ",K1388," ",L1388,". Please contact an service planner if necessary.")

A: Similar to @5202456's answer, but mine will check for blanks which are a result of formulas. It is also slightly more efficient as the OR does not short circuit and all the conditions will be checked, even if the first one returns true.
=IF(N1388="",""
    IF(P1388="","",
        IF(K1388="","",
            IF(L1388="","",
                CONCATENATE( "Valued Customer, your Map(s) request is ready at this link. ",
                              "Please retrieve within 7 days. ",
                              N1388, " ",
                              "map(s) will be billed for ",
                              P1388, ". "
                              K1388, " ",
                              L1388, ". ",
                              "Please contact a service planner if necessary."
                )
            )
        )
    )
)


text:
Q: WordPress paginate_links() Customization I'm using WordPress paginate_links() function, which is working, however I'd like to slightly later the html that is output.
Heres whats currently being displayed:
« Previous
1
2
3
4
5
Next »

The php:
<?php

$pages = array(

'show_all' => true,
'prev_text' => __('« Previous'),
'next_text' => __('Next »'),
 );

 echo paginate_links($pages);

?>

What I'm trying to achieve is to have the page number links wrapped inside of a div like so:
« Previous

  1
  2
  3
  4
  5

Next »

This way I can center the page numbers using margin: 0 auto;
Any help would be appreciated.

A: Get your data with type = array. You will get an array of the links and you can do the html markup yourself.

    $pages = array(
    'type' => 'array'

     );

     $links = paginate_links($pages);

     foreach($links as $link){
        // Render the HTML here
     }


text:
Q: how can reference from one Eclipse project to another when using cx_freeze I have a problem
I have eclipse work space it's contain 4project each project reference from anther project. When I need to make an executable file using cx_Freeze, it can't import the other referenced project to it?
thanks
I tried this code:
base = None
from cx_Freeze import setup, Executable
if sys.platform == "win32":
    base = "Win32GUI"
exe = Executable(
    script="MyForm.py",
     base="Win32GUI",packages=['QtCore', 'QtGui',     'QtSvg','tkinter','time','os','cls_MyForm','threading','sys','DAL','FS_Watch_Collection'],
     compress=False, copyDependentFiles=False)

setup(
    name = "First Version of File Watcher",
    version = "1",
    description = "File Watcher Program",
    executables = [exe])

and this code:
from cx_Freeze import setup, Executable
#http://www.youtube.com/watch?v=XHcDHSWRCRQ
#http://www.python-forum.org/pythonforum/viewtopic.php?f=4&t=34501&hilit=cxfreeze
includefiles = ['README.txt', 'CHANGELOG.txt']
includes = []
excludes = ['tkinter']
packages = ['pk_LocalStore','QtCore', 'QtGui', 'QtSvg','time','os','threading','sys']

setup(
    name = 'First Version of File Watcher',
    version = '0.1',
    description = 'File Watcher Program',
    author = 'ITE CO',
    author_email = 'info@from-masr.com',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
    executables = [Executable('MyForm.py')]
)

but it's not working correctly


text:
Q: Why doesn't this pymongo subdocument find work? I'm looking at using mongodb and so far most things that I've tried work. But I don't know why this find doesn't work.
col = db.create_collection("test")
x = col.insert_many([
    {"item": "journal", "qty": 25, "size": {"h": 14, "w": 21, "uom": "cm"}, "status": "A"},
    {"item": "notebook", "qty": 50, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "A"},
    {"item": "paper", "qty": 100, "size": {"h": 8.5, "w": 11, "uom": "in"}, "status": "D"},
    {"item": "planner", "qty": 75, "size": {"h": 22.85, "w": 30, "uom": "cm"}, "status": "D"},
    {"item": "postcard", "qty": 45, "size": {"h": 10, "w": 15.25, "uom": "cm"}, "status": "A"}
])

cursor = col.find({"size": {"h": 14, "w": 21, "uom": "cm"}})
if cursor.retrieved == 0:
    print("found nothing")          # <<<<<<<<< prints this

A: As explained into docs into section Match an Embedded/Nested Document:

Equality matches on the whole embedded document require an exact match of the specified  document, including the field order.

So, you have to set the object into find stage in the same order that exists into DB.
I really don't know if keys into objects follows an strict order (alphabetically or whatever) but using this query almost everything output the result. Not always so I think there is a "random" (or not possible to handle) concept to store data -at least into mongo playground-.
By the way, the correct way to ensure results is to use dot notation so this query will always works ok.
coll.find({
  "size.h": 14,
  "size.w": 21,
  "size.uom": "cm"
})

A: I was thinking that cursor.retrieved was non zero if it found something. I guess not. I found that this works:
lst = list(cursor)
print(lst)

cursor.rewind()
print(list(cursor))

if len(lst) != 0:
    for d in lst:
        print(d)


text:
Q: How to set device volume with Slider in Flutter As the title says, how to adjust device volume in Flutter? I want to use a Slider to adjust the device volume, but I didn't find a way.

A: I put my simple code here.
I tested on a pixel 3a API 27.(According to the package, 'No IOS Implementation yet.')
Later, I am going to changed the fixed max-value of slider with a value gotten from Volume.getMaxVol, and initial slider value with Volume.getVol.
import 'package:volume/volume.dart';
...

class _PlayerState extends State<Player> {
    double _sliderValue = 0.0;
    int maxVol, currentVol;

    @override
    void initState() {
        super.initState();
        initPlatformState();
    }

    Future<void> initPlatformState() async {
        await Volume.controlVolume(AudioManager.STREAM_MUSIC); // you can change which volume you want to change.
    }

    updateVolumes() async {
        maxVol = await Volume.getMaxVol;
        currentVol = await Volume.getVol;
        setState(() {});
    }

    setVol(int i) async {
        await Volume.setVol(i);
    }

    @override
    Widget build(BuildContext context) {
        return Slider(
        activeColor: Colors.indigoAccent,
        min: 0.0,
        max: 15.0,
        onChanged: (newRating) async {
            setState(() {
                sliderValue = newRating;
            });
            await setVol(newRating.toInt());
            await updateVolumes();
        },
        value: _sliderValue,
    )
}


text:
Q: URLRequest timeoutInterval for entire call Documentation states, that timeoutInterval for URLRequest is being measured not only from the start of the request, but anytime an event like new data is received occurs, time idle is being counted from 0.
Quote from documentation:

Hence, when an instance of load activity occurs (e.g. bytes are received from the network for a request), the idle interval for a request is reset to 0.

I wanted to ask if there is some other mechanism that doesn't restart when such event occurs, but simply gives a time from the beginning to the end, and if it takes longer then request is invalidated. I know that this can be easily achieved using dispatchAfter, just wanted to make sure there is no existing mechanism for this, so that I can use it.


text:
Q: Constraints in optimization; redundant hardness? This is not an accurate mathematical problem, and rather a philosophical and ambitious question.
As far as I know, unconstrained problems are easier than constrained problems; right? This is mostly because adding constraints creates complicated structure to feasible space.
Unlike the current status of technology, don't you think this should be the other way around? I mean, when you add constraints, (usually) you remove considerable space of feasible solutions (though adding some structure to feasible space).
This makes me to have serious doubts about the current trend of optimization models. The models are designed in a way to be simple for unconstrained problems, while they should have been designed to be simple for structured problems.

A: I think you can not say that "unconstrained problems are easier than constrained problems" or that this claim is always true. There is a price to pay to constraint the search space and whenver the space is constraint, it is possible that the constrained space, as a subpsace of the unconstrained one, is on average a much more difficult space for searching.

A: I don't exactly know what you mean by structured problems(because the term "structured" has some specific meaning in many fields); but as long as it's related to the constraints they are not problematic these days, In particular if your constraints are convex.
If your objective function is not convex, then it is very likely that your relaxed (unconstrained) problem is NP-hard any ways.
I refer you to interior-point method algorithm to see how you can easily get rid of the constraints.


text:
Q: When defining a vector space is the scalar part of the field or always a real number I've stumbled upon an exercise that takest the set of integers $\Bbb{Z}$, defines addition and multiplication as usual but scalar multiplication as $\lfloor{\alpha}\rfloor * k$, where $\alpha$ is the scalar and $k$ the element of the vector space and proceeds to claim that this set is not a vector space.
Wikipedia says the scalar is in field $\Bbb{F}$:
In the list below, let u, v and w be arbitrary vectors in V, and a and b scalars in F.

which in this case is the integers $\Bbb{Z}$?
However, the solution to the exercise only makes sense if the scalar is in $\Bbb{R}$. What am I misunderstanding?

A: In your case, $\mathbb Z$ plays the role of the set $V$ defined in Wikipedia article.
And you're right, the scalar multiplication defined in your exercise makes sense if the field $\mathbb F$ is the field of the reals $\mathbb R$.
So here a vector is just an integer in $\mathbb Z$.

A: Let $E$ be an abelian group and $\mathbb{k}$ be a field. Let $\left(\lambda,v\right)\in \mathbb{k}\times E \mapsto \lambda\cdot v \in E$ be a function. We say that $(E,~\cdot~)$ is a vector space if $\forall \lambda, \mu, v,w$
\begin{align}
\lambda\cdot(\mu \cdot v) &=(\lambda\mu)\cdot v &
 1_{\mathbb{k}}\cdot v &= v \\
\lambda\cdot(v+w)&= \lambda\cdot v + \lambda\cdot w &(\lambda+\mu)\cdot v &=\lambda\cdot v + \mu\cdot v
\end{align}
These four assumptions just say that the group structure of $E$ and the field structure of $\mathbb{k}$ are compatible.
In your question, $E = \mathbb{Z}$ is an abelian group and $\mathbb{k}=\mathbb{R}$ is a field, and $\lambda \cdot v = \lfloor{\lambda}\rfloor v$. To show that $(\mathbb{Z}, ~\cdot~)$ is not a vector space over $\mathbb{R}$, you can show that one of the four assumptions above is not respected.
For example, let $v = 1$ and $\lambda = \mu = \frac12$. Then :
\begin{align}
\left(\lambda + \mu\right) \cdot v = (1)\cdot 1 = \lfloor 1\rfloor \times 1 &= 1 \\
\lambda\cdot v + \mu \cdot v = \lfloor \frac12 \rfloor\times 1 +\lfloor \frac12 \rfloor\times 1 &= 0
\end{align}
so for this particular choice of $\lambda,\mu,v$, we have $(\lambda+\mu)v \neq \lambda v + \mu v$. Thus, $\mathbb{Z}$ with this operation is not a vector field over $\mathbb{R}$.


text:
Q: Pandas dataframe columns extension using another dataframe column values I have two dataframes (df1 and df2) as follows:
In [4]:df1
   Year  Annual Counts
0  1979          45345
1  1980          15381
2  1981          32171
3  1982          30288
4  1983          50573
In [5]:df2
   Year  CanESM2  GFDL-ESM2M  HadGEM2-ES365  IPSL-CM5A-MR  NorESM1-M
0  1984    10645       48143          57366         26979      37603
1  1985    15918       17178          34617         21304      31956
2  1986    51790       44111          50017         29233      61203
3  1987    34039       14504          23136         35848      34688
4  1988    68641       67681          24322         39591      34553

and I would like to combine both dataframes as follows:
   Year  CanESM2  GFDL-ESM2M  HadGEM2-ES365  IPSL-CM5A-MR  NorESM1-M
0  1979    45345       45345          45345         45345      45345
1  1980    15381       15381          15381         15381      15381
2  1981    32171       32171          32171         32171      32171
3  1982    30288       30288          30288         30288      30288
4  1983    50573       50573          50573         50573      50573
5  1984    10645       48143          57366         26979      37603
6  1985    15918       17178          34617         21304      31956
7  1986    51790       44111          50017         29233      61203
8  1987    34039       14504          23136         35848      34688
9  1988    68641       67681          24322         39591      34553

One simple solution I have:
df1 = pd.DataFrame(file1)
df1_list = df1['Annual Counts'].tolist()
# empty lists
ext1=[] ; ext2=[] ; ext3=[] ; ext4=[] ; ext5=[]
df2 = pd.DataFrame(file2)
models = ['CanESM2','GFDL-ESM2M','HadGEM2-ES365','IPSL-CM5A-MR','NorESM1-M']
for idx,m in enumerate(models):
    ext+str(idx).append(df1_list)
    df2_mod = df2[m].tolist()
    ext+str(idx).extend(df2_mod)

Any suggestions if pandas have any function to perform this task without the need to create multiple lists and then extending them?

A: Here is one way:
Rename the column Annual Counts to CanESM2 and then use combine_first after setting Year and CanESM2 as index, finally ffill() on axis=1
(df1.rename(columns={'Annual Counts':'CanESM2'})
.set_index(['Year','CanESM2']).combine_first(df2.set_index(['Year','CanESM2']))
.reset_index().ffill(axis=1))

Another way using merge:
(df1.rename(columns={'Annual Counts':'CanESM2'})
   .merge(df2,how='outer',on=['Year','CanESM2']).ffill(axis=1))

     Year  CanESM2  GFDL-ESM2M  HadGEM2-ES365  IPSL-CM5A-MR  NorESM1-M
0  1979.0  45345.0     45345.0        45345.0       45345.0    45345.0
1  1980.0  15381.0     15381.0        15381.0       15381.0    15381.0
2  1981.0  32171.0     32171.0        32171.0       32171.0    32171.0
3  1982.0  30288.0     30288.0        30288.0       30288.0    30288.0
4  1983.0  50573.0     50573.0        50573.0       50573.0    50573.0
5  1984.0  10645.0     48143.0        57366.0       26979.0    37603.0
6  1985.0  15918.0     17178.0        34617.0       21304.0    31956.0
7  1986.0  51790.0     44111.0        50017.0       29233.0    61203.0
8  1987.0  34039.0     14504.0        23136.0       35848.0    34688.0
9  1988.0  68641.0     67681.0        24322.0       39591.0    34553.0

A: Same way as anky_91 answer with renaming columns but then using concat here and forwardfilling (ffill) over axis=1:
pd.concat([df1.rename(columns={'Annual Counts':'CanESM2'}), df2],
           ignore_index=True,
           sort=False).ffill(axis=1)

Output:
     Year  CanESM2  GFDL-ESM2M  HadGEM2-ES365  IPSL-CM5A-MR  NorESM1-M
0  1979.0  45345.0     45345.0        45345.0       45345.0    45345.0
1  1980.0  15381.0     15381.0        15381.0       15381.0    15381.0
2  1981.0  32171.0     32171.0        32171.0       32171.0    32171.0
3  1982.0  30288.0     30288.0        30288.0       30288.0    30288.0
4  1983.0  50573.0     50573.0        50573.0       50573.0    50573.0
5  1984.0  10645.0     48143.0        57366.0       26979.0    37603.0
6  1985.0  15918.0     17178.0        34617.0       21304.0    31956.0
7  1986.0  51790.0     44111.0        50017.0       29233.0    61203.0
8  1987.0  34039.0     14504.0        23136.0       35848.0    34688.0
9  1988.0  68641.0     67681.0        24322.0       39591.0    34553.0


text:
Q: Working with Access from Excel? 'Create the recordset
Set dbRecordset = New ADODB.Recordset
dbRecordset.CursorLocation = adUseServer
dbRecordset.Open Source:="Table1", _
ActiveConnection:=dbConnection, _
CursorType:=adOpenDynamic, _
LockType:=adLockOptimistic, _
Options:=adCmdTable

'dbRecordset.AddNew

dbRecordset(Cells(2, 3).Value) = Cells(1, 1).Value

dbRecordset.Update

'Close the connections.
dbRecordset.Close
dbConnection.Close

I'm trying to make an application with a feature that stores data into access from excel  (Never have used access). I was able to connect them, and send values to the database. I believe the problem I am having is with the above piece of code. The dbRecordset(Cells(2, 3) to me it seems like the value should go to row/record 2 field 3, but it writes to (2,3). Trying to write to (1,1) gives me an error. I think I could write a for each loop that will move the data I need, but I don't understand where it will go.
Something that could bypass all of this is if I could trigger a DoCmd.TransferSpreadsheet Method that access has built in from excel. I do not know the syntax to write something like (sql, shell?). If you could point me in the right direction of where do write a doCmd command that would be appreciated as it would be much faster than looping.

A: Tweak this a bit.  You can run it from Excel:
Sub LoadSheet()
Dim accappl As Access.Application
Dim strpathdb As String
Dim strpathxls As String
Dim myrange As String, myrow1 As String, myrow2 As String

myrow1 = Range("a1").End(xlDown).End(xlDown).Row
myrow2 = Range("a1").End(xlDown).End(xlDown).End(xlDown).Row

myrange = ActiveSheet.Name & "!A" & myrow1 & ":H" & myrow2

'path to the database
strpathdb = "X:\cre\dep\STRAT_PLAN\StratPlan.mdb"
'path to the upload file
strpathxls = ActiveWorkbook.FullName
Set accappl = New Access.Application

accappl.OpenCurrentDatabase strpathdb

accappl.DoCmd.TransferSpreadsheet transfertype:=acImport, _
            tablename:="Tbl_Growth_Metric", _
            Filename:=strpathxls, Hasfieldnames:=True, _
            Range:=myrange, SpreadsheetType:=5
            'The Spreadsheet type = 5 specifies an Excel 5.0/7.0 file
            'format

MsgBox "All records are loaded"

accappl.Quit

End Sub


text:
Q: VUEJS Wrap Element in a link I would like to wrap an element with a link ONLY if a link is available:
Normally I would use:

      <some-content></some-content>

    <some-content v-else></some-content>

BUT this leads to a lot of code duplication, especially if some-content is complex.
I tried to use it like this:
    <wrap-link :url="url">
      <some-content></some-content>
    </wrap-link>

Where wrap-link is like the following, but I can't get rid of the "span" in the v-else part.
    <template>

        <slot></slot>

        <slot></slot>

    </template>

Any suggestions?

A: Vue 3
Vue 3 allows multiple root nodes, so putting the v-else directive directly on the <slot> in the root is allowed:
<template>

    <slot></slot>

  <slot v-else></slot>
</template>

demo 1
Vue 2 or Vue 3
In either version of Vue, you could use a <component> whose properties are computed based on url:
<template>
  <component :is="component" v-bind="props">
    <slot></slot>
  </component>
</template>

demo 2


text:
Q: How to force reload when back button is pressed in Nodejs application? I am trying to implement force reload page when back button is pressed in my nodejs application .
I cannot find anything relevant to this . Any suggestions?
Thanks in advance .


text:
Q: UI background changes with the aspect ratio I am making a 3D game on Unity. Currently I work on main menu. The problem is
when I use 16:9 aspect ratio I get this result:

The background is not scaled.
However when I use Free aspect ratio, I get this:

Here is background object properties and sprite properties:

I have no clue what is the problem here and how to solve it. I hope to find some help here. Thanks in advance.

A: You should extract one tile of the background sprite like this:

Then it should be tiled correctly.
The key is to extract the smallest repeatable element.
Also, you don't have to worry about the Free Aspect. Just make sure it looks fine on the real screen resolutions.


text:
Q: Is there a way to have non-overlapping data point labels on a ternery plot in R? I am trying to replicate a chart I found on FiveThirtyEight at https://fivethirtyeight.com/features/how-cable-news-reacted-to-the-cohen-hearing/. This shows a ternery plot where the location of the words in the 3 axis shows the proportion quoted that by that respective network.
I am currently using R, ggplot2 and more importantly ggtern (which I use extensively for ternery plots). However I have never found a way to make data labels on points not overlap. I have always hoped that ggtern would interact with ggrepel but sadly it doesn't (to my knowledge). Is there any way to force these to interact, or find another way of doing this?
Chart shown in link for clarity of what I'm after:

Example of my chart with words overlapping and looking bad:

EDIT
Code to create my hideous chart:
    data <- data.frame(word = c("A","random","set","of","words","that","can","hopefully","help","someone","solve","my","issue","of","overlapping","labels","and","make","my","chart","readable","and","a","good","visualization"),
               axis1 = sample(1:100),
               axis2 = sample(1:100),
               axis3 = sample(1:100))

    ggtern(data = data,
        aes(x = axis1, y = axis2, z = axis3, colour = word, label = word)) +
      geom_point(size = 1) +
      geom_text()

A: Ok, so you want the functionality as in ggrepel package. While ggrepel wont work here you can use position_nudge_tern and check_overlap:
word = c("A","random","set","of","words","that","can","hopefully","help","someone","solve","my","issue","of","overlapping","labels","and","make","my","chart","readable","and","a","good","visualization")
col = c("red", "blue", "green", "red", "blue", "green","red", "blue", "green", "red", "blue", "green","red", "blue", "green", "red", "blue", "green","red", "blue", "green", "red", "blue", "green","red")

n  = 25   #Number of Data Points
nv = 0.1  #Vertical Adjustment
pn = position_nudge_tern(y=nv,x=-nv/2,z=-nv/2)

data <- data.frame(x = sample(1:25),
               y = sample(1:25),
               z = sample(1:25),
               label=word)

ggtern(data = data, aes(x = x, y = y, z = z, colour = col, label = word)) +
  geom_point(size = 1) +
  theme_nomask() + #Allow Labels to Spool Over Edges
  geom_text(position=pn,aes(label=word),check_overlap=T, size=5)

Which will give you non-overlapping labels:


text:
Q: Class 'Collective\Html\HtmlServiceProvider' not found and other Class encrypter does not exist After adding aliases and the laravelcollective/html service provider, I'm getting an error.

A: Whenever you make changes to your core application configuration, don't forget to clear cache and dump autoload, since the application is often being served by the cache, so it does not pick up your changes. Use these commands to clear application cache:
php artisan cache:clear
php artisan config:cache
composer dump-autoload

After this, reload your page, and everything should be up and running.


text:
Q: Ant: How can I ignore build error if directory doesn't exist? I'm using Ant 1.8.1.  How can I ignore the following build error if a directory doesn't exist?  The error I get is
BUILD FAILED
/Users/davea/myco2-myco/build.xml:211: Directory does not exist: /Users/davea/myco2-myco/${mycousa.test.root}

The line in question is the delete directive from the clause below.  Thought the "erroronmissingdir" attribute would have solved the problem, but I guess not …
    <delete>
            <fileset dir="${mycousa.test.root}" erroronmissingdir="false">
                    <include name="suite.html" />
            </fileset>
    </delete>

Let me know how I can modify the above so that I won't get the error even if the directory doesn't exist.
Thanks - Dave

A: It's a bug in ant (version <= 1.8.0).
See
https://issues.apache.org/bugzilla/show_bug.cgi?id=50124
The fix:
http://svn.apache.org/viewvc?view=revision&revision=1027000

A: I think the problem is that the error condition you're handling is on the creation of the FileSet, not the delete itself.  Check out the failonerror directive on the delete task:
<delete failonerror="false">
            <fileset dir="${mycousa.test.root}" erroronmissingdir="false">
                    <include name="suite.html" />
            </fileset>
</delete>

Reference: http://ant.apache.org/manual/Tasks/delete.html


text:
Q: Permutations with replacement in rust? I'd like to write a generic function that can make all unique vectors where each index has a series of values.
Easiest to illustrate with an example.
for i in (1..3).combinations_with_replacement(3) {
   println!("{:?}",i);
}

Produces the ouput
[1, 1, 1]
[1, 1, 2]
[1, 2, 2]
[2, 2, 2]

Which is not satisfactory because it's missing members like
[1, 2, 1]
[2, 1, 2]
[2, 2, 1]

So I also tried permutations(3) but since their are more positions than items in the iterator, the iterator is empty. There also doesn't appear to be a permutations_with_replacement but maybe that'd be the name of the function I'm looking for.
In this case you could accomplish the task with 3 nested for loops but this is ugly and not a general solution. I think a recursive backtracking solution could do it too but seems like their should be something in itertools that I'm missing.

Here's another example of what I want but with code written a few languages that aren't rust.

A: Using itertools, based on @Ry-'s suggestion:
for i in (1..=3).map(|_| 1..=2).multi_cartesian_product()  {
   println!("{i:?}");
}

Output:
[1, 1, 1]
[1, 1, 2]
[1, 2, 1]
[1, 2, 2]
[2, 1, 1]
[2, 1, 2]
[2, 2, 1]
[2, 2, 2]

Playground

A: I'm not sure how this can be done using itertools, but here is one way to achieve the same result in plain Rust.
pub struct PermutationsReplacementIter<I> {
    items: Vec<I>,
    permutation: Vec<usize>,
    group_len: usize,
    finished: bool,
}

impl<I: Copy> PermutationsReplacementIter<I> {
    fn increment_permutation(&mut self) -> bool {
        let mut idx = 0;

        loop {
            if idx >= self.permutation.len() {
                return true;
            }

            self.permutation[idx] += 1;

            if self.permutation[idx] >= self.items.len() {
                self.permutation[idx] = 0;
                idx += 1;
            } else {
                return false;
            }
        }
    }

    fn build_vec(&self) -> Vec<I> {
        let mut vec = Vec::with_capacity(self.group_len);

        for idx in &self.permutation {
            vec.push(self.items[*idx]);
        }

        vec
    }
}

impl<I: Copy> Iterator for PermutationsReplacementIter<I> {
    type Item = Vec<I>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.finished {
            return None;
        }

        let item = self.build_vec();

        if self.increment_permutation() {
            self.finished = true;
        }

        Some(item)
    }
}

pub trait ToPermutationsWithReplacement {
    type Iter;
    fn permutations_with_replacement(self, group_len: usize) -> Self::Iter;
}

impl<I: Iterator> ToPermutationsWithReplacement for I {
    type Iter = PermutationsReplacementIter<<I as Iterator>::Item>;

    fn permutations_with_replacement(self, group_len: usize) -> Self::Iter {
        let items = self.collect::<Vec<_>>();
        PermutationsReplacementIter {
            permutation: vec![0; group_len],
            group_len,
            finished: group_len == 0 || items.len() == 0,
            items,
        }
    }
}

Then it can be used similarly to combinations_with_replacement.
for x in (1..3).permutations_with_replacement(3) {
    println!("{:?}", x);
}

// Output:
[1, 1, 1]
[2, 1, 1]
[1, 2, 1]
[2, 2, 1]
[1, 1, 2]
[2, 1, 2]
[1, 2, 2]
[2, 2, 2]

Playground Link
You can also put it on any iterator where the elements implement Copy. However, I wouldn't recommend it. The time complexity for this task is extremely bad. For an input iterator of n elements in groups of length m, this will create an iterator of about n^m items assuming my math is correct.


text:
Q: kotlin how to remove duplicate through some value in object array? how to remove duplicate through some value in object array?

data class Person(
    val id: Int,
    val name: String,
    val gender: String
)

val person1 = Person(1, "Lonnie", "female")
val person2 = Person(2, "Noah", "male")
val person3 = Person(3, "Ollie", "female")
val person4 = Person(4, "William", "male")
val person5 = Person(5, "Lucas", "male")
val person6 = Person(6, "Mia", "male")
val person7 = Person(7, "Ollie", "female")

val personList = listOf(person1,person2,person3,person4,person5,person6,person7)

Person 3 and person 7 have a "female" gender and have the same name. So person7 needs to be removed.
But "male" gender can have duplicated name.
And the order of the list must be maintained.
expect result
[
    Person(1, "Lonnie", "female"),
    Person(2, "Noah", "male"),
    Person(3, "Ollie", "female"),
    Person(4, "William", "male"),
    Person(5, "Lucas", "male"),
    Person(6, "Mia", "male"),
]

A: You could do something like this, assuming the order is indicated by the id field of the Person class:
val personList = listOf(person1,person2,person3,person4,person5,person6,person7)
    .partition { it.name == "male" }
    .let { (males, females) -> males + females.distinctBy { it.name } }
    .sortedBy { it.id }

A: I believe this does what you want:
val result = personList.filter {
  person -> person.gender == "male" || (personList.first {
    person.name == it.name && person.gender == it.gender
  } == person)
}


text:
Q: How to return multiple columns using vlookup in Excel? Let suppose i have 2 tables with below data. I want to return all three columns of a row(each row at a time) of table A, when location of table A found in the locations(look for all locations) of table B using vlookup.
e.g:
step 1: first location of table A = 1
step 2: look for location 1 in table B.
step 3: If found then return first row of table B.
Please see the below example and expected result.
Table A
Location    Quantity    Amount
  1           10         100
  2           20         400
  3           30         500
  4           40         600
  5           50         700

Table B
Location    Quantity    Amount
1            30          34
3             4          34
4             5          3454
6            65          565
7            66          76

Expected result:
Location    Quantity    Amount
1            10         100
N/A         N/A         N/A
3           30          500
4           40          600
N/A        N/A          N/A

I have been doing this for so long but couldn't find the solution yet.
I have millions of records and cannot do it manually. Your answer would be highly appreciated. Thanks !

A: You just need an If formula. Assuming Table A is in Columns A, B, C, and Table B is next to it in Columns D, E, F then wherever Table C is you'll want something like: =IF(A2=D2,A2,"") in the first column, =IF(A2=D2,B2,"") in the second, =IF(A2=D2,C2,"") in the third.