How to replace 'for' loop with more efficient code for stock market analysis example

Question: I am working on a stock market analysis project.  I am attempting to find the highest price in the past 5 days, the volume on the day of the highest price, and how many days before that highest price occurred.
I have constructed a solution utilizing a couple of 'for' loops, but would like to find a more efficient way to code this without utilizing 'for' loops. Any suggestions would be appreciated.
A1 = pd.merge(A, B, left_index = True, right_index = True)
A1["Date"] = A1.index
A1.reset_index(inplace = True)

### 5 Day High and Volume
Indexes = []
for index in range(len(A1.index) - 5):
    M = 0
    H = 0
    for i in range(1,6):
        if H < A1.iloc[i+index,2]:
            H = A1.iloc[i+index,2]
            M = i+index
    Indexes.append(M)

Vol = pd.DataFrame(columns = ['B','C'])
Vol5 = []
DH5 = []
Z = []
count = 0
for i in Indexes:
   Vol5.append(A1.iloc[i,1])
   DH5.append(A1.iloc[i,2])
   Z.append(count - i)
   count += 1
for i in range(5):
    Vol5.append(np.nan)
    DH5.append(np.nan)
    Z.append(np.nan)
Vol['B'] = Vol5
Vol.index = A1['Date']
Vol['C'] = DH5
Vol['D'] = Z

Comment: A bit hard to answer without knowing the columns of your dataframe but I think the max function of pandas would be useful here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.max.html
Comment: Columns would be date, open, high, low, close, volume
Comment: I am able to find the max value without an issue.  The difficulty I am having is in trying to find the correlating volume on the day of the max value along with how many days before day N in which the max occurred.
Answer: I suggest using the rolling method to find the index of the maximum value computed over the previous 5 rows:
import pandas as pd
import numpy as np

d={'date':np.random.random(10), 'open':np.random.random(10), 'high':np.random.random(10), 'low':np.random.random(10), 'close':np.random.random(10), 'volume':np.random.random(10)}
A1=pd.DataFrame(data=d)

df=A1.rolling(window=5).apply(np.argmax).shift(1).fillna(0)

Then to find the volume associated with this maximum value (in this example for the highest column):
A1['volume associated with maximum price']=A1.iloc[df.high]['volume']


C++ How do I create a dynamic array of objects inherited from an abstract class?

Question: My task specifically states that I have to create a random array of Squares and Triangles, that are inherited from an abstract class Figure, and then I have to print out their square area. Coming from C#, I thought I'd be off with an array of objects, but they do not exist in C++. I'm not allowed to use anything like vectors. Making a dynamic array of Figure doesn't work because apparently it never works with abstract classes. What should I do? Please, keep it simplified if possible.
Here's my current code. Very basic, but it's here just to show what I'm trying to do.
#include <iostream>
#include <stdlib.h>

using namespace std;

class Figure
{
    public:
        virtual double square() = 0;
};

class Square : public Figure
{
    public:
        double side;

        double square()
        {
            return side * side;
        }
};

class Triangle : public Figure
{
    public:
        double height;
        double side;

        double square()
        {
            return 0.5 * side * height;
        }
};

void main()
{
    int size = 20;
    Figure *dyn_arr = new Figure[size]; // this doesn't work
    //Also I have to fill it somehow too...
    for (int i = 0; i < size; i++) cout << Figure.square(); //this doesn't    work either
}

Comment: I'm not allowed to use vectors here.
Comment: Kind of. It was on my exam last week and I was supposed to do that on paper. I still haven't found out the way to do it, so I had to ask here.
Comment: @Alucard "I'm not allowed to use vectors here" - That's a stupid and arbitrary requirement. In the real world `std::vector` is what one would use *and* one would fill it with smart pointers in *most* cases, *not* raw pointers.
Comment: @JesperJuhl My whole uni is full of stupid and arbitrary requirements. I'm just waiting to get out of it with a diploma and do some real world stuff.
Comment: @Alucard heh, that reminds me of why I skipped uni 20+ years ago ;) Try a few open source projects on for size while you wait; to gain some "real life" experience. I jumped onto the Linux kernel back in the '90s - taught me a lot - these days I'd probably jump onto a successful C++ library that interrested me and start contributing.
Answer: Firstly main must return int. Then you need to create an array of pointers which will show to abstract class Figure.
Figure **dyn_arr = new Figure*[size];
Then if you want to add a new object of the derived class you are adding simply like this.
dyn_arr[0] = new Triangle(); --> this will create new object which will return the address of that object, and your array is actually array of pointers.
Finnaly if you want to call the function square from any class you can do that like this.
dyn_arr[0]->square();
p.s. If you don't have at least a little experience with pointers this can be confusing.
Comment: you should code it using vector and shared_ptr for extra credit
Answer:
Figure *dyn_arr = new Figure[size]; // this doesn't work

It doesn't work because we cannot create an array of Figures because of the pure virtual function. We wouldn't want to create a Figure by itself in any case. We only want to create either a Square or a Triangle and their sizes may differ. So there is no way to allocate the memory when the array is created.
You could create an array of pointers (size is known at compile time) and then iterate over that:
auto dyn_arr = new Figure*[size];
// auto in the above context becomes Figure** (pointer to a pointer)
for(int i = 0; i < size; i++)
    cout << dyn_arr[i]->square();

Please keep in mind that arrays and pointers used this way is prone to errors. Far better to use std::make_unique and std::vector.
Here is one way to randomly create the objects:
Figure* go_figure()
{
    std::uniform_int_distribution<int> ud{0,1};
    static std::random_device rd{};
    switch(ud(rd))
    {
        case 0: return new Square{};
        case 1: return new Triangle{};
    }
}

int main()
{
    int size = 20;
    auto dyn_arr = new Figure*[size];
    for(int i = 0; i < size; i++)
        dyn_arr[i] = go_figure();
    for(int i = 0; i < size; i++)
        cout << dyn_arr[i]->square();
    for(int i = 0; i < size; i++)
        delete dyn_arr[i];
    delete[] dyn_arr;
}

Comment: if vectors arent allowed then smart pointer probably arent either. Always depressing to see assignments that require unsafe, old fashioned code. Why not insist on assembler (or even direct hex machine code)
Comment: I'd suggest a vector of smart pointers instead of C-style arrays and raw pointers / manual memory management... That's so 90's-ish ;-)
Comment: @JesperJuhl Yes that would be best. The question was about basics.
Comment: Wow, that actually works! A couple more questions:
1) I need array filled with random objects. How do I do that?
2) Why just changing Figure *dyn_arr to auto dyn_arr fixed that? What does auto do?
Comment: @pm100 That's a good question. 90% of my knowledge comes from books, not sure if lecturers even try. But it's always refreshing to see these pop up.
Answer: You can create a list of generated functions to select from, to create dynamically allocated objects. Using a rng you can then randomly select from the list of generated functions to call, in order to fill out an array of unique_ptr
 s.
Example using std::deque instead of std::vector :
template<typename T>
Figure* Create() { return new T(); }

std::function
 createFunctions [] = {
    Create<Square>
   ,Create<Triangle>
};

int main()
{
    std::deque<std::unique_ptr
> shapes;
    std::mt19937 rng;
    rng.seed(std::random_device()());
    std::uniform_int_distribution<std::mt19937::result_type> idxSel(0,1);
    for(int i = 0; i < 20; ++i)
    {
        shapes.emplace_back(createFunctions[idxSel(rng)]());
    }
}


Mapping of column fields from CSV file with currently available fields

Question: We have scenario where we want to:-
upload CSV file -> then import data from it -> Map data with current fields
I tried few designs:-
1)

2)

But I am still not happy with my designs. As I dont feel those are user friendly.
Can someone help me improve it or someone provide some good examples?
Comment: Look out for other solutions - this is not a unique problem. For example, Thunderbird allows to map CSV columns to be mapped to their address book structure.
Comment: Here a PHP source code tool Csvxlsvisualmapping.com
Answer: You can try really intuitive like Match the following which we have done in our childhood.
i can suggest you few interactions but you have to be precise with visuals as if not properly visualised it may end up bad.
but make sure when you hover on a single item other lines(lines of other elements) will have opacity 50% so that they may not effect visibility

Here you just drag the item in the list1 and put it under item2 of other list.
Comment: I really like this solution, the only thing that I am afraid of is how visible the mapping will be if there are 30+ fields for example.
Answer: Prestashop has a similar functionality, where you can see your CSV file and match each column with an existing data. The drawback of this solution is that you need to click the arrows to see the next columns. I would propose to use a slider instead.

Things that you might need to consider:

Lines that the user doesn't want to import - usually the 1st line because it might contain the title of the data
Give a proposed mapping according to your columns' names
Skip columns that your user doesn't want to import
Mandatory destination fields in order the import to happen
Save mapping, in order to save time for the next process


my region does not have cloud function, can I use other region cloud function, and how about the billing?

Question: I want to make a new project using a brand new region, JAKARTA (asia-southeast2).
in my project, I need to use

Firestore
Cloud Functions
Cloud Storage for Firebase

but from the table info product availability by location in here . it seems that cloud functions is not available yet in region JAKARTA (asia-southeast2), asia pacific zone.
here is my questions:

for now, can I use cloud functions from the nearest available region ? I mean, my firestore is In Jakarta, but my cloud function is Hongkong/Tokyo ?

say for example I can deploy my function in other region, and then in the future, cloud functions is also available in Jakarta (asia-southeast2). can I switch it to cloud function in Jakarta ?

If I can deploy the function in other region, then my firestore and storage (Jakarta) will be in different region from my cloud function (Hongkong/Tokyo). will it affect the billing ? I need to consider some additional cost if any.
Answer:
For now, can I use cloud functions from the nearest available region ?
I mean, my firestore is In Jakarta, but my cloud function is
Hongkong/Tokyo ?

Yes you can have your Cloud Functions and Firestore database (or Cloud Storage buckets) in different regions. See the recommendations for choosing the regions.

Say for example I can deploy my function in other region, and then in
the future, cloud functions is also available in Jakarta
(asia-southeast2). can I switch it to cloud function in Jakarta

Yes, you will be able to change the region, see the doc. Note that you could deploy the same CF to different regions.

If I can deploy the function in other region, then my firestore and
storage (Jakarta) will be in different region from my cloud function
(Hongkong/Tokyo). will it affect the billing ? I need to consider some
additional cost if any.

Yes it will affect you billing in terms of Outbound data transfer (i.e. data transferred from your function out to the locations where Firestore and/or Storage are deployed). See the doc for more details. Note that you could also experience an increased latency.


Show Only 2 Decimal Places in SQL Server

Question: I've got some columns that are stored as an INT value that I am doing some addition and division on and I would like to display the results by limiting the digits after the decimal to 2.  I've tried different combinations of DECIMAL / NUMERIC / ROUND but I can't get the solution.
Could anyone offer any advice on how to get the desired solution?
Query:
SELECT cc.code AS [CountyID], RTRIM(LTRIM(cc.[description])) AS [CountyName],
SUM(ISNULL(ps.push_count,0)) AS [CountyPushCounts],
SUM(ISNULL(ps.push_unique_count,0)) AS [UniquePushCount],
SUM(ISNULL(ps.error_count,0)) AS [PushErrorCount],
SUM(ISNULL(ps.warning_count,0)) AS [PushWarningCount],

(CAST(SUM(ISNULL(ps.push_unique_count,0)) AS DECIMAL(15,2)) / CAST(SUM(ISNULL(ps.push_count,0)) AS DECIMAL(15,2)) * 100.0) AS [Unique Push Per Day] ,

((CAST(SUM(ISNULL(ps.error_count,0)) AS DECIMAL(15,2)) + CAST(SUM(ISNULL(ps.warning_count,0)) AS DECIMAL(15,2))) / CAST(SUM(ISNULL(ps.push_count,0)) AS DECIMAL(15,2)) * 100.0) AS [Data Error Rate]

FROM dbo.push_stats AS [ps]
INNER JOIN CCIS.dbo.county_codes AS [cc] ON ps.county_code = cc.code
WHERE DATEPART(YEAR,ps.ldstat_date) = 2017
AND DATEPART(MONTH,ps.ldstat_date) = 3
GROUP BY cc.code, cc.[description]
ORDER BY cc.[description];

And my data set looks as follows:
CountyID  CountyName  PushCounts  UniquePushCount  PushErrorCount  PushWarningCount  [Unique Push Per Day]  [Data Error Rate]
1         ALACHUA     210422      77046            0               39                36.61499273            0.018534184
2         BAKER       8099        5306             0               71                65.51426102            0.876651438
3         BAY         3178214     434893           117             2793              13.68356568            0.091560857
4         BRADFORD    17654       12119            0               131               68.64733205            0.742041464

Answer: You have to cast the final result, not just the individual numerator and denominator
DECLARE @Numerator INTEGER
DECLARE @Denominator INTEGER

SET @Numerator = 10
SET @Denominator = 3;
-- This will produce 3.33333333
SELECT CAST(@Numerator AS DECIMAL(5,2))/CAST(@Denominator AS DECIMAL(5,2))
-- This will give you 3.33
SELECT CAST(
     CAST(@Numerator AS DECIMAL(5,2))
          /CAST(@Denominator AS DECIMAL(5,2))
       AS DECIMAL(5,2))

Answer: I think this will do it:
SELECT cc.code AS [CountyID], RTRIM(LTRIM(cc.[description])) AS [CountyName],
    SUM(ISNULL(ps.push_count,0)) AS [CountyPushCounts],
    SUM(ISNULL(ps.push_unique_count,0)) AS [UniquePushCount],
    SUM(ISNULL(ps.error_count,0)) AS [PushErrorCount],
    SUM(ISNULL(ps.warning_count,0)) AS [PushWarningCount],

    CAST((SUM(ISNULL(ps.push_unique_count,0)) * 100.00) / SUM(ISNULL(ps.push_count,0)) AS DECIMAL(15,2)) AS [Unique Push Per Day] ,
    CAST((SUM(ISNULL(ps.error_count,0)) + SUM(ISNULL(ps.warning_count,0)) * 100.00) / SUM(ISNULL(ps.push_count,0)) AS DECIMAL(15,2)) AS [Data Error Rate]

FROM dbo.push_stats AS [ps]
INNER JOIN CCIS.dbo.county_codes AS [cc] ON ps.county_code = cc.code
WHERE DATEPART(YEAR,ps.ldstat_date) = 2017
    AND DATEPART(MONTH,ps.ldstat_date) = 3
GROUP BY cc.code, cc.[description]
ORDER BY cc.[description];

There are two main points here:

With the division operation, get at least one term to a floating point type of some kind before the division happens, so that it doesn't do integer division and truncate the decimal portion of the result. You're okay as long as either term is a floating point type of some kind, and you can accomplish this simply by moving the * 100.00 earlier.
You want to allow much greater than 2 decimal places for the internal calculations, and only set your output format at the very end. Rounding or casting to limited types too soon in an expression can change intermediate values in small ways that are exaggerated in the final results. This means you only want one big CAST() operation around the whole set.
Comment: That does work - so you just moved the *100.0 into the numerator instead of multiplying the divided product it looks like.
Comment: I also removed a bunch of extra casts() that were probably hurting your accuracy.
Comment: OK - let me take a closer look then. I probably did get a little crazy with the CASTS.


message: path is required

Question: Hi I'm trying to create a new subdocument via mongoose, but i'm getting the following messages when I execute the POST method in Postman:
{
  "message": "Location validation failed",
  "name": "ValidationError",
  "errors": {
    "reviews.1.reviewText": {
      "message": "Path `reviewText` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "reviewText"
      },
      "kind": "required",
      "path": "reviewText"
    },
    "reviews.1.rating": {
      "message": "Path `rating` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "rating"
      },
      "kind": "required",
      "path": "rating"
    },
    "reviews.1.author": {
      "message": "Path `author` is required.",
      "name": "ValidatorError",
      "properties": {
        "type": "required",
        "message": "Path `{PATH}` is required.",
        "path": "author"
      },
      "kind": "required",
      "path": "author"
    }
  }
}

Here is my DB Schema for Locations:
var mongoose = require('mongoose');

var reviewSchema = new mongoose.Schema({
    author: {type: String, required: true},
    rating: {type: Number, required: true, min: 0, max: 5},
    reviewText: {type: String, required: true},
    createdOn: {type: Date, "default": Date.now}
});

var openingTimeSchema = new mongoose.Schema({
    days: {type: String, required: true},
    opening: String,
    closing: String,
    closed: {type: Boolean, required: true}
});

var locationSchema = new mongoose.Schema({
    name: {type: String, required: true},
    address: String,
    rating: {type: Number, "default":0, min: 0,  max: 5},
    facilities: [String],
    coords: {type: [Number], index:'2ndsphere'},
    openingTimes: [openingTimeSchema],
    reviews: [reviewSchema]
});

mongoose.model('Location', locationSchema);

Here the controller launched under router.post('/locations/:locationid/reviews', ctrlReviews.reviewsCreate); routing:
//reviews.js
var mongoose = require('mongoose');
var Loc = mongoose.model('Location');

module.exports.reviewsCreate = function (req, res) {
    var locationid = req.params.locationid;
    if(locationid){
        Loc
            .findById(locationid)
            .select('reviews')
            .exec(
                function(err, location){
                    if(err){
                        sendJsonResponse(res, 400, err);
                    } else{
                        console.log(location);
                        doAddReview(req, res, location);
                    }
                }
            );
    } else{
        sendJsonResponse(res, 400, {
            "message" : "Not found, locationid required"
        });
    }
};
// START - Functions for review create  //////////////////////////////////////
var doAddReview = function(req, res, location){
    if(!location){
        sendJsonResponse(res, 404, "locationid not found");
    } else{
        location.reviews.push({
            author: req.body.author,
            rating: req.body.rating,
            reviewText: req.body.reviewText
        });

        location.save(function(err, location){
            var thisReview;
            if(err){
                //sendJsonResponse(res, 400, err);
                sendJsonResponse(res, 400, err);
            } else{
                updateAverageRating(location._id);
                thisReview = location.reviews[location.reviews.length - 1];
                sendJsonResponse(res, 201, thisReview);
            }
        });
    }
};

var updateAverageRating = function(locationid){
    console.log("Update rating average for", locationid);
    Loc
        .findById(locationid)
        .select('reviews')
        .exec(
            function(err, location){
                if(!err){
                    doSetAverageRating(location);
                }
            }
        );
};

var doSetAverageRating = function(location){
    var i, reviewCount, ratingAverage, ratingTotal;
    if(location.reviews && location.reviews.length > 0){
        reviewCount = location.reviews.length;
        ratingTotal = 0;
        for(i=0; i<reviewCount; i++){
            ratingTotal = ratingTotal + location.reviews[i].rating;
        }
        ratingAverage = parseInt(ratingTotal / reviewCount, 10);
        location.rating = ratingAverage;
        location.save(function(err){
            if(err){
                console.log(err);
            } else{
                console.log("Average rating updated to", ratingAverage);
            }
        });
    }
};

I've seen that error pops when the location.save function is executed. I'm learning MEAN Stack from a book, so you'll be able to download the complete code for this chapter here: https://github.com/simonholmes/getting-MEAN/tree/chapter-06
I've tried replacing the code of my locations.js and reviews.js files from app_api/controllers folder, but at this point the application crashes, I guess because other files needs to be updated so.
So I'm stuck there.
Does anyone understand why it would be happening?
Thanks in advance!
Answer: He bro.. Check this image.. I was also facing same problem.. and here is what I was doing wrong.
Answer: I believe your problem might be that body-parser is not configured.
Try npm installing body-parser, then import it at the top of your main server file:
bodyParser = require('body-parser');

Finally, configure it for use. This will allow you to use x-www-form-urlencoded:
// Setting up basic middleware for all Express requests
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses

Comment: Had a similar problem a bit ago happen to me and something along this was what solved it.
Comment: Joshua I have it configured this way already, but I do not discard that the issue comes from some parse error, as each time I install a module I'm facing several warnings like this: "npm WARN EJSONPARSE Failed to parse json", maybe this is something related, but I couldn't find any solution for this (cache clear doesn't solve).
Answer: Check your

    req.body.author,
    req.body.rating,
    req.body.reviewText

They must be coming as empty string

Answer: In fact. If, I change it for: author: "Big Mama", rating: 5, reviewText: "Lorem ipsum dolor amet" it works perfectly, but when I use Postman to add this in body it seems to be empty, and I think it should work. I'm using x-www-form-urlencode for this, but tried all other options. I'd like to undestand how should I use it here...
Answer: Seems that this is sorted: I added id creation function in the review.push and working. Really I still don't understad why this is necessary, as usually mongoose add id's to documents and subdocuments, even I'm having problems with other controller because it's adding id's where shouldn't...Here the updated code for doAddReview function that sorted this issue:
var doAddReview = function(req, res, location){
    if(!location){
        sendJsonResponse(res, 404, "locationid not found");
    } else{
        location.reviews.push({
            _id: mongoose.Types.ObjectId(),
            author: req.body.author,
            rating: req.body.rating,
            reviewText: req.body.reviewText
            /*
            author: "Big Mama",
            rating: 5,
            reviewText: "Lorem ipsum dolor amet"
            */
        });

        location.save(function(err, location){
            var thisReview;
            if(err){
                //sendJsonResponse("Error Here");
                sendJsonResponse(res, 400, err);
            } else{
                updateAverageRating(location._id);
                thisReview = location.reviews[location.reviews.length - 1];
                sendJsonResponse(res, 201, thisReview);
            }
        });
    }
};

Many thanks Joshua and Piyush!
Answer: Just make an curl call-
1.First import the curl command as Raw-text

2.Then send the POST request

message: path is required


Splitting Service conductors to reach remote building

Question: I am hoping ThreePhaseEel can chime in!
I am looking far ahead and planning the electrical for a home I am building. From left to right I have an electrical pole - 100ft then a garage - then another 30ft to the home. The POCO wants to put the meter in the Garage to avoid the need for a transformer upgrade. This is a 400amp service. My load calcs require ~300ish amps at the house, ~100amp at the garage, and 80A of solar will be on the garage roof.
The question: The NEC 2017 allows each building at a residential home to have one service conductor. How would I split the service conductor at the garage to go to the home and still feed a panel at the garage?
My plan is after the meter at the garage (Eaton 324C) to use a tap box and split the 400amp service - one set to the home and then the other to the garage.

At the garage: post tap box put a 100Amp service disconnect. then an interior subpanel
At the house: when the wires land at the house put a fused 400amp disconnect and feed 2 200amp sub-panels
Comment: @manassehkatz-Moving2Codidact its a lot but a big house all electric. Im really trying to get 400Amps over because that is typical. 2 AC,s with electric heaters, car charger, double oven, hot water heater, induction stove, dryer, heated floors.
Comment: Who do you have for an electric utility?
Comment: @ThreePhaseEel SCE in socal, nec2017
Answer: SCE may not let you cheap out on this
While NEC 230.40 Ex 3 would permit you to hang a socket at the garage and have separate service entrance lines from that socket to the garage and the house, that may not fly under the SCE ESR-5 section 3.0 and 3.1 rules on meter switches:

3.0 Meter Switch
For each and every meter, the contractor shall furnish and install a switch, or other approved
disconnecting means with overcurrent protection. This is referred to as the "Meter Switch." It shall
be installed at the same location and directly adjacent to the metering and service equipment. The
meter switch shall control all of, and only, the energy registered by that meter. Where permitted by
local code or ordinances, the meter switch may consist of a group of switches or breakers per
National Electric Code (NEC) 230-71. A separate meter switch will be required for each separate
service of any group where the loads are totalized by a single meter.
3.1 Number of Switches
Every meter or service shall be furnished with a meter switch as described in Section 3.0.
The NEC allows up to a maximum of six switches or disconnects to constitute the main
overcurrent device for a single commercial or industrial service. A residential service may
have a maximum of two switches or disconnects for each single-family service.

As a result of that, we'll have to start with something SCE will definitively let you install, even if it is a vastly more expensive setup than what you were originally contemplating.  We're also going to assume from your initial choice of meter socket that this is an underground service dip from the pole; if it's an overhead service instead, then you will need a unit that accepts an overhead conversion gutter, such as an Eaton HP40 or HP402442, or a Square-D CUM400CB.
The first component we'll need is a 400A, EUSERC-compliant, single disconnect meter main.  This is a very expensive piece of equipment (as in several thousand $), but it is quite important in that it's the only way we can provide 300A to the house while meeting SCE's rules about meter switches and the NEC restrictions on multiple feeders to a single structure.
Once we have that, our path then is determined by whether the meter-main you selected has a loadcenter interior in it or not.  If it does, then we can simply get two 100A breakers for it (or a 125A and a 100A, if your garage feeder turns out to be bigger than 100A) along with a matching pair of 225A subfeed blocks to provide an effective 400A tap from the panel busses to the house.  In this configuration, the garage panel is a 200A main lug (or main breaker converted to main lug) unit, configured as a subpanel, with a 100-125A feed from the main panel provided to it, and the solar breaker lives directly in the main panel.
If it doesn't, then we'll need either a three-pole power distribution block (UL1953 listed) with 2 250kcmil line and at least 3 250kcmil load ports or a 400A 120/240V tap (terminal) box and a conduit nipple + fittings, along with more 250kcmil Al to jumper between the load lugs of the main breaker and the tap box or PDB, to tap the feeder to provide power to the garage.  Since we are invoking the 10' feeder tap rule in NEC 240.21(B)(1) for the garage feeder in this case, we must run said feeder in conduit (using 250kcmil Al conductors and a 4AWG Al ground) instead of using a SE cable, and position the garage panel so that it is close enough to the main panel for said 10' rule to apply.  Furthermore, we must use a 200A main breaker panel for the garage panel here, also due to the tap rule coming into play.  This additionally means that the solar breaker must live in the garage panel.
Either way, from the garage to the house, we'll need to lay a 3" PVC conduit with 6 250kcmil wires (a pair for each hot and a pair for the neutral) and a 1AWG Al ground in it. At the house, we'll need a 400A, 120/240V, NEMA 3R tap/terminal box to combine the parallel conductors along with 2 200A main breaker panels, configured as subpanels.  Furthermore, since we're again invoking the aforementioned 10' feeder tap rule for the connection from the tap box to the house subpanels, we again must run the tap connections to the breaker panels in conduit, and position the house panels accordingly.
Note that neither of these setups requires an emergency disconnect at the house since it's being fed from service equipment located elsewhere on the property.  Grounding is not hard, either; the garage's ground electrode is wired to the main panel in this configuration, while the house's grounding electrode has a conductor run from it to the Intersystem Bonding Termination device at the house, which then has 4AWG tap conductors run from it to each of the two house panels.
Don't get gassed!
The LA Basin is an oil and gas producing area (still!), and one of the drawbacks of that is that you need to be attentive to the possibility that methane gas may try to seep into your electrical system via underground conduit runs, with obviously bad results.  The normal solution is to use extended range explosionproof Y seals (Eaton/Crouse-Hinds EYSX) in between your terminal adapter/expansion joint threads and the panels or tap boxes themselves, so that these metal fittings get grounded correctly.  Note that they need to be filled with the appropriate sealing compound to do their job!
Don't let your electrical system give you the loose lugnut, either!
If you're planning to install this yourself, note that you'll need an inch-pound torque wrench to meet the NEC 110.14(D) terminal torque requirements.  This is a good idea even if your jurisdiction doesn't enforce this rule, since you really don't want your electrical system to do to you what Greg Biffle's loose lugnuts did to him!
If SCE wasn't so picky...
If SCE lets you apply NEC 230.40 Exception 3, then things become simpler.  The meter box gets replaced with a Milbank U5056-O fitted with a K5049 triple tap kit, and the various 200A panels are fitted out as main panels instead of subpanels; also, there is no need for equipment grounding conductor runs from the meter to the panels, as they are all main panels now.  However, this does introduce the need for an emergency disconnect at the house instead of a simple tap box.  While one could use a fused disconnect for this, given the cost of dummy fuses these days, it's cheaper to use a non-fusible disconnect switch.  That said, 400A NEMA 3R non-fusible disconnects are not cheap or easy to find any more -- the Square-D HU265R is the only one that I can get a reasonable in-stock price for, and that requires you to fit a H600SN neutral kit to it for your application.
Comment: @TheePhaseEel based on your comment, and to avoid buying an expensive 400amp meter main. I think I can use a Siemens HF225NA beside a 324N meter box. Then a tap box at the garage to split out 600kcmil into 2 branches - 100amps to garage and 400amp kcmil to the house. Then at the house another tap box to split that for 2x 200amp panels. I'm worried about tap of a tap rule for this config. That's violated correct? So then I would not tap the garage 100amps. I'd tap that at the house and come back to the garage with it.. correct?
Comment: @RyanPond -- issue #1 is that the HF225NA is NEMA 1 (indoor only) not NEMA 3R (outdoor/rainproof) -- you need a HF225NRA instead.  As to whether you're violating tapping a tap with your proposed arrangement...that's much harder to tell.  I'd lean towards "no" since all the taps are coming off the full ampacity of the feeder, instead of being a "subset of a subset" if you will.  Also note that modern fusible hardware can draw a :( from an insurance adjuster or home inspector who doesn't know how fuses have changed over the years...
Comment: thanks for catching that. I was teaching myself more too. The fact that a tap is defined as an undersized conductor made me feel confident it's not a tap as defined by nec. I have one last question. Pushing the solar back on the garage feeder or sub panel. I worry the feeder conductors can see 400amps + 100amps (80*1.25) backfed from solar = 500amps. What do you see as an option? I think a line side tap makes the most sense? Ideally I'd like to keep the solar after the ocpd for future transfer switch and utilizing solar as backup generation.
Comment: it wouldn't let me edit my question but I wanted to add -- by design I think its ok to push the solar back through the 600kcmil conductors only because the total OCPD protection is 400amps (200*2) from the other panels. So there cant be any power overdrawn.. would the NEC/AHJ accept that?
Comment: @RyanPond -- yeah, there is the question of the math for the solar feed...I'll have to get back to you on that one
Comment: I'm looking at 705.12B,2,1,b and I am interpreting it as the sum (although it doesn't say sum) of the ocpd's on the load side cannot be greater than the ampacity of the feeder.. it's a little stretch but
Comment: @RyanPond -- yeah, that's not an unreasonable interpretation, given that it says "an overcurrent protection device" not "the overcurrent protection device" -- worse comes to worse, you can use another 400A fused switch instead of the tapbox on the house.  (I'm not sure how 705.12(B)(2)(2) comes into play here, for that matter...)
Comment: ThreePhaseEel can I take the 83% rule for the 400amp feeders to the house disconnect device? I ordered a siemens 400amp fused disconnect for the house. And can you confirm my rough choices on cable selection. 400kcmil/400kcmil/300kcmil, 1/0 EGC for the Shop to house (400amp and 83% rule). And 4/0,4/0,2/0, 2AWG EGC for 200amp subs. And the shop to house ground is considered an EGC correct?
Comment: @RyanPond -- yes you can apply the 83% rule in this case, but your cable selection seems to be off (those numbers would be fine to overkill in copper, but are too small in aluminum -- 600kcmil (or 2x250kcmil in parallel) Al shop to house and 250kcmil to the subs is Code minimum in this case).  You are correct that the shop-to-house grounding wire is an EGC, as well.
Comment: Thanks again its very helpful to get confirmation. My selections were all Cu. What am I missing? I was using 310.15(B)(16) to get my 400kcmil Cu from 400*83%. But since its underground can I take some >1.0 multiplier for thermal factor?
Comment: @RyanPond -- nah, you're still at the baseline table ampacities (it's overhead swinging in the breeze that helps, underground is just as bad as a cable buried in a wall full of insulation).  You should be using Al for this run, though (if your AHJ prohibits Al for a feeder this size, then they are *insane*)
Answer: See NEC section 240.21(B)
240.21(B)(2)
So long as it less than 35' to the house panel you can use 300A cables from a fused 400A disconnect next to the meter. else use 400A cables
So long as it's less than 10' to the garage panel you can use 100A cables 240.21(B)(1) from the same 400A disconnect else you'll need 134A cable assuming less than 35' 240.21(B)(2).
Comment: Thanks @Jasen. A detail I am struggling with - when the 400amp feeder lands at the house. Do I need an exterior disconnect at the house? Or can I use a tap box and go directly to 2 200Amp panels?
Comment: If there's an external disconnect at the meter/garage that shuts everything down, you don't need another at the house, AIUI
Comment: @Ecnerwal at that point am I not violating multiple feeders when I tap and split the 400amps at the house? At the garage, after the meter, where do I tap to keep my house supply a service conductor. And if I do that do I have to have a disconnect at the house?
Comment: Jasen's approach sounds like one 400 A service disconnect at the garage, with the feeder being premises wiring.  That is obviously the straightforward approach.  It sounds like Ryan wants to utilize 230.40, Exception No. 3, in which each building effectively has a separate service that comes from the single meter.  Even if that is legal, the utility may not like it. They generally get a veto on things that happen before the service disconnect (and things after it that could backfeed).
Comment: @KevinCathcart my goal is to get get 2, 200amp subs at the house because 400amp panels are expensive and hard to find. Jansens solution is good but how about the next step about landing at the house with 2, 200amps.
Comment: you can land a 400A feeder on a 200A main breaker in the house panel, and then run a feeder from before the main breaker if the first panel to the main breaker of the second panel


jQuery core tabs script - multiple instances?

Question: I have the following jQuery script on my site to switch tabs without reloading the page. I'm using jQuery core v1.3.2 (NOT jQuery UI)

Blog

Videos

Photos

Blog Content

Videos Content

Photos Content

I want to add another instance of this script on the same page, but just copy/pasting this with different variable names doesn't work. Any ideas?
EDIT: Here is my HTML and JS for the second instance. The problem is when I click on a tab in the second instance, it hides all the content divs in the first instance, and vice versa. I want them to be independent of one another.

Chance of Rain (2009)

Debut CD (2007)

Content Goes Here

Content Goes Here

Answer: You have a number of regions in your code where you've hard-coded elements.  I imagine you intend to use another container for the new tabs set, so you'll want to make sure that you change those parts of the code if you're going for a minimum amount of alteration.

Really though, you're probably better served by adjusting everything a little bit so that you're not relying on an interval.
$(function () {
  var mine = $('#content > ul > li > a').click(function () {
    $(this)
      .parent()
      .addClass('selected')
      .siblings('li')
      .removeClass('selected');

    $('#content > div')
      .filter($(this).attr('href') || ':first')
      .show().attr('aria-hidden', 'false')
      .siblings('div')
      .hide().attr('aria-hidden', 'true');
  });

  if (window.location.hash != undefined) {
    mine.filter('[href=' + window.location.hash + ']').click();
  } else {
    mine.filter(':first').click();
  }
});

I believe that second example should come close to achieving the same (though seeing your HTML Structure would help me to verify that) and will be easier to adapt for another set of elements.
Comment: I have updated my question with all the relevant code.

Your suggestion results in some wonky navigation, whereby the clicked tab doesn't give you the correct div.
Comment: @sam-nabi - Thanks for adding some extra code.  I've tweaked my approach slightly (`filter($(this).attr('href') || ':first'`) to address what I think is causing the odd navigation.  Please let me know if that helps.
Comment: We're getting there... it works well (with both instances) except for three things:
1. On page load, all the divs are expanded. Only the first div should be shown; the others should be hidden.
2. Clicking on a tab makes the page scroll down to the appropriate anchor. Is there a way to keep the window position where it is?
3. Pressing the back button does nothing. It should go to the previously loaded tab.
Sorry if these are trivial things; I've yet to wrap my head around PHP!
Comment: @sam-nabi - I've made a few more edits.  Does that resolve some of the errant behavior you describe?  Also, this is not PHP, this is Javascript.
Comment: Javascript, right. It's been a long day. Unfortunately your changes don't seem to have made any difference...
Answer: I found a good solution on this page: jQuery tabs - multiple sets on on page
There's less code duplication this way, too. (Only thing it doesn't do is let you use the back button, but I can live with that.)
jQuery.fn.minitabs = function(speed,effect) {
  var id = "#" + this.attr('id')
  $(id + ">div:gt(0)").hide();
  $(id + ">ul>li>a:first").addClass("selected");
  $(id + ">ul>li>a").click(
    function(){
      $(id + ">ul>li>a").removeClass("selected");
      $(this).addClass("selected");
      $(this).blur();
      var re = /([_\-\w]+$)/i;
      var target = $('#' + re.exec(this.href)[1]);
      var old = $(id + ">div");
      old.hide();
      target.show()
      return false;
    }
 );
}
$('#tabset1').minitabs();
$('#tabset2').minitabs();


How do I replace shower / tub handles / spouts?

Question: I recently bought a house with 20 year old fixtures 3 bathrooms including a shower, shower/tub, and roman tub. The shower knobs say Harden on them and the tub/shower knob has a separate tub/shower lever and the shower knob has a volume control lever. The Roman tub I'm not sure who makes it, but the knobs on the tub match the shower knob so perhaps they are also Harden. What I'm what I'm wondering is:

Can I replace the spouts/knobs without replacing the valves (all of the valves are in walls with no access)?
Assuming yes, how can I find knobs/spouts that will work with the existing valves? (I'm not sure if removing the tub spout requires turning off the water so I haven't wanted to do it yet).

Roman tub:

Shower:

Shower / tub:
Comment: *Why* do you want to replace the valves?  Are they leaking, squeaking, or something?  Or are you wanting to change the aesthetic?
Comment: @wallyk The change is desired for aesthetics.
Comment: I have the exact same assemblies from Harden and was able to find stems, etc., on Symmons sites.
Comment: So replacing the stems would require removing the trim, cutting the pipes, etc.? Or something else?
Answer: Yes: Everything in your pictures falls into the realm of trim.  If you remove the knobs, handles, and spouts, you will find valve and spout stubs.  You should be able to remove all trim without shutting off the water.
Plumbing supply houses should be able to find compatible trim pieces.
Comment: Am I likely limited in what will fit on the existing valves?
Comment: Unless you find the exact model and specs of what's on there now you won't know until you take it off.  For example, a lot of tub spouts just screw on to the bare pipe, but some require hardware behind the wall.  And I've seen a lot of valve stem adapters that open up a wide variety of trim.
Comment: I managed the get the tub knobs off pretty easily, but I'm not sure how to do the spout. There are no set screws anywhere. Is there risk in trying to unscrew it without knowing if that will work? FWIW, my sink faucets match the tub and I can see what they look like under those. Here's a [pic](http://i.imgur.com/d2BHsYr.jpg) (spout in the middle of pic).
Comment: Yep, especially since it's a roman tub spout, it's almost certainly secured from behind with a brass nut like you show on the sink.  You'll have to get wrench access to remove it.  At least you don't have to shut off your water, so long as you can ensure nobody will turn the faucets while the spouts are out.
Comment: That's a bummer though since I don't have wrench access - the tub is all tiled in. If that's the case I may have to wait a few years for till I can take on retiling :(
Comment: Usually there's a way in from the ceiling below or the wall the tub backs up to.  Easier to patch drywall, and if it's in a closet cut it so you can just cover the hole with a plastic access door.
Answer: The good news is that you can tell these are both Harden kits.  I have seen Harden on some older homes but don't know if they still make stuff or not - I certainly have never seen Harden stuff being sold at a plumbing store.
The easiest thing to do is remove all of the trim - anything that is brass.  Take this trim to a local plumbing supply store (with pictures of valve under trim).  They might not even need the trim to match it up with something else compatible but they might need some measurements.
Really there are two hard parts are the handle mechanism which is why they might need the trim there and the tub spout on the wall which might need some slight plumbing alteration - I would take a picture of this and measure your pipe length from wall too.
Comment: My concern would be removing the trim and having to shut the water off while I look and wait for suitable replacements. Also, I'm not sure how to remove the roman tub spout since there are no obvious set screws.
Comment: I am thinking you pop the top off of the handles for the tub and you will see screw underneath.  Also you don't need to shut off water when taking off the trim.
Answer: Try unscrewing the tub faucet itself. I am replacing old brass trim also and couldn't figure out how to remove the faucet from the roman tub. It has no set screw. I had a plumber take a look and he finally twisted the entire faucet counter clockwise and it unscrewed. My problem now is that underneath the faucet is a 3/4" pipe (valve?) that the new trim needs to screw onto. The faucet trim I bought doesn't screw on. It is the new kind of connection that just slides on and has a set screw. I'm looking for a chrome faucet that will screw on because to replace the rough in valve I will have to remove all the tile to get access.
Comment: You don't have to turn the water off to remove the faucet spout, but do not turn the hot/cold handles on without the spout in place or you'll have a water fountain that will shoot to the ceiling. I picked up a 3/4" cap for the spout to prevent any accidents while I had the spout off.


Sorting a vector based on multiple value types

Question: I'm looking to sort a custom struct based on multiple values... I've handled instances where I had to sort by 2 different numbers just fine using < > in a custom sort method... except this time I have to sort by 2 booleans and a number.
struct MyStruct
{
B1 = false;
B2 = true;
N1 = 0;
}

Now... I want it to sort as the following...
Anything that has B1 and B2 true comes first.
Anything that has B1 comes next.
Those 2 sections need to also be sorted by N1 (lower = comes first)
So B1 and B2's need to be ordered N1 lowest to highest.
Followed by just B1's ordered N1 lowest to highest.
Followed by everything else ordered lowest to highest.
Here's my attempt so far...
    if (lhs.boss && lhs.isLOS && lhs.distancetome < rhs.distancetome)
        return true;
    if (lhs.boss && lhs.isLOS && lhs.distancetome > rhs.distancetome)
        return false;
    if (lhs.boss && lhs.distancetome < rhs.distancetome)
        return true;
    if (lhs.boss && lhs.distancetome > rhs.distancetome)
        return false;
    if (lhs.distancetome < rhs.distancetome)
        return true;

    return false;

Comment: What's the problem? This is still just a simple lexicographic order...
Comment: My mind isn't working right I guess...I mean... should I just do

if B1 && B2 and N1 < N2 return true
if B1 and N1 < N2 return true
if N1 < N2 return true
return false
Comment: `  if (lhs.boss && lhs.isLOS && lhs.distancetome < rhs.distancetome)
   return true;
  if (lhs.boss && lhs.isLOS && lhs.distancetome > rhs.distancetome)
   return false;
  if (lhs.boss && lhs.distancetome < rhs.distancetome)
   return true;
  if (lhs.boss && lhs.distancetome > rhs.distancetome)
   return false;
  if (lhs.distancetome < rhs.distancetome)
   return true;

  return false;`
Comment: Can you paste the entire functor method?
Answer: Something like that:
struct complex_comparison
{
    bool operator()(const MyStruct& lhs, const MyStruct& rhs)
    {
        return lhs.B1 && lhs.B2 != rhs.B1 && rhs.B2 ? lhs.B1 && lhs.B2 > rhs.B1 && rhs.B2 :
                                   lhs.B1 != rhs.B1 ? lhs.B1 > rhs.B1 :
                                   lhs.N1 < rhs.N1;
    }
};

Example: http://coliru.stacked-crooked.com/a/b4888ac34d2ca6bb


Get datetime value from registry

Question: hi i save datetime value to registry by this code
string keyName = @"HKEY_CURRENT_USER\ITC";
string keyValue = "test";
string valueT1 = "T1";
string valueT2 = "T2";

 DateTime dateT1 = DateTime.Now;
 DateTime dateT2 = dateT1.AddDays(180);
 Registry.SetValue(keyName, valueT1, dateT1);
 Registry.SetValue(keyName, valueT2, dateT2);

but when i try to get that value again by this code
DateTime regTime1;
DateTime regTime2;
regTime1 = (DateTime) Registry.GetValue(keyName, valueT1, null);
regTime2 = (DateTime)Registry.GetValue(keyName, valueT2, null);

it's give error  "Spesified cast is not valid"
any idea how to do it rightly?
Comment: It's probably saved as a string in the registry. Save it to the registry in a specific format, and read it out using datetime.parse using the same format
Comment: Did you look at the values in RegEdit to see what type they ended up being? As you didn't specify a type when you wrote them, they probably ended up being strings (`REG_SZ`).
Comment: Note that you'd be better off converting date to string (with `"O"` format specifier) and storing resulting string... Parse after reading as string. Less interesting, but way more readable code and guaranteed to do what you want.
Comment: The registry doesn't have a datetime format. The easiest way to deal with it is probably to write it as a string *and* specify the format you want (eg., 'CCYYMMDDHHMMSS`), and then read it back and parse it accordingly into a `DateTime`. Or write it as binary data (`REG_BINARY`) and read it back into a double and then convert that to a `DateTime`.
Comment: @DavidLibido can you give me example how to save it to spesific format because as i see in detail .setValue it's not give information how to do it
Comment: @KenWhite the value saved in registry is "12/23/2014 4:54:42 PM" yeah it's REG_SZ...do you have idea how to spesifict type to save in datetime format?
Answer: You could probably write/read DateTime to the registry with the following methods
These methods are storing the DateTime in the QWORD registry format (A 64-bit binary number)
public static void SetDate(string keyName, string valueName, DateTime dateTime)
{
   Registry.SetValue(keyName,valueName, dateTime.ToBinary(), RegistryValueKind.QWord);
}

public static DateTime GetDate(string keyName, string valueName)
{
   var result = (long)Registry.GetValue(keyName,valueName);
   return DateTime.FromBinary(result);
}

Note : there is no error checking here, and please do due-diligence before using them
the registry is not the place to be playing if you are unsure
Comment: @t3chb0t, Fair comment, and i like your youthful exuberance, you can vote up my answer now :)
Comment: I'm not sure if this has changed, however under .NET 4.5, `Registry.GetValue()` shows params of `string keyName`, `string valueName`, and `object defaultValue`.  There's no mention of an overload that takes a `RegistryValueKind`.  Can you confirm that?
Comment: @Memetican yes you are correct and it was seemingly a mistake, you can pass in a default value or just omit the parameter
Comment: ...the registry is like every other place in windows. I on the contrary encourage to play with it ;-) you can hurt your system every where and the registry is in no way special. just another playground.
Comment: Here you are... I have another 39 to spend today so be the first ;-)
Answer: Try this code:
DateTime dateTime1;
if (DateTime.TryParse((string)Registry.GetValue(keyName, valueT1, DateTime.MinValue),
    out dateTime1))
{
     ........
}

Get datetime value from registry


Choosing points for a 2d Convex Hull

Question: I am making one algorithm a day, and didn't make to finish this one recently.
I have a set of points that i draw, and now I'd like to chose pairs to draw lines between them so that when it's done they will form a convex hull.
My idea was to start from the one that has the lowest y- coordinate, and then go in CCW order, but I am not sure how to write a good algorithm for choosing the pairs.
This question is in fact very simple, it's just me who is a beginner :)
Answer: Have you tried using the Graham scan algorithm? It actually uses coordinate-sorting and CW order.
Comment: Or indeed, any of the other algorithms on the wikipedia page: http://en.wikipedia.org/wiki/Convex_hull_algorithms

Choosing points for a 2d Convex Hull


Get a css parameter without creating an element

Question: I dispose of the following class :
.specialCell {
  padding-left: 10px;
}

I would like to use this value as a property in JS, eg
var specialCellLeftPadding = getCssValue('.specialCell', 'padding-left');

The only way I can think of would be to create an element with the wanted class and get the seeked attribute value :
var tmpElt = document.createElement('div');
tmpElt.className = 'specialCell';
document.body.appendChild(tmpElt);
var specialCellLeftPadding = getComputedProperties(tmpElt).getPropertyValue('padding-left');
document.body.removeChild(tmpElt);

Is it possible to achieve the same purpose without creating and adding an new element to the dom ? (assuming no element with this class exists).
Comment: @Patrick indeed, didn't see this question
Comment: One issue that I see with the approach is that whatever style you'll get will be missing the element's context that may be essential to determine the CSS parameter. For example, you could have this in your CSS: `.specialCell { padding-left:10px; }` and `table#myTable .specialCell { padding-left:30px; }`. Which one should be returned for `getCssValue('.specialCell', 'padding-left')`?
Answer: You can query CSS information directly from stylesheets using the CSSOM. E.g.,

var stylesheet = document.styleSheets[0];

document.getElementById('output').innerHTML = stylesheet.cssRules[0].style.paddingLeft;
.test { padding-left: 12px; }
Padding left:
Comment: Is this cross-browser ? The mdn page is quite evasive on the subject.
Comment: Do you need to know the exact position of the rule in the CSS file? or would it be possible to access it as an index (e.g.: `stylesheet.cssRules[".test"].style.paddingLeft;`)?
Answer: Borrowing from the example of dystroy's answer, you can get a css value using the document.styleSheets property
Using the css
.specialCell {
    padding-left: 10px;
}

and
function getCssProperty(cssclass, property) {
    for (var i = 0; i < document.styleSheets.length; i++) {
        var styleSheet = document.styleSheets[i];
        var cssRules = styleSheet.rules ||  // chrome, IE
                       styleSheet.cssRules; // firefox
        for (var ir = cssRules.length; ir-- > 0;) {
            var rule = cssRules[ir];
            if (rule.selectorText == "." + cssclass) {
                return rule.style.getPropertyValue(property);

            }
        }
    }
}

var prop = getCssProperty('specialCell', 'padding-left');
console.info(prop);

this example will  print 10px in the console


Is it possible to randomly choose a player to be killer?

Question: When playing with friends, we'd prefer if one of us was randomly made a killer, rather than having to explicitly choose ourselves.  Is this possible?
Comment: An Out of game option that always worked for me and my friends is a [virtual dice roll](https://www.wizards.com/dnd/dice/dice.htm). Everyone roles the same die, and whoever gets the highest number is the killer.
Comment: @Malco But no one's supposed to know who the killer is. It's like a Murder Mystery game.
Answer: No, the game does not provide such a feature yet. It is also unsure if it will provide such a feature in the near future.
Comment: Well that's unfortunate.  Why do so many asymmetric multiplayer devs not know their audience?
Comment: It's not a developer decision most of the time.
Comment: Well, I think it has a technical limit for now. The Killer is also treated as the host. In theory, it should be easy to change, but I don't know how they coded it. The request for making the killer a random choice exists for quite a while but hasn't been heard yet so far.
Comment: @Nelson: Of course it's a developer decision.  Who else could it be? The publisher is not going to care about this feature.


angular 5 spring boot 1.5.8 multiple files and multiple properties into one object,using POST ,Request rest api spring boot

Question: I'm using angular5 and Spring boot. How can I send multiple file and some other properties into one object, i  have a class Student, now i have properties like, first name, last name, email, profile image file, id card image file, father id card image file into one object student,how i pass one object that have all things (all properties and some files like idCard image , profile iamge) to springBoot rest api for POST Request.
Answer: http service file:
import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;

@Injectable()
export class HttpClient {
  requestUrl: string;
  responseData: any;
  handleError: any;

  constructor(private router: Router,
  private http: Http,
  private constants: Constants,
  ) {
    this.http = http;
  }

  postWithFile (url: string, postData: any, files: File[]) {

    let headers = new Headers();
    let formData:FormData = new FormData();
    formData.append('files', files[0], files[0].name);
    // For multiple files
    // for (let i = 0; i < files.length; i++) {
    //     formData.append(`files[]`, files[i], files[i].name);
    // }

    if(postData !=="" && postData !== undefined && postData !==null){
      for (var property in postData) {
          if (postData.hasOwnProperty(property)) {
              formData.append(property, postData[property]);
          }
      }
    }
    var returnReponse = new Promise((resolve, reject) => {
      this.http.post(this.constants.root_dir + url, formData, {
        headers: headers
      }).subscribe(
          res => {
            this.responseData = res.json();
            resolve(this.responseData);
          },
          error => {
            this.router.navigate(['/login']);
            reject(error);
          }
      );
    });
    return returnReponse;
  }
}

call your function (Component file):
onChange(event) {
    let file = event.srcElement.files;
    let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
    this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
        console.log(result);
    });
}

your html code:
<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">

Note : This code is working code for me you just need to modify this based on your parameters.
Refer this : Angular - POST uploaded file
Comment: It would be good to see the corresponding Spring Controller method


How can I change the accelerate key in Need for Speed: Hot Pursuit?

Question: I am trying to change the key controls of Need for Speed: Hot Pursuit on Windows 7, but when I go to: Settings → Gameplay Settings → Controls, and I press Enter to change the key configuration, it says "volume down":

I don't have any idea what key that corresponds to.
I have a Lenovo Y470 laptop, which has a Fn key, and if you press Fn + ←, it reduces the volume. Initially, I thought maybe this was what it was referring to, but it doesn't work.
How can I use the accelerate control? What button does this correspond to?
Comment: Hm. I thought maybe it was constantly sending a volume down signal. Can you turn your volume up, or is it constantly being turned down?
Comment: Does your computer have a touch panel at the top? Looking at a picture of it, I can see little dimples there, but I can't tell what they're for.
Comment: @SaintWacko No there is no touch panel ( at top ). Do you have any idea why it is showing volume down? BTW, as 'Volume down' is pressed i can accelerate without pressing any key.
Answer: I had a similar issue but had button Home instead of Volume Up. I tried pressing fn + home and home a few times and then it fixed itself and I could switch to WASD.
Answer: I was having this problem until I disabled the webcam from device manager, then it worked for me.


I want to make a responsive banner

Question: I want to make a responsive banner. Please see the image.
I am using bootstrap. When I see it on mobile screen, the text and bottom images should scale accordingly. Can anyone help me implementing that? All the images, text should be responsive and scale accordingly. Regards.
EDIT
This is my banner normally. On large screen.

When I see it on small screen, the text and images dont scale, instead they overlap.

This is the code to my slider. Also I want the bottom 3 images to be hoizontal, not verticle.

It's color therapy like you've never seen before!

 Colorpeutic is available on mobile for FREE!

 It's no longer a secret - coloring books have transcended age, and have become a worldwide phenomenon. Just relax and paint in a stress-free environment -- let your imagination soar!

Available Free on all major mobile platforms including iPhone, iPad, Google Play and Amazon!

Unlimited colors available for FREE!

Pinch to zoom on all mobile devices!

Categories include mandalas, floral, animals, abstract, landscapes and much more!

Simply pick a color and tap area to fill!

Easy to save your work, share with friends, or share it online!

Comment: Are you requesting someone to write or give code? Show us what you've tried and any obstacles so we can help. Requests are not taken
Comment: I'm asking if you are trying to get someone to hand code to you as your atitude seems like you want want someone else to do your work. Show us things you've tried or look online for resources to start learning. You shouldn't really be here if you don't anything about programming with bootstrap
Comment: I am not a designer. I don't even know the A B C of designing.
Comment: Okay let me show you what i have tried so far.
Comment: @AndrewL, I have updated my question.
Comment: Try adding float=left on the style properties?
Comment: This solved the bottom links issue. Now, how can I make the text and images scale accordingly?
Comment: Not sure off the top of my head—sorry
Comment: You may want to take a look at media queries
http://www.w3schools.com/css/css_rwd_mediaqueries.asp You can set sizes in percentages according to the device size
Answer: I do that thing with the help of display:table and display:table-cell
It's the best way to show your text for me in mobile view also.
you can have a look at this for reference
You can see in it that the text doesn't leave the image and image also behave as a background-size:cover. it's the only reference for you that I wanna show. If it help's you just tell me, I will be happy to know.

I want to make a responsive banner


Installing leviton ODS10 motion occupancy switch on 3 way switch

Question: I'm trying to install a motion sensor occupancy switch on a 3 way switch. It can be used with sensors in 2 locations as shown in instructions below, but I want to use the regular switch at the other end that is already installed, and not a motion sensor. So motion sensor at one end, and regular 3 way switch at other end.
In the switch I am replacing, I have 4 wires (Hot, ground, and 2 travelers) and only 3 wires to connect from my motion sensor switch (black, blue, green) as shown in diagram . I am trying to figure out how to wire them, and if this is possible. Thanks! Let me know if any other information or pics would be helpful.
Answer: That motion sensor is not designed to be a true 3-way switch so it cannot be used the way you want.
If you study the second diagram, you'll realize that it effectively is two single-pole switches in parallel. Either one turning on will turn on the light; both must turn off to turn off the light. If you wire one sensor with one normal switch and you turn on the normal switch, the sensor will not be able to turn off the light.
You need to return the sensor and get a different model that will function as a true 3-way switch.


Self join on amount field not working in Postgres

Question: With below data i am trying to get employees of same location and department with type as manager whose salary is equals to sum of other employees sal
EMP_Name    EMP_Loc EMP_Dept    EMP_Sal Emp_type
Arjun       Hyd     Comp        1000    Manager
Ramesh      Hyd     Comp        500     Interim
Ragav       Hyd     Comp        300     Interim
Rajesh      Hyd     Comp        200     Interim

I have tried this way and returning records correctly  but is it correct way of do it if there is huge data?
select  a.emp_dept , a.emp_loc ,a.emp_dept,b.emp_dept
     from
     (select sum(emp_sal) as sett,emp_loc,emp_dept
                   from employee
                   where emp_type = 'Interim'
                   group by emp_loc,emp_dept
                  ) a
                  inner join
                  (select emp_sal ,emp_loc,emp_dept
                   from employee
                   where emp_type = 'Manager'
                  ) b
     on a.sett=b.emp_sal and a.emp_loc=b.emp_loc and a.emp_dept=b.emp_dept;

Comment: [There's nothing wrong with your query.](https://dbfiddle.uk/?rdbms=postgres_13&fiddle=e745cc13bf9979c4284aea77c0529f6b)
Comment: its not working
Comment: Clearly you can see from the link above that it does work. Suggest you create a Fiddle that demonstrates your issue, otherwise there is nothing to answer.
Comment: What is the error you get?
Comment: no errors first query simply not returning data and second query returning data but is it correct of way do it?
Comment: @Stu i have edited my question , please check now ,not sure why vote down on my question.
Answer:
With below data i am trying to get employees of same location and department with type as manager whose salary is equals to sum of other employees sal

You need a correlation clause:
select *
from employee e
where e.emp_sal = (select sum(e2.emp_sal)
                   from employee e2
                   where e2.emp_type = 'Interim' and
                         e2.EMP_Loc = e.EMP_Loc and
                         e2.EMP_Dept = e.EMP_Dept
                  ) and
      e.emp_type = 'Manager';

For performance, you want an index on (emp_loc, emp_dept, empt_type, salary).
Comment: Thanks Gordon!  how to select e2 data emp_name ,if there are millions of records is it correct way of do it?
Comment: I have tried this way select  a.emp_dept , a.emp_loc ,a.emp_dept,b.emp_dept
     from
     (select sum(emp_sal) as sett,emp_loc,emp_dept
                   from employee
                   where emp_type = 'Interim'
                   group by emp_loc,emp_dept
                  ) a
                  inner join
                  (select emp_sal ,emp_loc,emp_dept
                   from employee
                   where emp_type = 'Manager'
                  ) b
     on a.sett=b.emp_sal and a.emp_loc=b.emp_loc and a.emp_dept=b.emp_dept;
Comment: @user914357 . . . With the right index, this version should be fine.
Comment: hi Gordon , coming back to your answer , how to retrieve e2 details in select statement from your answer?
Comment: @user914357 . . . I believe this answers the question that you asked here.  If you have a new question, you should ask it as a *new* question rather than as a comment.
Comment: Hi , it answers the question i just want to know how to get details of emp2 details rather than raising duplicate question.
Comment: i have posted new question as per your advice https://stackoverflow.com/questions/68593807/how-to-access-columns-from-correlated-subquery
Comment: i have updated my question with joins please check and help


Is the well in the market functional?

Question: The market structure in Banished features a well in the middle of the building. It looks exactly the same as the well structure that can be constructed to help with firefighting in areas of the town that are far from natural sources of water, but does it work in the same manner?
Answer: No.
It is purely cosmetic and does not serve as a source of water during a fire.
Source

Is the well in the market functional?


Protobuf-net & IL2CPP - System.Reflection.Emit is not supported

Question: I have a problem with the protobuf-net and Android app built with IL2CPP.
Everything worked fine when I used MONO instead of IL2CPP for development. Now I need to use IL2CPP for x64 support. I didn't know System.Reflection.Emit is not supported with IL2CPP and protobuf-net is using it.
Is there a way to make the protobuf-net work with IL2CPP?
Answer: I got same problem on iOS. You have to compile ProtoModel before.
using Assembly = UnityEditor.Compilation.Assembly;
private static void BuildMyProtoModel()
{
    RuntimeTypeModel typeModel = TypeModel.Create();

    foreach (var t in GetTypes(CompilationPipeline.GetAssemblies(AssembliesType.Player)))
    {
        var contract = t.GetCustomAttributes(typeof(ProtoContractAttribute), false);
        if (contract.Length > 0)
        {
            MetaType metaType = typeModel.Add(t, true);

            // support ISerializationCallbackReceiver
            if (typeof(ISerializationCallbackReceiver).IsAssignableFrom(t))
            {
                MethodInfo beforeSerializeMethod = t.GetMethod("OnBeforeSerialize");
                MethodInfo afterDeserializeMethod = t.GetMethod("OnAfterDeserialize");

                metaType.SetCallbacks(beforeSerializeMethod, null, null, afterDeserializeMethod);
            }

            //add unity types
            typeModel.Add(typeof(Vector2), false).Add("x", "y");
            typeModel.Add(typeof(Vector3), false).Add("x", "y", "z");
        }
    }

    typeModel.Compile("MyProtoModel", "MyProtoModel.dll"); //build model
    string protoSchema = typeModel.GetSchema(null);//content for .proto file, you can generate a proto file for a specific type by passing it instead of null
}

private static IEnumerable<Type> GetTypes(IEnumerable<Assembly> assemblies)
{
    foreach (Assembly assembly in assemblies)
    {
        foreach (Type type in AppDomain.CurrentDomain.Load(assembly.name).GetTypes())
        {
            yield return type;
        }
    }
}

Copy MyProtoModel.dll from root to Plugin folder.
And use like this:
TypeModel typeModel = new MyProtoModel();

I create small project Protobuf-net & Unity:
https://github.com/koshelevpavel/UniBufExample
https://github.com/koshelevpavel/UniBuf
But it just experimental and it don't have any documents.
Small example MonoBehaviour:
https://gist.github.com/koshelevpavel/8e2d62053fc79b2bf9e2105d18b056bc
Comment: I updated my answer. Please check my gist link. Take this script and paste into your project and after that select tab "Protobuf/Build model" in Unity Editor menu.
Comment: Thank you. So far I tried the steps from [here](https://medium.com/@datdeveloper/using-protocol-buffer-in-unity-ios-android-windows-phone-8-1-4a8ea18e082b) with no luck and [Marc wrote](https://github.com/protobuf-net/protobuf-net/issues/351#issuecomment-363691700) that this solution is not good anymore.
Comment: I will try it and accept the answer when I get it to work. Do I need to create the TypeModel for every .proto file?
Comment: You need call typeModel.GetSchema(type), if type = null function will return .proto for whole model.
Comment: I checked Unity docs and in Unity 2017.4 that I am using the CompilationPipeline.GetAssemblies takes no parameters.
Comment: Could you please explain a bit more how this script should be used? Where and when it should be called? I have no experience with UnityEditor.Compilation and I think I am doing something wrong (I am not getting the .dll file). Thanks again.
Comment: I keep getting errors in Unity Editor when using `MyProtoModel`. No errors when using `RuntimeTypeModel.Default`. The errors are of type - **Could not load file or assembly UnityEngine.UI, UnityEngine.Purchasing, Assembly-CSharp etc.** Do you know what is causing this and how to fix it?
Comment: I case you know how to fix it, please post the answer [here](https://stackoverflow.com/questions/57760099/custom-protobuf-net-runtimetypemodel-in-unity3d-could-not-load-file-or-assembl?noredirect=1#comment101956304_57760099). Thank you.


VBA Stuck after certain loop

Question: I am trying to write a code in excel VBA but am stuck at one point where i need help from you experts please. File is attached
The scenario is this that i have a data where column D has shipment # and when i receive it i put yes in column E. I need to prepare a report where in column E there is blank then if there is blank in column E then copy the shipment number of that blank from column D and paste it in column J which i have already done coding. but now i am stuck as I need to copy the name also which is in column B with same criteria. meaning that for the same shipment number which is copied in column J the name from column B should be copied and pasted in column K by finding the shipment number in column D and then selecting the name from column B for that shipment number.
Image is the data I have

Code:
Comment: Please read [An image of your code is not helpful](http://idownvotedbecau.se/imageofcode) and [edit] your question to add your code formatted as code block. Also include which error you get and in which line, or where exactly you got stuck.
Comment: Sub CopyData()
Application.ScreenUpdating = False
Dim D As Range
For Each D In Range("D2:D500")
If D.Offset(0, 1) = "" Then
D.Copy
Cells(Rows.Count, "J").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
End If
Next D
Comment: Please [edit] your original question. Don't post code in comments, it is not readable.
Comment: Sub CopyData()
Application.ScreenUpdating = False
Dim D As Range
For Each D In Range("D2:D500")
If D.Offset(0, 1) = "" Then
D.Copy
Cells(Rows.Count, "J").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
End If
Next D
End Sub    "this code which i have written it finds the blank cells in column E & then copies cells from column D adjacent left to it. I used offset to copy those cells in column D. but now with the same criteria i want to copy column B but how to proceed an not getting it.Just like column D i want column B also with same criteria.
Answer: Hi Please find the below code , This is working fine at my end.
<code>Sub so()
lRow = ThisWorkbook.ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
lRow1 = ThisWorkbook.ActiveSheet.Cells(Rows.Count, 2).End(xlUp).Row
ThisWorkbook.ActiveSheet.Range("E1").AutoFilter Field:=2, Criteria1:=""
ThisWorkbook.ActiveSheet.Range("D1:D" & lRow).SpecialCells(xlCellTypeVisible).Copy       Range("J1")
ThisWorkbook.ActiveSheet.Range("B1:B" & lRow1).SpecialCells(xlCellTypeVisible).Copy Range("K1")
Selection.AutoFilter
End Sub
</code>
Comment: Sub CopyData() Application.ScreenUpdating = False Dim D As Range For Each D In Range("D2:D500") If D.Offset(0, 1) = "" Then D.Copy Cells(Rows.Count, "J").End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues) Application.CutCopyMode = False End If Next D End Sub "this code which i have written it finds the blank cells in column E & then copies cells from column D adjacent left to it. I used offset to copy those cells in column D. but now with the same criteria i want to copy column B but how to proceed an not getting it.Just like column D i want column B also with same criteria.

VBA Stuck after certain loop


MInecraft Zombie Children on Chickens

Question: I have a small chicken farm and I enjoy playing with aggressive mobs. However I sometimes get a zombie child riding on one of my chickens. I end up having to kill the chicken in the process.
Is there a way to kill the zombie child without killing my chicken?
Answer: A clever but slightly expensive way to accomplish this is to throw a Splash Potion of Healing at it.  The chicken will be healed, but because the baby zombie is undead, he will be injured or killed.
Answer: It sounds like your chicken farm isn't lit up bright enough (level 8) to stop spawning. Either that, or there is a break in your walls that is only 1 block tall. Zombie babies can get through those openings without difficulties.
To get the zombie off your chicken simply leave. When the zombie despawns, the chicken won't. Presto - chicken without a rider.

MInecraft Zombie Children on Chickens


Android Context menu from listsview

Question: I am new to android development, and not very good at programming in general but, I am working on a tab layout that has a listview per tab.  Each tab has it's own java file. I am currently trying to add a context menu that when clicked (not long clicked) on an item in my listview, will bring up a menu so I can choose an option.  Right now it just shows a toast displaying the name of the item I clicked.  The listview options are currently added to the list via local string declaration, here is an example of on of my tabs:
public class AlbumTab extends ListActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
      final String[] CDExplorer_tabs = new String[] {"Client Heirarchy", "Territory", "Sales Credit", "Admin", "General Search"};
      super.onCreate(savedInstanceState);

      setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, CDExplorer_tabs));

      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      lv.setOnItemClickListener(new OnItemClickListener()
      {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id)
        {

          Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
              Toast.LENGTH_SHORT).show();
        }
      });
    }

would I have to make another string array for each menu I want to popup and somehow connect it to the other string?  Or do if statements that decide on which menu to popup based on which listview item is clicked?
Comment: What kind of choices do you want to show on the Context Menu?
Comment: Each of the strings  (client hierarchy, territory, etc) will have multiple choices, I'm just looking for an example I can modify, like when if i click on client hierarchy, the menu is opened up, It will have choices to select that will take me to another page.  So if I click on Client hierarchy, I can choose from options like, firm, name, office location, etc.
Comment: From what I understand you need different options for each item in the list. Context Menu wouldn't be well suited for that.
Comment: Yes I need different options for each list item, what should I use, and how can I apply it?
Comment: If someone could tell me how to do a listview in a listview that would work too, Kind of like the default music player app on the droid.
Comment: Nvm, I ended up making a list open in a whole new window which works just as fine
Answer: First, you if you want each part of the list to have a different menu, make a switch statement in your onItemClick() that depends on your position. switch(position){ //cases and such
Then what you might want to try instead of having a nested ListView is try doing an AlertDialog. Search for adding a list. And then implementing that for each position on your list. Then make sure that you implement another switch inside of the DialogInterface onClick function to call a function to do what you what it to do from the list.//Also make sure to alert.show();.
That would be my recommendation if you want to do it. However, if you want to do nested listviews, its more complicated but possible.
What you need to is implement a custom list adapter for you list. And create a view holder for each that holds a another listview. A good example for that is here.
That should pretty much do it. Mind you that if you decide to do the nested listviews it will be very crowded inside that listview.

Android Context menu from listsview


Icons are not smooth

Question: I have recently upgraded to ubuntu 15.04. But all icons on my left panel are choppy. Is this a bug of new ubuntu or there is a way I can correct it ?
I am attaching the screen shot of the icons.
Comment: An image of these icons might help (upload it to a images hosting and edit into the question the url to the image; someone with enough rep will edit the image into the question)
Comment: Please check the image I have attached.
Answer: I had the same issue with some resolution and iconsize values.
Go to Settings -> Appearance -> Look its the slider at the bottom.
Try chaning the size of the icons one step up or down.
Comment: thanks for your reply. But the problem is still there. Nothing changed by changing icon size.
Comment: Please add the picture to your question then, as Rinzwind suggested.
Comment: Please check the image I have attached.
Comment: Strange, it looked the same on my screen. Have you tried different settings for the size? Only every other one worked for me.

Icons are not smooth


In $\triangle ABC$, $\angle ABC=105^\circ$, $AD=DC$ and $BC=2$. Find the length of $AB$

Question: I found this problem on Facebook from a Mathematics group. Apparently it had appeared as one of the problems on a college entrance exam.

The person who shared it on Facebook did not disclose the correct answer. I'm going to post my own approach below, please let me know if my answer is correct or if there are any other methods possible. (I even encourage solutions that may typically go beyond pre-college level mathematics.)
Comment: If you copy $B$ and rotate the copy about $D$ by $180^\circ$ to $B'$, then $\triangle DBC$ is congruent to $\triangle DB'A$.
Comment: @peterwhy I'm not sure how that helps?
Answer:
1.) Locate $F$ outside $\triangle ABC$ such that $AF \perp BF$. Notice that $\triangle BAF$ is an isosceles right triangle. Extend a line from $C$ such that it meets $BF$ at $E$, where $CE \perp BF$. Notice that $\triangle BEC$ is a $30-60-90$ triangle, therefore $BE=1$ and $CE=\sqrt3$
2.) Notice that $\triangle AFD \cong \triangle CED$. Therefore $AF=CE=\sqrt3$. Finally, by Pythagorean theorem, $AB=(\sqrt2)(\sqrt3)=\sqrt6$
Answer: In $\triangle ABD$, use sine law
$$\frac{AB}{\sin\angle ADB}=\frac{AD}{\sin 45^\circ}\tag{1}$$
In $\triangle BCD$, use sine law
$$\frac{2}{\sin\angle BDC}=\frac{CD}{\sin 60^\circ}\tag{2}$$
Note $AD=CD$ and:
$$\sin\angle ADB=\sin(180^\circ-\angle BDC)=\sin\angle BDC$$
From (1), (2), we get:
$$AB\cdot\sin 45^\circ=2\sin 60^\circ$$
Therefore,
$$AB=\sqrt6$$
Comment: It's way better than the construction
Answer: If you reflect $B$ about $D$ to $B'$, then $\triangle DB'A$ is congruent to $\triangle DBC$:
$$\begin{align*}
DB' &= DB &&\text{By construction}\\
\angle ADB' &= \angle CDB &&\text{Vertically opposite angles}\\
DA &= DC &&\text{Given}\\
\triangle DB'A &\cong \triangle DBC &&\text{SAS}
\end{align*}$$
In particular, $AB' = BC = 2$, and $\angle DB'A = \angle DBC = 60^\circ$.
Consider $\triangle ABB'$, by the sine law,
$$\begin{align*}
\frac{AB}{\sin \angle AB'B} &= \frac{AB'}{\sin \angle ABB'}\\
\frac{AB}{\sin 60^\circ} &= \frac{2}{\sin 45^\circ}\\
AB &= \frac{\sqrt 3}{2} \cdot \frac{2}{1/\sqrt2} = \sqrt 6
\end{align*}$$


TypeError: type datetime.datetime doesn't define __round__ method

Question: I'm working on an API with Python. When trying to parse the data that I got from my database, I got this error: TypeError: type datetime.datetime doesn't define __round__ method.
api.py:
response = []
for i in range(len(histTuple)):
        currentTime = histTuple[i][2].replace(microsecond=0)
        currentTime = str(currentTime) + f" GMT{TIMEZONE}"
        response.append({"humidity": round(histTuple[1][i], 1), "celsius": round(histTuple[0][i]), "fahrenheit": round(histTuple[0][i] * 9/5 + 32), "timestamp": currentTime}) # error here

I'm not trying to round a datetime.datetime, and currentTime isn't even a string!
Comment: Check your index try [i][1] instead of [1][i] for humidity, [i][0] for celcius, and [i][0] for fahrenheit
Comment: This could be written more cleanly (and less prone to error) with a loop like `for hist in histTuple` so that you can access the values inside each tuple as `hist[0]`, `hist[1]` and `hist[2]`.
Answer: My query was in this format: [(temperature,),(temperature,),(temperature,)]
So, flipping the indexes, it worked.


How do I propose my project to be part of Debian too?

Question: I have a new project hosted at launchpad.net. My project can be useful for both: Ubuntu and Debian. However, I can't find a documentation to start host my project at launchpad.net and get my package mirrored back to Debian.

How to propose my project to be part of Debian too?
What is the difference between a Ubuntu and a Debian?
Can I keep it hosted at launchpad.net but ask it to be cross-hosted (and packaged) at Debian too?

Thanks in advance.
Answer: The process for getting a package into Debian is outlined in this FAQ. Once your package is in Debian, it will be automatically imported into Ubuntu.
Debian and Ubuntu use the same packaging system. Binary packages (.deb files) for Debian and Ubuntu are not necessarily compatible but when you package for Ubuntu and Debian you upload source code so that it is built for different architectures. Binary packages are built separately for Debian and Ubuntu.
It doesn't matter where you host your code.
Answer: Basically you need to suggest your package according the the Debian guidelines for New Packages where you need to report a bug that your package be set on the wishlist. Once your package is in Debian it will be mirrored with Ubuntu.
Answer: To request packaging in debian you should read wnpp page and fill a bug with RFP
Comment: If OP had submitted a package there at time time your answer was written, he or she might still be waiting for action today. It's a graveyard.


Update Query with a Twist - MYSQL

Question: I have a table with Column name "Height", the table has millions of records
The Records are show for example
18-24"
30-36"
36-42"
12-15"

and so on...
What i want to do is update the Column so that it looks like below
18-24 inch
30-36 inch
36-42 inch
12-15 inch

Is this possible in MYSQL using SQL Query or i have to do it manually by exporting it in XLS and then find replace ?
Answer: You can do something like :
UPDATE Height SET your_column = REPLACE(your_column, '"', ' inch')

Answer: update yourTable
set height = replace(height, '"', ' inch')

Update Query with a Twist - MYSQL


Get the line number in Edit control

Question: how can you get the current line number in a multi-line edit control?
Comment: Doesn't really matter - he said "winapi" in his tags. While it would be easier to do in C#... :-)
Answer: From the docs for EM_LINEFROMCHAR, if you pass -1 as wParam, you get the line number of the line containing the caret (or the start of the selection if there is one).
Answer: Look at the EM_LINEFROMCHAR window message.
Answer: Did you try checking the MSDN index for anything beginning with EM_*. If you did, you'd find EM_LINEFROMCHAR, EM_LINEINDEX, EM_LINELENGTH, etc, which can probably solve your problem

Get the line number in Edit control


How many possible ways of counting to 100 using only a collection of certain number

Question: SEE EDIT BELOW: Lets say that I have the set {$ 2,3,4,5,6,7 $} and that I want to add multiples $\geq0$ of these elements in different orders (sequences) to get $100$. How many such sequences are there?
At first I thought about the number of non-negative integer solutions to an equation on this form:
$$x_1\ +\ x_2\ +\ ...\ +\ x_n\ =\ k$$
but doesn´t that just count the number of times each element occurs? Can I use this, and if so, how, and then somehow order them and count the number of sequences? How can I do this?

EDIT: Im sorry for the confusion but I need to correct some things, my bad. The goal is to partition the number $100$ into EXACTLY $15$ integers-parts where all these parts must be multiples of elements of the set {$2,3,4,5,6,7$}. I know that the number of partitions of $100$ into exactly $15$ parts is $p(100,15)$, but these include all the partitions using all the numbers from $1$ to $100$, right?
So is there a way to just get the partitions of the set above? Thank you for great answers so far even though I messed the question up!
Comment: OEIS: [A013984](http://oeis.org/A013984)
Comment: @MikeEarnest also $[4,2,2],[2,4,2],[2,2,4]$
Comment: Based on your response to @MikeEarnest, you're interested in counting certain integer compositions rather than integer partitions.  In partitions, the order of the summands doesn't matter, so there are 5 partitions of 4 = 3+1 = 2+2 = 2+1+1 = 1+1+1+1.  But there are 8 compositions of 4 (add in 1+3, 1+2+1, and 1+1+2).
Comment: You need the number of positive integral solutions of $2x_1+3x_2+...+7x_6=100$. Denote the number of solutions of $a_1x_1+...a_nx_n=k$ by $N(a_1,...,a_n;k)$. Then you have recurrent relations like $\sum_{l=1}^{\lfloor k/a_1\rfloor} N(a_2,...,a_n, k-la_1)=N(a_1,...,a_n,k)$. You solve it by considering a generation function.
Comment: @cittee To make I understand what you are trying to count: if the target were $8$ instead of $100$, would the complete list of valid sequences be
$$
[6,2],[2,6],[3,5],[5,3],[4,4],[3,3,2],[3,2,3],[2,3,3],[2,2,2,2]\quad ?
$$
Comment: @MikeEarnest, yes that would be correct without the constraints I forgot to add to the question. I have now added that in the EDIT. Each partition should consist of exactly 15 elements, and one must use the elements in the set I wrote above. So what you did here is the right idea but ONLY those sequences consisting of exactly the right number of elements. Sorry for the confusion...
Answer: Let $a_n$ be the number of sequences that add up to $n$.  Then $a_n=0$ for $n<0$, and $a_0=1$.  Conditioning on the first element of the sequence yields recurrence
$$a_n = \sum_{i=2}^7 a_{n-i},$$
which you can readily use to compute $a_{100}$.

To obtain the generating function $A(z)=\sum_{n=0}^\infty a_n z^n$, multiply both sides of the recurrence by $z^n$ and add them up, yielding
\begin{align}
A(z)
&= a_0 z^0 + \sum_{n=1}^\infty \sum_{i=2}^7 a_{n-i} z^n \\
&= 1+\sum_{n=1}^\infty \sum_{i=2}^{\min(7,n)} a_{n-i} z^n \\
&= 1+\sum_{i=2}^7 \sum_{n=i}^\infty a_{n-i} z^n \\
&= 1+\sum_{i=2}^7 z^i \sum_{n=i}^\infty a_{n-i} z^{n-i} \\
&= 1+\sum_{i=2}^7 z^i A(z) \\
&= 1+A(z) \frac{z^2-z^8}{1-z},
\end{align}
so
$$A(z) = \frac{1}{1-\frac{z^2-z^8}{1-z}} = \frac{1-z}{1-z-z^2+z^8}.$$
Comment: Thanks for the heads up, I overlooked that.  I therefore deleted my answer.
Comment: Yes, I figured that out after I commented, and then deleted my comment.  Your answer is very elegant. +1.
Comment: Thank you for the response! What if my sequence has to consist of exactly $m$ positive integers (using the same set)?
Comment: Please open a separate question for that.
Comment: @RobPratt Would that be better than just editing? I could absolutely do that if it is, I just messed up the question a bit because I missed important points and wanted to correct it. All the answers are great even though they are not exactly what I search for in this particular case. My bad for not being clear
Comment: It is a different question, and you already have answers and comments for the original question.  Better to ask separately.


export IDM download list using C#

Question: I have to make a program to back up my IDM download list every day, because there is other ones using my computer and they removing my download list.
IDM API only lets me add download to IDM list, so is there any library or other way to back up my IDM download list using C#?
thanks for helping
Comment: I don't use this particular application so I can't be sure, but the first thing I'd look into would be UI Automation. See if it exposes the control (listbox?) that holds the desired list, using something like UIA Verify. If that doesn't work, then the brute force approach would be to read its memory using PInvoke.
Comment: Well you can always create another user for `other ones`...
Comment: @Setsu I'm not a pro, but I guess both of these ways needs application to be running, and won't work if it is hidden or closed, please enlighten me if I'm wrong with some non-MSDN example because MSDN website is so complicated for me! I need the program to get the list anyway! no matter application is hidden or not running (there is a free program called IDM backup manager which is gets the IDM download list while IDM is not running) thanks
Comment: thank you @Muctadir but I tried all normal ways! they always using my account and I really want this program to be written!
Comment: I think Muctadir has a point. The simplest solution would be to just get them to use individual (user) accounts rather than deal with this beast of a problem you have here. Trying to coerce another program to do your bidding is never easy; this is especially true if you find MSDN difficult to use.
Comment: @Setsu I tried, my siblings won't help me through it, so I have to do it like sneaky ways!! I always do this kind of stuffs in hard ways! but thanks for the advise anyway.
Comment: @SepehrParsa That's unfortunate. On second thought, IDM is most likely saving that list somewhere on the disk, and it's probably going to be plain text. If you can find it you can just archive that file directly. The first places I would look would be in "My Documents" or "\{username}\AppData\".
Comment: OMG @Setsu you are a genius! I already made a bat file for backing up the IDM info and there is this registry key which is contains all info about the downloads, its: HKEY_CURRENT_USER\Software\DownloadManager but there is a question: this key contains a lots of numerical named keys which contains a value named Url0 that have the links in it. how can I get all Data of string values named Url0 under this key? please answer it as an answer so i can accept it :)
Comment: @SepehrParsa See [this question](http://stackoverflow.com/questions/18232972/how-to-read-value-of-a-registry-key-c-sharp). If you come up with a solution in C#, post a concise sample that demonstrates the key functionality and post it as an answer. As it stands this question has little to do with C#.
Answer: Thanks to @Setsu found out a solution. there is a key in registry which contains all of the URLs. the key is HKEY_CURRENT_USER\Software\DownloadManager and it contains keys which contains values named Url0 with the URL in it.
As an example HKEY_CURRENT_USER\Software\DownloadManager\85\Url0 contains one of added link to IDM download list.
So I searched all of the HKEY_CURRENT_USER\Software\DownloadManager subkeys for Url0 and saved the values to a list box using this code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace IDMListSaver
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
            string[] keys = key.GetSubKeyNames();
            for (int i = 0; i <= key.SubKeyCount-1; i++)
            {
                key = key.OpenSubKey(keys[i]);
                Object o = key.GetValue("Url0");
                if (o != null)
                {
                    listBox1.Items.Add(o);
                }
                key = Registry.CurrentUser.OpenSubKey("Software\\DownloadManager");
            }
        }
    }
}

It definitely can get better, but it solved my problem until here.
So thanks again @Setsu

export IDM download list using C#