Application of Gauss Divergence Theorem

Question:
Consider
$$
\begin{cases}
-\Delta u &= f\quad \text{in} \ \ \Omega\\
\frac{\partial u}{\partial n} &= g \ \ \ \text{on} \ \ \ \ \partial \Omega,
\end{cases}
$$
where $\Omega \subset \mathbb R^n$ is a bounded domain with boundary $\partial \Omega$ , $\Delta$ is the laplace operator, $f$ and $g$ are given smooth functions and $\frac{\partial u}{\partial n}$ denoes the outer normal derivative of $u$.
What is the necessary  and sufficient condition for the following problem to admit a solution?

I am using Gauss divergence theorem in $k$-dimensional space $\mathbb R^k$ which states the following:

Let $F(X)$ be a continuously differentiable vector field in a domain $D \subset \mathbb R^k$. Let $R \subset D $ be a closed, bounded region whose
boundary is a smooth surface, $\Sigma \subset D$ . For each point $x \in \Sigma$ , let $\frac{\partial u}{\partial n}$ be the unit normal vector on $\Sigma$ with respect to the region $R$. Then, with $dX ≡ dx_1dx_2\dots dx_k$ and with $d\sigma$ indicating integration with respect to surface area on $\Sigma$
$$\int_R \nabla \cdot F(X)dX=\int_{\sum}F(X)\cdot n\, d\sigma.$$

Here, $\Sigma = \partial \Omega$ and $R = \Omega$ and $$\frac{\partial u}{\partial n} = \frac{\partial F}{\partial x_1}e_1 + \frac{\partial F}{\partial x_2}e_2 \dots  + \frac{\partial F}{\partial x_n}e_n = F(X)\cdot n.$$
We get
$$\int_{\Omega} \nabla \cdot \frac{\partial u}{\partial n} dX = \int_{ \partial\Omega}\frac{\partial u}{\partial n} dS = \int_{\Omega} \nabla\cdot \nabla u  \ \ dX$$
iff
$$\int_{\Omega} \Delta u \ \ dX = \int_{\partial \Omega} \frac{\partial u}{\partial n} \ \ dS$$
Since $\nabla \cdot\nabla u = \Delta$,
$$\int_{\Omega} -f \ \ dX = \int_{\partial \Omega} g \ \ dS.$$
Please check my Solution, if you find any mistake, then correct me.
Thank you.
Comment: Your usage of MathJax broke something in me, I had to fix it.
Answer: What do you want to prove here? In this context you look for a solution $u$ for the boundary value problem $- \Delta u = f$ in $\Omega$ and $\frac{\partial u}{\partial n} = g$ on $\partial \Omega$ i.e. you consider the Poisson equation with von Neumann boundary conditions. The existence and uniqueness of a solution can be proved under certain assumptions concerning the regularity of the data $f$ and $g$ and the domain $\Omega$ using Gauß or Green's formulas.
Comment: By the way: useful literature in this context are the books from Lawrence Evans and of course Folland's book...
Comment: I  want to find a condition which is necessary and sufficient  for the exisitence of a solution for $f$ and $g$.
Comment: That is not that simple, but refer to the books I mentioned and you will find conditions which imply existence and uniqueness of $u$.
Comment: ok, I will see it,
Comment: tell me about my solution , it is correct or not
Comment: First: I do not see a solution o
Comment: ... in your proof, a solution would provide something like $u(x) =...$ i. e. an explicit representation of the unknown function $u$. But as to your calculation I may say, it is correct. What follows from your observations?

Application of Gauss Divergence Theorem


How do we Move SSRS Snapshot Data from one server to another?

Question: I have a requirement to move SSRS Snapshot data from one report server to another.  I found a way to export the snapshots using PowerShell, but I do not see a way to import the data from there.
Thanks for the help in advance!
<code>This SQL statement shows the snapshot data, but it appears that the data is being streamed into a BLOB in the Segment table.

select * from [dbo].[SnapshotData] SD
    join dbo.History H
      on h.SnapshotDataID = sd.SnapshotDataID
    join dbo.Catalog C
      on c.ItemID = h.ReportID
    join dbo.SegmentedChunk SC
      on SC.SnapshotDataId = SD.SnapshotDataID
    join dbo.ChunkSegmentMapping CSM
      on csm.ChunkId = sc.ChunkId
    join dbo.Segment S
      on s.SegmentId = csm.SegmentId
where 1=1
order by
 c.Path
, sd.CreatedDate DESC
</code>
Answer: what you have there is what you need.  the data is in segment.content.
swap out the reportid in history with the reportid on the new server.
in order load:
history (with the new reportid)
snapshotdata (just goes without alteration)
segmentedchunck (dont load the int segmentedchunkid its an identity)
chunksegmentmapping (just goes)
segment
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


xarray coordinate-dependent computation

Question: I'm using xarray with data for which I have measurements and errors.
I store these along a dimension moment in the dataset with coordinates value and variance.
When I compute for example the mean along a dimension I need values and variances to be treated differently as the former should be combined as
mean_values = sum(values)/len(values)
but the latter as
mean_variance = sum(variances**2)/len(variances).
Currently I'm doing this by forming two new datasets and concatinating them. This is very ugly, convoluted and not suited to more complex calculations. I would like to be able to do this kind of operation in one step, perhaps by defining a function taking values and variances as input and then broadcasting the dataset dimension moment onto it.
Given a dataset q_lp with dimensions moment, time, position:
q_lp_av = q_lp.sel(moment='value').mean(dim='time')
q_lp_var = q_lp.sel(moment='variance').reduce(average_of_squares, dim='time')
q_lp = xr.concat([q_lp_common_av, q_lp_common_var], dim='moment')

where average_of_squares is defined by
def average_of_squares(data, axis=None):
    sums = np.sum(data**2, axis=axis)
    if axis:
        return sums/np.shape(data)[axis]**2
    return sums/len(data)**2

What better ways are there to handle this?
Is it possible to use xr.apply_ufunc and a my_average function to do this in one step and in-place?
Should I no be putting theses into one dataset together at all? q_lp is later on combined with other quantities, also with dimensions moment, pos and time, into a DataSet.

I'm grateful for discussion, ideas, tips and links to examples.
Edit:
To clarify, I don't like splitting the DataArray, handling each moment seperately and concatenating them again. I would prefer a possibility to do the following (untested pseudocode for illustration):
def multi_moment_average(mean, variance):
    mean = np.average(mean)
    variance = np.sum(variance**2)/len(variance)
    return mean, variance

q_lp.reduce(multi_moment_average, broadcast='moment', dim='time')

Minimal working example:
import numpy as np
import xarray as xr

def average_of_squares(data, axis=None):
    sums = np.sum(data**2, axis=axis)
    if axis:
        return sums/np.shape(data)[axis]**2
    return sums/len(data)**2

times = np.arange(10)
positions = np.array([1, 3, 5])
values = np.ones((len(times), len(positions))) * (2 + np.random.rand())
variance = np.ones((len(times), len(positions))) * np.random.rand()

q_lp = xr.DataArray(np.array([values, variance]),
                    coords=[['value', 'variance'], times, positions],
                    dims=['moment', 'time', 'position'])

q_lp_av = q_lp.sel(moment='value').mean(dim='time')
q_lp_var = q_lp.sel(moment='variance').reduce(average_of_squares, dim='time')
q_lp = xr.concat([q_lp_av, q_lp_var], dim='moment')

Answer: I think you can write your function in an xarray-friendly way, and then call it on your data. i.e.
def average_of_squares(data, dim=None):
    sums = (data ** 2).sum(dim)
    return sums/data.count(dim)**2

q_lp_var = q_lp.sel(moment='variance').pipe(average_of_squares, dim='time')

Having them concat-ed in the same DataArray is fine; it might be a more natural fit for items on a Dataset, though.
Does that answer your question?
Edit: re the edited question, I think holding the items in a Dataset rather than a DataArray is most coherent with the data structures. It seems like the mean & variance are two different arrays you want aligned on the same indexes, so a Dataset is ideal
Comment: Thank you for your answer. The re-writing of average_of_squares is interesting and I will look into the use of .pipe, but my main concern was the split operation on q_lp_av and q_lp_var. I will update my question to better reflect this.
Comment: TBC `pipe` is just running a function, this is equivalent: `average_of_squares(q_lp.sel(moment='variance'), dim='time')`
Answer: I found a solution that suits my needs, but am still grateful for more suggestions:
groupby can seperate a Dataset or DataArray along a specified dimension, list thereof creates (key, value) tuples and dict of this has essentially the form of a keyword dictionary. See http://xarray.pydata.org/en/stable/groupby.html
My current solution thus looks like this:
import xarray as xr

def function_applier(data, function, split_dimension=None, **function_kwargs):
    return xr.concat(
                function(
                    **dict(list(data.groupby(split_dimension))),
                    **function_kwargs),
                dim=split_dimension)

Now I can define functions taking specific coordinates as inputs which can be written to also work for e.g. numpy arrays.
(MWE using the specific example of my original question here)
import numpy as np

def average_of_gaussians(val, var, dim=None):
    return val.mean(dim), (var ** 2).sum(dim)/var.count(dim)

val = np.random.rand(12).reshape(2,6)
var = 0.1*np.random.rand(12).reshape(2,6)

da = xr.DataArray([val, var],
                  dims=['moment','time','position'],
                  coords=[['val','var'],
                          np.arange(6),
                          ['a','b']])

>>>da
<xarray.DataArray (moment: 2, position: 2, time: 6)>
array([[[0.66233728, 0.71419351, 0.96758741, 0.96949021, 0.94594299,
         0.05080628],
        [0.44005458, 0.64616657, 0.69865189, 0.84970553, 0.19561433,
         0.8529829 ]],

       [[0.02209967, 0.02152369, 0.09181031, 0.00223527, 0.01448938,
         0.01484197],
        [0.05651841, 0.04942305, 0.08250529, 0.04258035, 0.00184209,
         0.0957248 ]]])
Coordinates:
  * moment    (moment) <U3 'val' 'var'
  * position  (position) <U1 'a' 'b'
  * time      (time) int32 0 1 2 3 4 5

>>>function_applier(da,
                 average_of_gaussians,
                 split_dimension='moment',
                 dim='time')
<xarray.DataArray (moment: 2, position: 2)>
array([[0.71839295, 0.61386263],
       [0.001636  , 0.00390397]])
Coordinates:
  * position  (position) <U1 'a' 'b'
  * moment    (moment) object 'val' 'var'

Note the input names equal to the coordinates for average_of_gaussians. The different operation on each variable in one function and the lack of references to xarray within it are the properties I am after.

xarray coordinate-dependent computation


Year in GUI not showing proper year

Question: public class Output extends javax.swing.JFrame {

    public Output() {
        initComponents();
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("abc.jpg")));
        setSize(400, 700);
        setLocationRelativeTo(null );
        setResizable(false);
        setdate();
    }
    public void setdate(){
        ActionListener obj = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                java.util.Date date = new Date();

                Date.setText(date.getDate()+"-"+(1+date.getMonth())+
                        "-"+date.getYear()+" / "+date.getHours() + ":"
                        + date.getMinutes()+ ":" +
                        date.getSeconds());
            }
        };
        new javax.swing.Timer(1000,obj).start();
}

Whenever I run this code I get every thing OK but while setting year it shows 18-8-116, while it should show 18-8-16 or 18-8-2016.
Comment: You are using a troublesome old class now supplanted by [`java.time.LocalDate`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html). Instead call [`LocalDate.of( int year , int month , int dayOfMonth )`](http://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html#of-int-int-int-). No funky counting on this class; the year 2016 is `2016` as it should be.
Answer: Date stores the year of a date as years from 1900, hence the 116 (1900 + 116 = 2016).
Most of Date's methods have been deprecated since Java 1.1. Until Java 1.8, you better used Calendar or LocalDate from Joda-Time. Since Java 1.8, Date has been superseded by LocalDate, LocalTime, LocalDateTime and their timezoned counterparts, i.e. ZonedDateTime.
So you might want to use a LocalDate here, i.e.
LocalDate date = LocalDate.of(2016, Month.AUGUST, 18);

Comment: Only certain "methods in[`Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) are deprecated."
Comment: oops, yes, it's true. The class Date is not deprecated, but the majority of it's methods. I have corrected that.
Comment: While not entirely deprecated, the class Date is supplanted by the [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes as mentioned in the class documentation.

Year in GUI not showing proper year


Java 8 stream grouping by within an Object containing list of String

Question: I am not so familiar with Java 8 (still learning) and looking to see if I could find something equivalent of the below code using streams.
The below code mainly tries to get tag for each person and then groups them based on this Tag. One person can be associated with Multiple tags - Please let me know if this is a duplicate :(
I was not able to find solution for it online.
The part I want to simplify
Safe assumption - No null checks required
Map<Tag, List<String>> tagPersonListMap = new HashMap<>();
for (Person person: personList) {
    List<Tag> tags = person.getTags();
    String id = person.getId();
    for(Tag tag: tags) {
        tagPersonListMap.computeIfAbsent(tag, k ->new ArrayList<>()).add(id);
    }
}

Entire code for reference
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Scratch {
    public static void main(String[] args) {
        Person person1 = new Person(Arrays.asList(Tag.EMPLOYEE, Tag.UNKNOWN), "123");
        Person person2 = new Person(Arrays.asList(Tag.UNKNOWN, Tag.VISITOR), "345");
        Person person3 = new Person(Arrays.asList(Tag.VISITOR), "678");
        Person person4 = new Person(Arrays.asList(Tag.EMPLOYEE, Tag.UNKNOWN), "910");
        List<Person> personList = Arrays.asList(
            person1, person2,
            person3, person4
        );

        Map<Tag, List<String>> tagPersonListMap = new HashMap<>();
        for (Person person: personList) {
            List<Tag> tags = person.getTags();
            String id = person.getId();
            for(Tag tag: tags) {
                tagPersonListMap.computeIfAbsent(tag, k ->new ArrayList<>()).add(id);
            }
        }

        System.out.println("Final result: " + tagPersonListMap);
    }
}

enum Tag {
    EMPLOYEE("employee"),
    VISITOR("visitor"),
    UNKNOWN("unknown");
    private final String mValue;
    private Tag(String value) {
        this.mValue = value;
    }
}

class Person {
    List<Tag> tags;
    String id;

    Person (List<Tag> tag, String i) {
        tags = tag;
        id = i;
    }

    List<Tag> getTags() {
        return tags;
    }

    String getId() {
        return id;
    }
}

Expected output
Final result: {EMPLOYEE=[123, 910], UNKNOWN=[123, 345, 910], VISITOR=[345, 678]}

Comment: AFAICT there is nothing in Java 8 that will do this. Your code looks fine as it is btw.
Answer: You can do it like this.  To achieve this I essentially converted the tag list and the id to Map.Entry objects of (Tag tag, String id).   So if there were four tags and one Id that would be four entries.  Then I simply grouped them by Tag with a value of List<String>.
Map<Tag, List<String>> result = personList.stream()
        .flatMap(per -> per.getTags().stream()
                .map(tag -> Map.entry(tag, per.getId())))
                .collect(Collectors.groupingBy(Entry::getKey,
                        Collectors.mapping(Entry::getValue,
                                Collectors.toList())));

result.entrySet().forEach(System.out::println);

Prints
UNKNOWN=[123, 345, 910]
EMPLOYEE=[123, 910]
VISITOR=[345, 678]

Having done this I would still stick with what you have.  Sometimes, using streams is like driving a nail with a sledge hammer.
Comment: yup - seems like streams would complicate it over simplifying it :(

Thats what I was afraid of. Thanks for giving it try though :D


How to fillna limited by date in a groupby

Question: I am working with the following Dataframe that has some NaN values inside.
df = pd.DataFrame({'day':[pd.datetime(2020,1,1),pd.datetime(2020,1,3),pd.datetime(2020,1,4),pd.datetime(2020,1,5),pd.datetime(2020,1,6),pd.datetime(2020,1,7),pd.datetime(2020,1,8),pd.datetime(2020,1,8),pd.datetime(2020,6,9)],
                   'TradeID':['01','02','03','04','05','06','07','08','09'],
                   'Security': ['GOOGLE', 'GOOGLE', 'APPLE', 'GOOGLE', 'GOOGLE','GOOGLE','GOOGLE','GOOGLE','GOOGLE'],
                   'ID': ['ID001', 'ID001', 'ID001', 'ID001', 'ID001','ID001','ID001','ID001','ID001'],
                   'BSType': ['B', 'S', 'B', 'B', 'B','S','S','S','B'],
                   'Price':[105.901,106.969,np.nan,107.037,107.038,107.136,np.nan,107.25,np.nan],
                   'Quantity':[1000000,-300000,np.nan,7500000,100000,-100000,np.nan,-7800000,np.nan]
                  })

Out[318]:
         day TradeID Security     ID BSType    Price   Quantity
0 2020-01-01      01   GOOGLE  ID001      B  105.901  1000000.0
1 2020-01-03      02   GOOGLE  ID001      S  106.969  -300000.0
2 2020-01-04      03    APPLE  ID001      B      NaN        NaN
3 2020-01-05      04   GOOGLE  ID001      B  107.037  7500000.0
4 2020-01-06      05   GOOGLE  ID001      B  107.038   100000.0
5 2020-01-07      06   GOOGLE  ID001      S  107.136  -100000.0
6 2020-01-08      07   GOOGLE  ID001      S      NaN        NaN
7 2020-01-08      08   GOOGLE  ID001      S  107.250 -7800000.0
8 2020-06-09      09   GOOGLE  ID001      B      NaN        NaN

My goal is to fillna with the method ffill only for the same Security, same ID and limited for the next 60 days (not the next 60 observations, because there may be more than one observation per day).
Here is what i tried but is not working, it does not replace any of my NaN values
df=df.groupby(['day',"Security","ID"], as_index=False).fillna(method='ffill',limit=60)

The expected output should look like this: (Note that only the second pair of NaN values have been filled)

The first pair of NaN values should not be filled because is not the same Security.
The second pair of NaN values should be filled with the previous observation.
The third pair on NaN should not be filled because they are out of the 60 days scope.

Out[320]:
         day TradeID Security     ID BSType    Price   Quantity
0 2020-01-01      01   GOOGLE  ID001      B  105.901  1000000.0
1 2020-01-03      02   GOOGLE  ID001      S  106.969  -300000.0
2 2020-01-04      03    APPLE  ID001      B      NaN        NaN
3 2020-01-05      04   GOOGLE  ID001      B  107.037  7500000.0
4 2020-01-06      05   GOOGLE  ID001      B  107.038   100000.0
5 2020-01-07      06   GOOGLE  ID001      S  107.136  -100000.0
6 2020-01-08      07   GOOGLE  ID001      S  107.136  -100000.0
7 2020-01-08      08   GOOGLE  ID001      S  107.250 -7800000.0
8 2020-06-09      09   GOOGLE  ID001      B      NaN        NaN

So, my question is, ¿is there a plausible way to fill NaN values limiting the ffill method on a certain period?
Thank you very much for you time.
Answer: You can group the dataframe on columns Security and ID along with an additional grouper for column day with frequency set to 60 days then use ffill to forward fill the values for the next 60 days:
g = pd.Grouper(key='day', freq='60d')
df.assign(**df.groupby(["Security","ID", g]).ffill())

         day TradeID Security     ID BSType    Price   Quantity
0 2020-01-01      01   GOOGLE  ID001      B  105.901  1000000.0
1 2020-01-03      02   GOOGLE  ID001      S  106.969  -300000.0
2 2020-01-04      03    APPLE  ID001      B      NaN        NaN
3 2020-01-05      04   GOOGLE  ID001      B  107.037  7500000.0
4 2020-01-06      05   GOOGLE  ID001      B  107.038   100000.0
5 2020-01-07      06   GOOGLE  ID001      S  107.136  -100000.0
6 2020-01-08      07   GOOGLE  ID001      S  107.136  -100000.0
7 2020-01-08      08   GOOGLE  ID001      S  107.250 -7800000.0
8 2020-06-09      09   GOOGLE  ID001      B      NaN        NaN

Comment: Hi, thank you very much for this usefull tip. It is working very well. What abou if i want to limit this command only to a certain column, i.e. ffill NaN values with this criteria only on one column. I have tried df.assign(**df.groupby(["Security","ID", g])["Quantity"].ffill()) but it is not working.
Comment: @GuillermoCambroneroPérez If you want to forward fill any particular column then you can use `df.assign(**df.groupby(["Security","ID", g])[['Quantity']].ffill())` or `df.assign(**df.groupby(["Security","ID", g])['Quantity'].ffill().to_frame())`
Comment: Hi @ShubhamSharma, I have tried your method but the freq does not seems quite correct.
Can you please help to look into it?

`g = pd.Grouper(key='date', freq='180d')
df5 = df5.assign(**df5.groupby(['customer_id', g]).ffill())`
`
Comment: @ShubhamSharma, for the same id I have, for 2 dates within 180 days, but the amount didn't populate to the NaN value.
Comment: @Danny Its hard to guess with looking at the sample of dataset and code you are trying. Can you provide the sample?
Comment: @ShubhamSharma please refer to below sample. It's basically the same questiona as this post but I have many different IDs and date, just some records are able to populate correctly, some are just still missing.
Answer: Here's my attempt, not sure if this is particularly scalable though:
filled_df = df.groupby(["Security","ID"], as_index=False).fillna(method='ffill')
diffs = df.groupby(["Security","ID"])["day"].diff().dt.days
df["diffs"] = diffs
df["price_isna"] = df["Price"].isna()
df["quantity_isna"] = df["Quantity"].isna()
df = df.drop(columns=["Price", "Quantity"]).merge(filled_df, on=["day", "TradeID", "BSType"])

def reverse_fillna(value, value_isna, diffs, time_limit=60):
    if (value_isna and (diffs <= time_limit)) or (not value_isna):
        return value
    else:
        return np.nan

df['Price'] = df.apply(lambda row: reverse_fillna(row['Price'], row['price_isna'], row['diffs']), axis=1)
df['Quantity'] = df.apply(lambda row: reverse_fillna(row['Quantity'], row['quantity_isna'], row['diffs']), axis=1)

df.drop(columns=["price_isna", "quantity_isna", "diffs"], inplace=True)


getting location in android on a map

Question: if i have the latitude and longitude and i want to open up Google maps to that specific location how do i do so? which intent launches Google maps with a given latitude and longitude to display?
 i have this intent but this intent looks for navigation... i only want it to display the location at the given latitude and longitude
 Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                    Uri.parse("http://maps.google.com/maps?saddr=" + lat
                            + "," + lon));
 intent.setClassName("com.google.android.apps.maps",
                    "com.google.android.maps.MapsActivity");

Answer: Try this :
String uriName = "geo:"+ lat+ "," + lon;
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri)));

It will show map For Latitude and longitude
For Specific location:
String uriName = "geo:"+ lat+ "," + lon+ "?q=my+street+address";
startActivity(new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uriName)));

Other answer

getting location in android on a map


How to create fade animation in my case

Question: I am trying to create a fade in and fade out feature for ng-show. I have read many posts but it seems like they were using old Angular version.
I have something like
<button ng-click="play()"></button>

TEST HERE

JS
$scope.animate = false;
$scope.play = function() {
    $scope.animate = true;
}

CSS
.animate-show, .animate-hide {
  -webkit-transition:all linear 1s;
  -moz-transition:all linear 1s;
  -ms-transition:all linear 1s;
  -o-transition:all linear 1s;
  transition:all linear 1s;

}

.animate-show {
  opacity:0;
}

.animate-show.animate-show-active {
  opacity:1;
}

.animate-hide {
  opacity:1;
}

.animate-hide.animate-hide-active {
  opacity:0;
}

The above codes only show and hide element but doesn't provide animation. Does anyone have idea of how to animate it? Thank you!
Answer: add angular-animate.js file
add dependent module as
 angular.module('myApp', ['ngAnimate']);

and modify the css
.animate-show,
.animate-hide {
   -webkit-transition:all linear 1s;
   -moz-transition:all linear 1s;
   -ms-transition:all linear 1s;
   -o-transition:all linear 1s;
   transition:all linear 1s;
}

.animate-show.ng-hide-remove,
    .animate-hide.ng-hide-add.ng-hide-add-active {
    opacity: 0;
    display: block !important;
}

.animate-hide.ng-hide-add,
.animate-show.ng-hide-remove.ng-hide-remove-active {
     opacity: 1;
     display: block !important;
 }

change ng-animate to class

TEST HERE

here is the Demo Plunker

How to create fade animation in my case


How could I enable hibernation on a Dell Inspiron 5548 running ubuntu focal?

Question: I'm running Ubuntu Focal and I have 15gigs of Ram and 20G of swap space.
Partition: ID-1: / size: 437.52 GiB used: 47.14 GiB (10.8%) fs: ext4 dev: /dev/sda5
       ID-2: swap-1 size: 19.53 GiB used: 0 KiB (0.0%) fs: swap dev: /dev/sda6

I've tried adding acpi=noirq to my grub boot options but it didn't work and it ended up disabling my keyboard.
When I type sudo pm-hibernate and turn the computer back on it starts up normally.
Is there something else I could try?
Answer: To enable Hibernation in 20.04 using swapfile:
Confirm swapfile size matches RAM size

Check the swap that is in use:
sudo swapon -s

If swap partition(s) are found:
sudo swapoff -a
sudo nano -Bw /etc/fstab

Add # before the UUID of the swap partition(s):
# UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX   none   swap    sw     0       0

Add a line for the swapfile, if one does not exist:
/swapfile   none    swap     sw      0       0

Create the swapfile:
sudo fallocate -l XG /swapfile*

where X is swapfile's size in GB:
sudo mkswap /swapfile
sudo chmod 0600 /swapfile
sudo swapon /swapfile

Reboot:
sudo reboot

Add resume location and offset to grub.cfg:

Edit /etc/default/grub:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX resume_offset=XXXXX"

Use UUID from root.

Use offset from:
sudo filefrag -v /swapfile |grep " 0:"| awk '{print $4}'

Update GRUB:
sudo update-grub

Test hibernation:
sudo systemctl hibernate

A hibernate button can be added using GNOME extensions.
Note that there is a slight possibility of getting holes in a swapfile when creating it with fallocate. /var/log/syslog can be searched for the phrase swapon: swapfile has holes to ensure there will be no data loss.
A swap file can alternatively be created using dd:
sudo dd if=/dev/zero of=/swapfile bs=1G count=8

An error when using dd may overwrite your HDD.
Comment: This guy hibernates. Scratched my head for weeks trying to make hibernation work on my Thinkpad, landed here and got it working in 4 minutes. This is the way.
Comment: I was using a swap partition. The piece of the puzzle I was missing was "resume=UUID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" in the Kernel options in the grub config.
Comment: @Frank Barcenas: Thank you for letting us know. I should probably change the instructions to allow for either swap partition or swapfile.


C++ Reading from file incorrectly

Question: There is a certain problem that I would like to have help with. Here is how it goes:
I'm using the following code to read a certain amount of characters into a char array to process later:
char str[15]; // first 16 characters that i need to get from file

  std::ifstream fin("example.txt");
  if(fin.is_open()){
      std::cout<<"File opened successfully \n";
         for(int i = 0;  i<=15; i++)
         {
            fin.get(str[i]); //reading one character from file to array

         }

  }
  else{
      std::cout<<"Failed to open file";
  }

  std::cout<<str;

It works fine for the first 4 or even 5 characters, but when it reaches to 8 it starts to print out garbage characters.
Contents of the example.txt file, from which i read text.
The Quick Brown Fox Jumped Over The Lazy Dog The Quick Brown Fox Jumped Over The Lazy Dog

Output when I read 8 characters:
The Quic�j�

Output when I read 16 characters:
The Quick Brown ASCII

Why is this happening and where did the 'ASCII' come from when I try to read certain length from a file?
And lastly, what kind of code should I utilize if I want to get specific lengths from a file? For example if I want to read the first 4 or 8 or 16 or even 20 characters? It doesn't necessarily have to be into a char array, it can be saved into a string.
Thank you in advance.
Comment: You'll need to put a `'\0'` character after the last one you read from the file.
Comment: std::string line; getline(fin, line); std::cout << line ; // The Quick Brown Fox Jumped Over The Lazy Dog The Quick Brown Fox Jumped Over The Lazy Dog
Comment: Your char array needs to be larger or your loop needs to be < 15 and not <= 15.  C++ is a zero to n - 1 for array indices.
Comment: `read` reads blocks of bytes: http://en.cppreference.com/w/cpp/io/basic_istream/read
Answer: Your char array is only 15 chars long. So this line goes out of bounds:
for(int i = 0;  i<=15; i++)

If i is equal to 15 that's one too many because your array counts from 0 to 14.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <= count them!
There are 15 places starting at 0 ending at 14
Also when strings are stored in memory they have to be terminated by a null character '\0'. Otherwise the function that prints them doesn't know when to stop, which is probably where your garbage is coming from.
So, because the null terminator takes one of your 15 spaces, that only leaves you with 14 to read from the file.
So:
     for(int i = 0;  i < 14; i++)
     {
        fin.get(str[i]); //reading 14 characters (0-13)
     }
     str[14] = '\0'; // add the string terminator at the end of the array.

See if that works.
Comment: Oh yes! The null-terminator, how could i forget? I'm a bloody idiot. Thank you for the answer

C++ Reading from file incorrectly


Display a String in Asp.Net Core 3.0 MVC ViewModel

Question: Currently learning Asp.Net Core. I was learning with Razor pages initially and had everything working fine, but ditched them in favour of familiarizing with MVC first.
Despite online courses etc. I've been struggling for 3 days to get a simple string to display using a ViewModel and now my mind is frazzled!
I want to inject a string into my cshtml page, so that the string can come from a strings library. I had all this all setup and working fine with Razor pages, but I cannot get a simple string to display using MVC unless I use ViewBag. I want to use ViewModel. What am I missing?
Any help would be much appreciated.
AboutViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyApp.Models
{
    public class AboutViewModel
    {
        public string Title { get; set; }

        public void OnGet()
        {
            Title = "Test";
        }
    }
}

AboutController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using MyApp.Models;

namespace MyApp.Controllers
{
    public class AboutController : Controller
    {
        public IActionResult About()
        {
            return View();
        }
    }
}

About.cshtml
@model AboutViewModel
    @{
        ViewData["Title"] = _loc["About Us"];
    }

        @Model.Title

Error:
 NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml, line 22

NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_About_About.<ExecuteAsync>b__12_2() in About.cshtml
+
        @Model.Title
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
AspNetCore.Views_About_About.ExecuteAsync() in About.cshtml
+
        ViewData["Title"] = _loc["About Us"];
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)

Thoughts:
I'm pretty sure I'm crossing over with Razor pages here and my OnGet method is useless for MVC?
I have tried putting all sorts of code into my controller and nothing seems to work.
Response to Suggestion Below:
If I change my controller to:
    public IActionResult About()
    {
        var viewModel = new AboutViewModel();

        return View(viewModel);
    }

then the error disappears but the string still doesnt display.
Comment: You are only returning View() instead return View(InstanceOfAboutViewModel);
Comment: If I change my controller to use [ var viewModel = new AboutViewModel(); ] and [ return View(viewModel); ] then the error disappears but the string still doesnt display. Edited the question above to indicate this.
Comment: You now correctly sent the viewmodel to the view, however it is still empty. The .Title is null
Comment: And yes, the OnGet is useless in the MVC viewmodel
Answer:  public IActionResult About()
    {
        var viewModel = new AboutViewModel();
         viewModel .Title = "Test";
        return View(viewModel);
    }

Comment: Further if u want to set Title in ViewModel you can use properties. i think you havent learn c# properly and u need guidance?
Comment: You're correct. I'm moving over from Java and Android. Just starting.
Comment: if u want further guidance in learning in asp.net core. and u dont want to check documentation i recommend to follow kudvenkat youtube series.
Comment: Cheers Muhammad


How to write code for Server side pagination in ASP.NET Core

Question: I want to implement Server side pagination for loading of some data I want to be loaded into browser. It's working fine Client side  with PageList in MVC but I don't know how to do in Asp.net Core Server side.
This is my Class There I want to show all proporties , even photo (image)
public class HouseDTO
    {
        [Key]
        public int HouseId { get; set; }
        public Nullable<decimal> Price { get; set; }
        public string LiveArea { get; set; }
        public string RoomAmount { get; set; }
        public string HouseType { get; set; }
        public string ImageName { get; set; }
    }

And then my Repisitory
public interface IHouseRepository
{

  public IEnumerable<HouseDTO> GetAllHouses()

}

 public class HouseRepository : IHouseRepository
 {

    private ApplicationDbContext db;

    public HouseRepository(ApplicationDbContext db)
    {
            this.db = db;
    }

    public IEnumerable<HouseDTO> GetAllHouses()
    {
            return db.Houses;
    }
}

And this is my Controller
public class AdvController : Controller
{

   private IHouseRepository db;
   private IHostingEnvironment hostingEnvirnment;

   public AdvController(IHouseRepository db, IHostingEnvironment hostingEnvirnment)
   {
      this.db = db;
      this.hostingEnvirnment = hostingEnvirnment;

   }

   public IActionResult Index()
   {
     var model = db.GetAllHouses();  // How can I do this to Server side pagination?
     return View(model);
   }
}

So How can create Server side Pagination for this action?
public IActionResult Index()
{
   var model = db.GetAllHouses();
   return View(model);
}

I would greatly appreciate it if you help me.
Comment: Note that all you need to do/know is already covered in question you've likely seen in your research - https://stackoverflow.com/questions/446196/how-do-i-do-pagination-in-asp-net-mvc. Some clarification why that was not enough could help targeting answer.
Answer: You can use Skip() and Take(). Make a repository method that will take current position (to skip) and give parameter to Take. Something like:
public House GetPaged(currentPosition)
{
  return db.Houses.Skip(currentPosition).Take(20);
}

Comment: This shouldn't call `db.GetAllHouses()`, though, because that's reducing it from `IQueryable` to `IEnumerable`, which will end up pulling all records before applying `Skip` and `Take. Change that to `db.Houses` (and expose the method instead of making it private) and you're good. The repository *is* the better place for it.
Comment: That's not the distinction I was trying to make. Compare this to Dmytro's answer, which suggests doing this in the controller. That's not good because it assumes that `GetAllHouses` doesn't return a reified set. Your answer is better (the crux of my point).
Comment: I am sure that a service class, using repository is the best place for storing such business logic. And then controller should use service method, not repository directly.
Comment: I see. Thanks. I guess I was trying to improve it further - do what I would do in my code.
Comment: Edited my answer to include suggestions from @madreflection
Comment: @Ljubomir Bacovic thank you for your response. I'am new for this kind of staffs, please can you show me more detail how to do?
Comment: @Anna - as you've likely already found in you research https://stackoverflow.com/questions/446196/how-do-i-do-pagination-in-asp-net-mvc has all the same information with a lot of detail. This answer just rehashes those...
Comment: @Anna,

I assume House is a persistance class? In that case, call it just House, not HouseDTO.

In your repository, you can add a new method

public IEnumerable GetPagedHouses(int pageNumber, int recordsPerPage)
    {
            return db.Houses.Skip(pageNumber*recordsPerPage).Take(recordsPerPage);
    }

In your controller you can call HouseRepository.GetPagedHouses(2, 20);
Comment: @LjubomirBacovic Thank you, Is this Serverside not Client side? I want this to be Server side.
Answer: Take() and Skip() over results of db.Houses is the way to go.
Like this:
// Skip (n) pages and take (x) elements from required page.
return db.Houses.Skip(page*countPerPage).Take(countPerPage);
// As suggested in comments for the answer above, specified code should belong to
// repository method. Initially implemented as a template to be copypasted
// and reused according to your needs.

make sure that page numbering in query is 0-based:
page = 0 if page not specified; page = 0 if you require page #1; page = 1 if you need page #2 etc. And countPerPage meaning is obvious :)
Comment: thank you for your response. I'am new for this kind of staffs, please can you show me more detail how to do?
Answer: I might be a bit late for the party but I wrote a lightweight package to address this issue by giving you the toolkit to build your DB queries using Skip() and Take() as the other answers suggested.
This might be helpful for someone googling around: https://github.com/YannikG/dotnet-pageable-data
Answer: Here's a simple steps to do server side pagination
@model UsersPaginationModel<User>
@*

*@
@{
}

                  User Id
                  First Name
                  Last Name
                  Username
                 Email
                 Password
                 IsActive

            @for (var i = 0; i < Model.Data.Count; i++)
            {

                    @Model.Data[i].user_id
                    @Model.Data[i].first_name
                    @Model.Data[i].last_name
                    @Model.Data[i].username
                    @Model.Data[i].email
                    @Model.Data[i].password

                        <form method="post" action="onActiveButtonClick">

                                @if (Model.Data[i].isActive)
                                {

                                }
                                else
                                {

                                }

                        </form>

            }

    // Buttons to Navigate

            @for (int i = 1; i <= Math.Ceiling((double)Model.TotalItems / Model.PageSize); i++)
            {

                    @i

            }

ViewModel to pass Model/List and other variables :
 public class UsersPaginationModel<T>
 {
    public List<T> Data { get; set; }
    public int Page { get; set; }
    public int PageSize { get; set; }
    public int TotalItems { get; set; }
 }

Controller Action :
    [Authorize]
    public async Task<IActionResult>
    HomePage(int page = 1, int pageSize = 6)
    {
       int skip = (page - 1) * pageSize;

       string q = "SELECT * FROM Users ORDER BY user_id DESC OFFSET @skip ROWS FETCH NEXT @pageSize ROWS ONLY";
       var users = context.Users.FromSqlRaw(q, new SqlParameter("@skip", skip), new SqlParameter("@pageSize", pageSize)).ToList();

       int totalItems = context.Users.Count();
       var userPaginationViewModel = new UsersPaginationModel<UserModelClass>
         {
              Data = users,
              Page = page,
              PageSize = pageSize,
              TotalItems = totalItems
         };
          return View(userPaginationViewModel);
     }

Comment: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it'd be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren't as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?**.
Answer: Server Side Pagination in .NET Core MVC 8.0
View :
@model IEnumerable<Food>
@*

*@
@{
}

                Food Id
                Food Name
                Food Subline
                Mobile
                Email
                First Name
                Last Name
                Country
                 City
                 Zip Code
                 Delivary
                 Address

@section scripts {
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/jquery.dataTables.min.css" />

}

Controller Action Method :
[Authorize]
public async Task<IActionResult> JQueryDataTbServerSidePagination() {
    return View();
}

Controller IActionResult Method To Load Data :
 [HttpPost]
  public IActionResult LoadData([FromBody] DataTableRequest request)
  {
      try
      {
          var draw = request.Draw;
          var start = request.Start;
          var length = request.Length;
          var sortColumn = request.Columns[request.Order[0].Column].Data;
          var sortColumnDirection = request.Order[0].Dir;
          var searchValue = request.Search.Value;

          var pageSize = length != 0 ? length : 10;
          var skip = start != 0 ? start : 0;

          var data = context.Foods
              .Where(x => EF.Functions.Like(x.food_name, "%" + searchValue + "%"));

          if (!string.IsNullOrEmpty(sortColumn))
          {
              data = sortColumnDirection == "asc"
                  ? data.OrderBy(x => EF.Property<object>(x, sortColumn))
                  : data.OrderByDescending(x => EF.Property<object>(x, sortColumn));
          }

          var recordsFiltered = data.Count();
          var jsonData = data.Skip(skip).Take(pageSize).ToList();

          return Json(new
          {
              draw = draw,
              recordsTotal = context.Foods.Count(),
              recordsFiltered = recordsFiltered,
              data = jsonData
          });
      }
      catch (Exception ex)
      {
          return Json(new { error = ex.Message });
      }
  }

Model Class :
public class Food
 {
     [Key]
     public int food_id { get; set; }
     [Required]
     public string food_name { get; set; }
     [Required]
     public string food_subline { get; set; }
     [Required]
     public int mobile { get; set; }
     [Required]
     public string email { get; set; }
     [Required]
     public string first_name { get; set; }
     [Required]
     public string last_name { get; set; }
     [Required]
     public string country { get; set; }
     [Required]
     public string city { get; set; }
     [Required]
     public int zip_code { get; set; }
     [Required]
     public int delivery_charges { get; set; }
     [Required]
     public string address { get; set; }
     public string image { get; set; } = "";
     [NotMapped]
     public IFormFile photo { get; set; }
 }

Comment: Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it'd be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren't as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?.


How to access a nested variable in a referenced Hash.

Question: I'm writing an Ansible Playbook and am trying to access a nested variable inside a referenced hash.
Here is my vars file:
<code>SourceIPs:
  192.168.33.20:
    DestIP: 192.168.33.30
    Port: 22
  192.168.33.30:
    DestIP: 192.168.33.20
    Port: 22
</code>
Here is my task file:
<code>- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs[' {{ansible_host}} '] }}  "
</code>
It fails when executing this saying dict_object has no variable called {{ ansible_host }}. So clearly its not converting that to the IP address of the current host.
However if I modify the task file to include a static host ip like so:
<code>- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs['192.168.33.30'] }}  "
</code>
It works and get the values back for that particular host.
What I'm trying to achieve is get the values back associated to the host I'm currently executing on.
Answer: Never do nesting in Jinja2 expressions. You can use variables inside them without any wrappings:
<code>- name: Testing varibale access.
  debug:
    msg: " Source IP: {{ ansible_host }} corresponding Port IP and Port {{ SourceIPs[ansible_host] }} "
</code>


Inground Conduit Box for Driveway Snow Melting

Question: I'm installing snow melting cables into a concrete and stone paver driveway.  It requires 5 mats rated at 25 Amps and 6000 watts. I also need a 6th small run of heating wire to cover the full area. The cold leads (non-resistive conductor cable) are 10/3 and 20 feet long.
So to get it to my basement I need an in-ground conduit box to run the 6 cables into then splice them with 10/3 NMWU in the box and run those through one or 2 conduits to the house panel.
So my first questions are about the conduit sizes and pulling the wires.
For the cold leads to the conduit box ...
Will 1/2" PVC conduit be to hard to pull through (3 to 15 feet, 2x 90 elbows)?
Is 3/4" overkill?
Can I get 6x - 10/3 wires easily through one 2" conduit?  (3x 90 elbows @ 15-20 feet).
Fill table says 63 max for 10/3 conductors and I will have 6x3 =18 plus ground and sheathing.
Ontario, Canada
Comment: Good grief. Do the lights in your neighbors' houses dim when you turn that on? :D 1/2" is too small. 3/4" may be legal, but conduit is cheap. Go bigger and don't worry about fill tables. Those are for jobs with five miles of conduit where dollars count. 1" minimum.
Comment: Also be aware the underground splices require rated hardware. No nuts for you.
Comment: Thanks. Very useful input so far. Yes ... cost consideration is not an issue so will go with bigger conduit.  I understand the wet location splicing requirements so thanks for that as well.
Comment: Yeah it will be a big draw.  My driveway has a 3 foot drop over 25 feet in length.  At least twice a year after a new snow fall, my car slides down the driveway after I park it.  Very unsafe.  I'm still going to clear the snow but I have to melt that last few millimetres of surface slick snow and ice.
Comment: Since you have plenty of space to work with, use a bigger conduit than you think. I'd even go to 1 1/2" just to make it easy. PVC is too cheap to worry about. And instead of using 90 degree elbows, use two 45 degrees or a sweep elbow to make the pulling easier.
Comment: Definitely will be using a sweep elbow.
Comment: Actually more than $5 per hour for the whole driveway.
Answer: If in only 1 pipe is there a derate for the number of current carrying  conductors? In the U.S. I would be using thhn/thwn wire, but with 25 amp actual draw I would need to upsize the wire to #8 because 125% of 25 is 31.25a . 1-1/2 rigid pvc would allow 18 #8 , i would not try to pull multi conductor cables through conduit it costs more and is not needed since you are running conduit. Thhn/thwn wire is rated for wet locations and would cost less than NMWU. And as Isherwood mentioned since the splices are going to be below grade they need to be listed for wet / direct burial.
On a side note are you going to put insulation under the mats? It will really help with power consumption that is going to be an expensive way to melt the ice and snow.
Answer: Six 30A circuits, eh?
And it requires neutral? Are you sure? There's no logical reason to need neutral, and if their cold cord is 10/3, remember this is cordage and in cordage, the /3 number includes ground.  Regardless, it doesn't change what I'm about to say about conduit derate.  In a split-phase circuit, neutral is not counted for wire count derate.
Here's how the math works with conduit derate (at least on the south side of the 49th parallel). You look at the wire capacity of the wire at its maximum temperature - 90 degrees C for THWN -2, THHN or NM -B.  Multiply by 80% for 3-6 wires, 70% for 7-9 wires or 50% for 10-20 wires.  And in split-phase supply, all circuits have 2 wires that count.  So with 3 circuits, #10 wire is good for 32A, with 4 circuits 28A (which you can still get away with) and 5-10 circuits only 20A (no good at all).
So I recommend 2 conduits with 3 circuits per conduit.
Each conduit only needs 1 ground wire.  You don't need to design for each circuit to have a ground fault at the same time!
That's either 7 or 10 wires depending on if you need neutral. Both are allowed in 3/4" conduit, but 10 wires in 3/4" is the statutory limit, and that means a very challenging pull.
However if you are very committed to 6 circuits in 1 conduit, you must derate 50%.  You need 30A service, so you need wire capable of 60A at its highest operating temperature.  For THWN-2, that's #6 copper or #4 aluminum, which allow 75A which you derate to 37.5A. Assuming 13 wires (12 conductors + 1 ground), you'll want 2" conduit for #6Cu or 2-1/2" conduit for #4Al, to keep the pulling effort "merely brutal" instead of totally impossible.  If neutrals are required go up another 1/2".
Upside, with #4, remarking is now allowed, so you can buy all black and tape it white or green for neutral and ground.  Downside, you need to provide large cavities for wire splices with consideration for bending radius.
Comment: ... Oh.  Well, that is a horse of a different color.
Comment: @FredoCorleone From the documents it appears 1 of the 3 conductors is ground, and the other 2 are marked L and N.  Assuming your heat cable leads are red and black (their code for 240V), what they really mean is (on 240V in North America) L1 and L2.  Neutral is not used, even though a wire is labeled N for compatibility with Europe.
Comment: I probably didn't explain the layout enough.  I have 6 separate heating pads.  EACH is 25 Amps (or less).  Total of 150 AMPS (ish).  Each heating pad has a "cold lead" that will need it's own 3/4" or 1" conduit to a conduit box.  Each of these will be waterproof spliced inside the box.  Then I will have 24 THWN wires to run to the house in a 2" conduit and then to the controllers and sub-panel inside the basement.
Comment: Thanks I'll go with 2 conduit to the house.  I added a pic to my post.  There are 3 conductors going to the heating cable.


Using a conversion function to make something an instance of a type class

Question: Let's say I have:
data MyType
myToDouble :: MyType -> Double

Let's say I want MyType to be an instance of Num or Real or something that Double is already an instance of.
Is there a simple way to accomplish that without having to manually writing out all the methods in Num/Real for it?
So... is there some way of just saying:
instance Real MyType by way of myToDouble

Answer: Definitely not; Real depends on Num, and Num has methods which return a (or more accurately, are covariant in a).  How are you going to implement:
(+) :: MyType -> MyType -> MyType

given just MyType and myToDouble?
Now maybe you already have all the other instances and are just wondering about Real.   Well, the only method Real has is of its own toRational, so:
instance Real MyType where
    toRational = toRational . myToDouble

As for your more general question: unfortunately not.  If you have a class whose methods are all contravariant (only take as arguments) in the type variable, then you should be able to automatically define a typeclass on a projection like this.  But Haskell has no mechanism to do so.  (You could write one yourself using Template Haskell).
You can "forward" a newtype's instances to its underlying type using GeneralizedNewtypeDeriving.  Eg.
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype MyType = MyType Double
    deriving (Eq,Ord,Show,Num,Real)

But you can't use any old isomorphism.  It's a shame.


How to disable specific values in input range?

Question: Hello I have an input range with values 0-380 and I want to disable some value, like ID 30. So when I select 29 and press the right arrow, it must be change to 31.
Answer: Just check if the slider.value is on a certain number, and if it is, do something to avoid the number. Here's a simple way I thought to fix this, but this is by no means the best way.

var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;

function removeNum(num) {
    if (slider.value == num-1) {slider.value++}
  else if (slider.value == num+1) {slider.value--}
}

slider.oninput = function() {
  output.innerHTML = this.value;
  removeNum(10) //Doesn't allow slider to go to number 10
}
 <input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Value:

Comment: Thank you for the quick answer, its almost working, but now the value stuck in 9-11. (with using the keypad arrows)
Comment: Perhaps this article can help you? https://stackoverflow.com/questions/23014375/how-to-disable-specific-values-from-input-type-range


Connect Excel to PostgreSQL via ODBC

Question: I am trying to connect to a PostgreSQL database table from Excel via the PostgreSQL ODBC 32-bit driver.
In Excel, I go to Data>Get Data> From Other Sources> From ODBC. I navigate to the ODBC data source I set up, enter the credentials, and it clearly connects as the available tables appear. The preview fails and the query fails when I hit "Load" giving the error:
DataSource.Error: ODBC: ERROR [HY000] Error while executing the query
Details:
    DataSourceKind=Odbc
    DataSourcePath=dsn=PostgreSQL
    OdbcErrors=Table

When I test the connection in ODBC admin it is successful. I have tried both the ANSI and Unicode drivers. TIBCO Spotfire connects to the ODBC datasource and pulls the data in just fine.
Any help you can provide would be greatly appreciated.
Comment: Do you have any special permissions/restrictions on viewing the specific table from a DBA standpoint? Have you tried using a full admin's credentials?
Comment: Can you please showing at least the structure of the database and the table name? Especially if there is a underscore `_` in it like `the_name`?
Comment: @JosephSerido Not that I am aware of. This is a hosted, AWS RDS PostgreSQL database. I am using the credentials I set up with the instance. Every other viewing platform like Spotfire or PGadmin, is reading the table(s) with no extra effort.
Comment: @AxelRichter yes, sorry. It contained a customer name so I didn't want to. Neither the database name nor the table name contains an underscore. The formats are 'ABCquickbase' and 'CompanyTracking', respectively. The structure of 'CompanyTracking' is 131 records by 14 fields. It should be noted that the error occurs for both tables in the database. Thanks.
Answer: This appears to be a bug with the latest psqlODBC driver, which is psqlodbc_09_06_0500 at the time I'm writing this. I have access to my PostgreSQL server logs. Here's the error message and the offending query:

ERROR:  syntax error at or near "ta" at character 553
STATEMENT:  select ta.attname, ia.attnum, ic.relname, n.nspname, tc.relname from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class tc, pg_catalog.pg_index i, pg_catalog.pg_namespace n, pg_catalog.pg_class ic where tc.relname = 'rates' AND n.nspname = 'public' AND tc.oid = i.indrelid AND n.oid = tc.relnamespace AND i.indisprimary = 't' AND ia.attrelid = i.indexrelid AND ta.attrelid = i.indrelid AND ta.attnum = i.indkey[ia.attnum-1] AND (NOT ta.attisdropped) AND (NOT ia.attisdropped) AND ic.oid = i.indexrelid order by ia.attnumselect ta.attname, ia.attnum, ic.relname, n.nspname, NULL from pg_catalog.pg_attribute ta, pg_catalog.pg_attribute ia, pg_catalog.pg_class ic, pg_catalog.pg_index i, pg_catalog.pg_namespace n where ic.relname = 'rates_pkey' AND n.nspname = 'public' ANDic.oid = i.indexrelid AND n.oid = ic.relnamespace AND ia.attrelid = i.indexrelid AND ta.attrelid = i.indrelid AND ta.attnum = i.indkey[ia.attnum-1] AND (NOT ta.attisdropped) AND (NOT ia.attisdropped) order by ia.attnum

Here's the context around character 553: order by ia.attnumselect ta.attname, ia.attnum. Note that it's missing a comma between two field names.
I was able to get it working with psqlodbc_09_06_0200, which is about a year old. Since it sounds like you use 32-bit Office, you can download psqlodbc_09_06_0200-x86.zip from https://www.postgresql.org/ftp/odbc/versions/msi/. (Use x64 if you have 64-bit Office installed.)
You might be able to experiment with driver versions between psqlodbc_09_06_0200-x86.zip and psqlodbc_09_06_0500-x86.zip as the bug was presumably introduced somewhere between those two versions.
Comment: I'm running into the same issue but using PostgreSQL Unicode (x64) driver version 10.03 which is a later version than the above driver. Do you know any other way of resolving this issue?
Answer: You can skip this error by removing the navigate step and querying the information you need throw an SQL statement.
For example if you want to retry some information from LineItemExport the default query is something like this:
let
    Source = Odbc.DataSource("dsn=name", [HierarchicalNavigation=true]),
    quickbase_Database = Source{[Name="quickbase",Kind="Database"]}[Data],
    public_Schema = quickbase_Database{[Name="public",Kind="Schema"]}[Data],
    LineItemExport = public_Schema{[Name="LineItemExport",Kind="View"]}[Data]
in
    LineItemExport

You have to change the source step in the query editor or change the code to something like this:
let
    Source = Odbc.Query("dsn=name", "select * from public.LineItemExport")
in
    Source

This is the way you can came over the error, otherwise you should try to change your drivers version.
Comment: @Confounded this is best method to connect to a PostgreSQL db in Excel:

**1** [Download the PostgreSQL ODBC driver for Windows](https://www.postgresql.org/ftp/odbc/versions/msi/) -I use v10.3
**2** Enter your DB credentials. Go Start > ODBC Data Sources (64 bit)
**3** Open Excel > File > Options > Data > Tick the 'From Data Connection Wizard (Legacy)' option
**4** Click Excel Data Tab>Get Data>Legacy Wizards>From Data Connection Wizard (Legacy) > ODBC DSN > [Your ODBC Datasource name] > Choose View
**5** Data loads into table and you can right click & refresh for live data
Comment: Have you found any other solutions to solving this issue, as I feel this is a bit long-winded for some users, especially those who are not used to changing / reading code. Unfortunately I have run into the same issue as OP and your solution works, but it's not ideal for someone who frequently pulls in 5+ data sources a day.

Interestingly you can pull this through using the "Legacy Data Connection Wizard" - but this doesn't have the nice search bar UI.
Comment: @rup  Could you please elaborate on what you mean by "Legace Data Connection Wizzard"?  Or maybe you found other solution?  The one offered here  does not allow for query folding so not workable for me unfortunately.  Thanks

Connect Excel to PostgreSQL via ODBC


Ordering UK Regions (NUTS)

Question: I'm designing a form that requires me to collect a user's region using the NUTS 1 standard for the options.
At the moment I'm ordering by the NUTS 1 Code which gives this:
NUTS 1 Regions
North East
North West
Yorkshire and the Humber
East Midlands
West Midlands
East of England
London
South East
South West
Wales
Scotland
Northern Ireland
The East-West, North-South ordering of the English regions instinctively feels preferable to purely alphabetical, but I'm less certain about the arrangement of Northern Ireland, Scotland and Wales.
Is there a standard for the arrangement of the NUTS regions? I suspect there isn't.
If not, is there a standard for ordering the countries of the UK which would apply here?
Answer: There obviously is a standard listing, as evidenced by the coding (illustrated on the map in Wikipedia):

What you could do, to illustrate the order, if you don't want to provide a map, is list the codes:

UKC North East
UKD North West
UKE Yorkshire & Humber
UKF East Midlands
...
UKL Wales
UKM Scotland
UKN Northern Ireland

This should absolve you of any charges of arbitrariness or prejudice. A map also serves to illustrate just how arbitrary the regions are: Lincolnshire (east coast of F) isn't really East Midlands; and the area where F, G, J and K are in close proximity can fall foul of personal preference.
Even if you don't actually list the codes or include a map, using the code order means that the decision is Eurostat's, not yours.
Don't forget UKZ (extra-regio, which presumably includes Gibraltar, the Channel Islands and the Isle of Man).
Answer: I'd include Scot/NI/Wales in your north-south (major axis), east-west (minor axis) classification. It's essentially scanning the UK from top to bottom a row at a time, Scotland's at the top like it would be in a map, London/South-East at the bottom.
<code>Scotland
Northern Ireland
North West
North East
Yorkshire & Humber
Wales
West Midlands
East Midlands
East of England
South West
South East
London
</code>
You could of course do a map, but that's assuming a bit more of a leap in geographical knowledge of your users (and the fact London makes a small target). Another alternative is location sniffing through your browser, but again that's a fair lump of technical work to convert to a region of the uk.
If you want something like a 'standard', the ONS has this list --> http://www.ons.gov.uk/ons/guide-method/geography/beginner-s-guide/eurostat/index.html but they just bung wales/scotland/ni at the end as well, which from experience can annoy.
Comment: Location sniffing in the browser is fraught with difficulty as the user has to give permission and even then it could rely on IP address, which to all intents and purposes is useless for geolocation in the UK.
Answer: I think the best alternative is to put the 'non England' bits at the top of the list.
For some reason (size?) I would order them like this
Scotland
Wales
Northern Ireland
Visually it 'gets them out of the way' before the user starts to scroll through the England list.
And then follow on with the England regions as you have them.
Comment: Why at the top, and not, say, at the bottom? This feels opinionated and with little backing to the suggestion.
Comment: At the top as it "gets them out of the way".  Most of the list are parts of England, so a short scroll will show all the constituents parts of the UK.   If you put them at the bottom of the list all the user will see will be (parts) of England until they've scrolled right down to the bottom of the list.   This also keeps people from the geographic margins of the UK happy as the London media tends to ignore them, and they rightly might feel marginalised.

Ordering UK Regions (NUTS)


resize or crop base64 images using php

Question: I'm uploading images from the pc to a server using this php code
  $ImageToLoad=mysql_real_escape_string($_POST['image_attached']);

if($ImageToLoad){

$token=$token;//variable
$ImageToLoad = str_replace('data:image/png;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace('data:image/jpeg;base64,', '', $ImageToLoad);
$ImageToLoad = str_replace(' ', '+', $ImageToLoad);
$fileData = base64_decode($ImageToLoad);

$destino_path="/images/$token/image.png";

file_put_contents($destino_path, $fileData);

}

It works ok.
PROBLEM
I need to know how to resize it/crop them before to store the image in the server. Otherwise it keeps the same size (problem when huge image)
Comment: related https://stackoverflow.com/questions/14649645/resize-image-in-php
Comment: its actually not. this is not a file, is a bas64 image.
Answer: Resizing images can be is a costly operation and should be handled by a specialized library. In the past, the default pointer was ImageMagick's Imagick::resizeImage. However, this package does not work for everybody and other solutions have emerged in the meantime.
I suggest gumlet's php-image-resize. Resizing a base64 encoded image can be as simple as that:
$image = ImageResize::createFromString(base64_decode('R0lGODlhAQABAIAAAAQCBP///yH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=='));
$image->scale(50);
$image->save('image.jpg');

Comment: It's not that hard. Just use composer, if available, or put the lib source files on the server and include `'/path/to/ImageResize.php';`
Comment: OK...I see the point. but I dont actually use libraries...do I need to install it on the  server?
Comment: Note that gumlet uses a namespace. So it would look like: `\Gumlet\ImageResize::createFromString(....)`
Answer: If we want to create a temp image from an image file for resizing, we can use
imagecreatefromjpeg($filename);

or
imagecreatefrompng($filename);

If we want to create a temp image from blob we can use
imagecreatefromstring($blob);

imagecreatefromstring()
So, give this a try:
<?php
$filename = 'folder_name/resized_image.png'; // output file name

$im = imagecreatefromstring($fileData);
$source_width = imagesx($im);
$source_height = imagesy($im);
$ratio =  $source_height / $source_width;

$new_width = 300; // assign new width to new resized image
$new_height = $ratio * 300;

$thumb = imagecreatetruecolor($new_width, $new_height);

$transparency = imagecolorallocatealpha($thumb, 255, 255, 255, 127);
imagefilledrectangle($thumb, 0, 0, $new_width, $new_height, $transparency);

imagecopyresampled($thumb, $im, 0, 0, 0, 0, $new_width, $new_height, $source_width, $source_height);
imagepng($thumb, $filename, 9);
imagedestroy($im);
?>

Comment: simply change your output name.. $filename = "$desintao_path";
Comment: this is what I was looking for....but once created how do I upload it to the server? I think I wont be able to use `file_put_contents($destino_path, $fileData);` anymore1

resize or crop base64 images using php


Should we close specific programming questions?

Question: There are now and then questions like this one.
It's a clear and laser-like focused Q. All good. However, it's basically a die-hard computer programming question on a specific EEG toolbox in PsychoPy. Now, EEG is more than on-topic here, and today no scientist escapes this in siliconized arena of science. However, as I write in a comment on the linked question:

I think a specific question like this is more suitable for the
  PsychoPi forum and your duplicate question there has four replies.
  Personally, I do not post any questions on the MATLAB PsychToolbox
  here either; as the respective forum is more suitable for these kinds
  of specifics. I went over to Bio Informatics SE and they regard your
  question as offtopic there, so migration is not an option. It will
  likely not be answered here either. Would you mind if this question is
  closed?

The reference to PTB-3 is quite apt - I would never ask a question on specific PTB-3 questions, as its respective forum is the prime place to go. Likewise, the PsychoPy forum has provided OP's Q over there with multiple answers.
Can we close specific scripting questions regarding toolboxes / programming environments with a custom close-reason as being too specific?
With custom I mean that no standardized close reason is asked for, I'm just asking for feedback from the community. I left thw linked question open for now.
Answer: I would not close them. Those questions are on-topic. We are simply not a big enough community yet to ensure we have all the knowledge available here. Closing questions of people who might actually bring in that knowledge seems counterproductive.
Instead, I would (as you did) simply comment that there might be more suitable places to ask, and you could even encourage them to post an answer themselves once they have found it.
Comment: Not 100% certain. This is not so much a feature as it is a guideline. faq might be more appropriate.
Comment: can I use he tag status-completed for this? Or is it off?


Property without setter cannot be assigned to

Question: I am writing a spec flow test with three columns...
example:
|Field  | Key       | Value |
|A      | aa        |   ""  |
|       | bb        |   ""  |
|       | cc        |   33  |
|       | dd        |   1   |
|B      | aa        |   5   |
|       | bb        |   4   |
|       | cc        |   2   |
|       | dd        |   ""  |

I added this method to read data from the table:
      var elements = new Dictionary<string, Dictionary<string,string>>().ToList();
        var data = table.CreateSet<SpecFlowData>();
        elements.AddRange(collection: from item in data
                              let field =item.Field
                              let key = item.Key
                              let value = item.Value
                               select new Dictionary<string, Dictionary<string,string>>()
                                  {
                                      Keys = field,
                                      Values = new Dictionary<string,string>()
                                          {
                                              Keys= key,
                                              Values = value

                                          }

                                  }

                              );

I am trying to assign a key value pair for each field in the first column.But I get error "Property without setter cannot be assigned to" while building the code. Any idea is appreciated. Thank you.
Answer: You can't assign Keys and Values to Dictionary<> directly. But you can project data to proper Dictionary of Dictionaries using LINQ:
var result = data.GroupBy(i => i.Field, (k, v) => new
                          {
                             Key = k,
                             Values = v.ToDictionary(x => x.Key, x => x.Value)
                          })
                 .ToDictionary(x => x.Key, x => x.Values);

Answer: You can't specifically set the Dictionary<,>.Keys or Dictionary<,>.Values properties. They are only get properties. You need to loop through your values and use the Add(Key, Value) or use the LINQ ToDictionary<TSource, TKey> method.


How to set a single, main title above all the subplots

Question: I am using pyplot. I have 4 subplots. How to set a single, main title above all the subplots? title() sets it above the last subplot.
Answer: Use pyplot.suptitle or Figure.suptitle:
import matplotlib.pyplot as plt
import numpy as np

fig=plt.figure()
data=np.arange(900).reshape((30,30))
for i in range(1,5):
    ax=fig.add_subplot(2,2,i)
    ax.imshow(data)

fig.suptitle('Main title') # or plt.suptitle('Main title')
plt.show()

Comment: Note, it is `plt.suptitle()` and not `plt.subtitle()`. I did not realize this in the beginning and got a nasty error! :D
Comment: Works with `suptitle`. Still, I saw your "shameless hack!" :)
Answer: A few points I find useful when applying this to my own plots:

I prefer the consistency of using fig.suptitle(title) rather than plt.suptitle(title)
When using fig.tight_layout() the title must be shifted with fig.subplots_adjust(top=0.88)
See answer below about fontsizes

Example code taken from subplots demo in matplotlib docs and adjusted with a master title.

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

Comment: Simply adding `figure.suptitle()` is not enough since titles of subplots will mix with suptitile, `fig.subplots_adjust(top=0.88)` is good.
Answer: If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)

Comment: In python 2.7 it is **fontsize** instead of **size**.
`plt.suptitle("Main Title", fontsize=16)`


FileNotFoundError when using python -m pytest vs. pytest

Question: I recently changed the IDE I am using to VSCode. For the most part I like it, but there is one particular problem that I can't seem to resolve. I didn't realize it was a problem either, until I moved IDEs.
I have a directory structure like this:
my_app
├── env
│   ├── bin
│   ├── include
│   ├── lib
│   ├── lib64 -> lib
│   ├── pyvenv.cfg
│   └── share
├── my_app
│   ├── expected_results
│   ├── __init__.py
│   ├── test_data
│   └── tests
├── pytest.ini
├── README.rst
├── setup.cfg
└── setup.py

When I launch my virtual environment I am sitting at the root of this directory structure.
I run my tests by issuing this command (or providing additional options). This currently works:
pytest

But, when VSCode launches, it spits out an error saying it can't find an expected file:
E   FileNotFoundError: [Errno 2] No such file or directory: 'my_app/expected_results/expected_available_items.yml'

After some investigation, I figured out that this is because when VSCode launches it issues the following command:
python -m pytest

I am setting that path by doing this:
import pathlib
EXPECTED_RESULTS_BASE = pathlib.Path("my_app/expected_results")
expected_results = EXPECTED_RESULTS_BASE.joinpath('expected_available_items.yml')

What do I need to modify so that my tests will continue to operate when I just issue a pytest command AND will operate if I (or my IDE, apparently) issues python -m pytest?
I hope it's safe to assume that VSCode is launching this from the root of my_app like I am?
Comment: Use paths relative to a module using `__file__`, e.g. `EXPECTED_RESULTS_BASE = pathlib.Path(__file__, '..', 'expected_results').absolute()`.
Answer: Probably not enough information to answer this for you straight out, but lets try some things:

In your test code, above the line where you are getting the error insert some lines like these and see if they print out what you're expecting

print(os.getcwd())
print(EXPECTED_RESULTS_BASE.absolute())

Since you're using a venv and the error is a result of calling pytest with a different command, try using which to see if you're actually calling different things. Both before and after activating your venv:

which pytest
which python

python -m pytest will call the pytest module installed with the version of python you've just called. If python calls a different version than you're getting from pytest inside your venv, then that could be the problem.
You should be able to check which python version pytest is calling by looking at the hashbang at the top of the file
head -1 $(which pytest)

On my system, macOS with anaconda Python installed, I get the following from those commands
$ which pytest
/Users/Shannon/anaconda/bin/pytest

$ which python
/Users/Shannon/anaconda/bin/python

$ head -1 $(which pytest)
#!/Users/Shannon/anaconda/bin/python

This tells me that pytest is calling the same version of python I get when I call python. As such, pytest and python -m pytest should result in the same thing for me, inside my default environment.
Are you sure VSCode is loading your venv correctly before running the test?
Comment: Solved it on my own, it was just a missing `__init__.py` in the test-folder, which `pytest` seems to require in some set-ups, as opposed to `unittest` where the `__init__.py` just needs to be in the folder where the modules being tested are located: https://stackoverflow.com/a/67165280/12298276
Comment: How do I make sure that VS Code is loading my venv correctly (using virtualenvwrapper on Windows10 via powershell)? I have the same problem as the OP, but the other way around: when using just `pytest`, it throws `modulenotfounderror`, but when using `python -m pytest` it works like a charm. I've checked and installed pytest both with my global environment and my venv.
Comment: If you could take a look it my question, I've filed one as well, because it seems to be more involved: https://stackoverflow.com/questions/67164367/pytest-fails-due-to-modulenotfounderror-but-works-when-using-python-m-pytest
Answer: Assuming you have a virtual environment selected for your Python interpreter in VS Code:

Open the terminal in VS Code
Let the virtual environment activate
Run python -m pip install pytest

That will install pytest into the virtual environment which is why python -m fails (pytest globally on your PATH is installed in some global Python install which a virtual environment won't have access to).


What is sudo? I can't access to it

Question: I am very very new to all of this.
I get it that sudo is some kind of authorisation. When it asks for the password, I can't type anything.
EDIT:
OMG GUYS THANKS. I just realized that I might have a solution for my wireless network now!! Well since I had no idea what Sudo was and when I tried to boot up 12.10 I couldn't since I thought I couldn't access to it! YES, I'm gonna try this out!
Comment: sudo has a long history - it comes from mainframes where they had to use the `pseudo` command for a program to invoke a system command as if a user had typed in the command - it was a pseudo user. The original bearded Unix boys picked up the sound of it (sue-doe) and realized it also could be SuperUser DO - so it became sudo, pronounced same as pseudo. It was a very useful joke. But that was many moons ago. Now the n00bs (that is, everybody born too late to remember watching the first moon landing live along with the rest of the world) use it.  It is fun to remember the history of these things
Answer: You are actually typing, it is just not shown there because someone should not watch it over your shoulder!
Answer: When you type sudo into the terminal and it asks for your password, your password is not visible when you type it. So when you do happen to use the sudo command just type in your password even though you may not see it then hit enter.

What is sudo? I can't access to it


sql - sum,average values in a table

Question: I have a table:
DATE    TIME    ITEM    PRICE
01-01-2011  0   Gold    22000
01-01-2011  1   Gold    23000
01-01-2011  2   Gold    22000
01-01-2011  3   Gold    21000
01-01-2011  4   Gold    24000
01-01-2011  5   Gold    19000
01-01-2011  6   Gold    18000
01-01-2011  7   Gold    17000
01-01-2011  8   Gold    16000
01-01-2011  9   Gold    30000
02-01-2011  0   Gold    22000
02-01-2011  1   Gold    15000
02-01-2011  2   Gold    28000
02-01-2011  3   Gold    31000
02-01-2011  4   Gold    19000
02-01-2011  5   Gold    22000
02-01-2011  6   Gold    23000
02-01-2011  7   Gold    25000
02-01-2011  8   Gold    26000
02-01-2011  9   Gold    27000

I want to have an output as:
DATE        ITEM    TOT      AVG    MAX     TIME_MAX MIN    TIME_MIN
01-01-2011  GOLD    21200   2120    30000   9        16000  8
02-01-2011  GOLD    23800   2380    31000   3        15000  1

where:

DATE - date from the table
ITEM - item from the table
TOT - sum of price in a day
AVG - average of price in a day
MAX - maximum price in a day
TIME_MAX - time at which the price was maximum in a day
MIN - minimum price in a day
TIME_MIN - time at which price was minimum in a day
Comment: Please tag the RDBMS you are using and the version , eg. SQL Server 2016, Oracle 11g
Comment: While it is interesting what table you have and what output you want (thanks for telling the story), is there any question you have? Any SQL you tried and have issues with?
Comment: what if more rows have maximum/minimum in that day?
Comment: Also please state what you have tried.
Comment: Stackoverflow is NOT a free coding service. if you have troubles with a query, we will help you. but we won't do your work!
Comment: Check out `GROUP BY`, and the aggregate functions `SUM()`, `AVG()`, `MAX()` and `MIN()`.
Comment: I have tried the following code:                                                              select date,item,time,max(price),min(price),sum(price) from table t group by date,item, time
This query is giving me the output per hour wise.
Comment: I am using Oracle 11g
Answer: Try This query.
SELECT
DATE,ITEM,SUM(PRICE) AS TOT,
AVG(PRICE) AS AVG,
MAX(PRICE) AS MAX,
MAX(TIME) AS TIME_MAX,
MIN(PRICE) AS MIN,
MIN(TIME) AS TIME_MIN
FROM T
GROUP BY DATES,ITEM;

Since you do not need Time in your result, its not needed to include it in the SELECT statement of GROUP BY statement.

sql - sum,average values in a table


add filter to replace part of a string

Question: What would be the correct way to add a filter to replace part of a string in an echo?
The function is this:
function woocommerce_template_loop_product_title() {
    echo '
' . get_the_title() . '
';
}

I tried to implement this in my functions.php:
add_filter( 'woocommerce_template_loop_product_title', 'product_title_mod');
function product_title_mod($str) {
    return str_replace ('h3','h2',$str);
}

But that does not affect the h3 values, what would be the best way to filter those be?
Comment: You pass `$str` by value and the result of function `product_title_mod` is not utilized.
Answer: function should return value so you can use it or echo value directly:
add_filter( 'woocommerce_template_loop_product_title', 'product_title_mod');

// option 1
function product_title_mod($str) {
    return str_replace("h3","h2",$str);
}

// option 2
function product_title_mod($str) {
    echo str_replace("h3","h2",$str);
}

Not totally sure how wordpress filters work, but I suppose you can't achieve what you want, because woocommerce_template_loop_product_title function echoes result directly.
Comment: I 'm not familiar with wordpress, but I think you can't do what you want, see my update.

add filter to replace part of a string


How do I get this event-based console app to not terminate immediately?

Question: Source
class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Created+= fw_Created;
    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}

Question
Should be pretty self explanatory. I'm trying to create a file watcher so I can sort my videos for me automatically...how do I get the program to not terminate, ever?
I want to keep it console-based for now so I can debug it, but eventually I want to remove the console and just have it run in the background (I guess as a service).
Comment: What event do you expect to cause your application to stop?
Comment: @M.Babcock: I don't expect to stop it. I'll forcibly close it with Ctrl+Alt+Del on windows. Or while I'm developing, closing the console window via the X can terminate it. Ultimately it would be terminated by stopping the windows service.
Answer: Perhaps something like this:
class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Changed += fw_Changed;
        fw.EnableRaisingEvents = true;

        new System.Threading.AutoResetEvent(false).WaitOne();
    }

    static void fw_Changed(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}

Update
In the spirit of helping anyone else that may be looking for a similar solution, as @Mark stated in the comments, there is also a way to use the WaitForChanged method of the FileSystemWatcher class to solve this question:
class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@".");
        while (true)
        {
            Console.WriteLine("added file {0}",
                fw.WaitForChanged(WatcherChangeTypes.All).Name);
        }
    }
}

Doing so allows the application to wait indefinitely (or until the while is broken) for a file to be changed.
Comment: After you set your event handler you need to set EnableRaisingEvents to true. I've updated the answer to show how. Check out the example from the FileSystemWatcher documentation for more information: http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx
Comment: Ooo...it also has a `WaitForChanged` function..then we don't have to use a separate threading object.
Comment: I like the AutoResetEvent approach since I have multiple FSW objects that are firing events, so the WaitForChanged approach won't work for me.
Comment: That's keeping the window open.....but I think it's preventing the file watcher from receiving events, unless I've programmed it wrong...."added file" is never being hit when I create files in said directory.
Comment: Err...I should have been using the "Created" event instead, but it's the same problem.
Comment: @Mark - The answer has been updated to include a very primitive example of using the `WaitForChange` method.
Comment: @MBabcock: That doesn't return a bool.....you can't put it in a while. I amended my answer with one that works awhile ago :D
Comment: @Mark - My mistake. Fixed now.
Answer: class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.EnableRaisingEvents = true;
        fw.Created += fw_Created;

        Console.ReadLine();

    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }

}

Just had to EnableRaisingEvents apparently.

Found another solution that is perhaps even nicer:
class Program
{
    static void Main(string[] args)
    {
        var fw = new FileSystemWatcher(@"M:\Videos\Unsorted");
        fw.Created += fw_Created;
        while(true) fw.WaitForChanged(WatcherChangeTypes.All);
    }

    static void fw_Created(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine("added file {0}", e.Name);
    }
}

Comment: Works nice with other events, too. Tried it with Timer, doesn't block execution.
Answer: You can wait forever using this:
System.Threading.Thread.Sleep(-1);

Comment: The description reads "acquires an exclusive lock on the specified object"... not sure how that helps, but I tried it anyway. Doesn't do anything; still closes immediately. Tried it with `obj` and `fw`.
Comment: @Mark: Quite right! I've updated my answer with a better solution anyway.
Comment: Nope...that's going to wait for keyboard input and not allow any events to get through.
Comment: @Mark: No, `FileSystemWatcher` is asynchronous. You need to set the `EnableRaisingEvents` property to `true` - just noticed that now :) Also, a more elegant solution is now in my answer.
Comment: You're right. I knew it was async but I thought that meant it wouldn't halt execution *but* I thought `ReadLine` would essentially hog all the threads and not let anything through...but I guess it would just hog the one thread, and the async event would fire on a separate thread...
Answer: I have had the exact same problem as you. What i did is if the program is launched with the command line --console it will prompt you to hit enter to close, if no parameters it will expect to be launched as a service.
class MyExampleApp : ServiceBase
{

    public static void Main(string[] args)
    {
        if (args.Length == 1 && args[0].Equals("--console"))
        {
            new MyExampleApp().ConsoleRun();
        }
        else
        {
            ServiceBase.Run(new MyExampleApp());
        }
    }
    private void ConsoleRun()
    {
        Console.WriteLine(string.Format("{0}::starting...", GetType().FullName));

        OnStart(null);

        Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
    }
    //snip
}

Comment: ServiceBase is [part of .NET](http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx). When I write a service I want my debugging to be as close to a running service as possible. Events will file while waiting for a ReadLine(), however I think you problem is like [M.Babcock mentioned](http://stackoverflow.com/a/8676112/80274) ,you need to set EnableRaisingEvents to true. [From the MSDN](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.enableraisingevents.aspx) "**The component will not raise events unless you set EnableRaisingEvents to true**"
Comment: Err...perhaps I'm missing something, but merely adding `Console.ReadLine();` at the end of Main() doesn't seem to work either. I think it's waiting for input and not accepting events, no? Is `ServiceBase` one of your classes, or something I should be inheriting from too?
Comment: That seems like an awful lot of code to fulfill the minimal task that Mark is asking for.
Comment: @ScottChamberlain: You are correct! Didn't think to look for such an option..why would you create a file system watcher if you didn't want to listen for events?!
Comment: @Mark You may want to delay the watching until you are ready to receive the events or something else happens first, it is easier to start disabled and enable when you are set up, than start enabled and ignore messages until you had a chance to stop it.
Comment: @ScottChamberlain: I suppose.. I'm trying to think of a scenario where you couldn't immediately set it to false...but... I dunno! Perhaps a bool in the constructor to start enabled or disabled would have been optimal then.
Answer: Console apps are never a good way to test events due to this scenario. Whatever method you use, it has to halt the current thread, either sleep or lock in some while(true) loop, which pevents your events from firing or makes it almost impossible to hit breakpoints inside events.
Use a windows app if you can.
Comment: Seems like the only legit solution so far. I can do that, but console app seemed more convenient because I'm only using it as a debug window.
Comment: But often this is done to make an easier way to work on windows services.


Layout method using concrete retaining wall block for angled wall

Question: I am planning to use the rectangular 12x4 retaining wall blocks as below

http://www.lowes.com/pd_357656-215-30732___?productId=3722166
This is because we like the design of this better than using trapezoid shape (not available locally for Tranquil color and special order is too expensive).
Now this block is good for 90 degree edges only.  For example:

How do I lay them out in below shape and angle? Without cutting the 4-in concrete?
Or do people leave the gaps in the front wider as it's getting closer to the corner like that?
I am open to any creative idea for that corner. I was thinking about creating a small square-looking seating column using 3x4 of the blocks to "mask" the adjustment in angle and gaps.
Thanks.
Answer: When it comes to cutting block, you don't need to cut it (but cutting a score can be helpful). Using a rock hammer (and perhaps a chisel) to break the rock is the way it's done.
The method for shaping rocks is kind of simple, but a video is a better way to describe it... so here's a few youtube videos about shaping rocks.
Flagstone (good info)
Rock hammer (more like what you're working with)
With a chisel
Otherwise (if you are adamantly opposed to breaking or shaping stone), you could build a form and pour a concrete joint (like in the shape of a Y). If that's the plan, I would probably start with this, then lay the rock.
Also, a suggestion to make it look a little better might be to make an exposed aggregate joint. There are several ways to accomplish that, but it's not really relevant here.
Comment: I am also thinking about building stair step in that Y corner. So basically from ground level up to the 2-ft high ground, then 3-ft high ground. I still don't know how to lay that one out (until I see some pictures).


How to print specific div content using jquery with out using window.print() method

Question: I want to print the entire div content using jquery.
Currently I am using window.print() method. But it displays only some content in print page and some content missing.
I want to print entire  data in my print page.
Comment: can you show your code.
Comment: Your css might have "@media" styles for print mode preventing some of your content to display correctly. See more info about "@media" here: http://www.w3schools.com/css/css3_mediaqueries.asp
Comment: