text:
Q: New_post in blogdown doesn't make Rmarkdown files I'm trying to practice the blogdown with one of hugo themes but I cannot make new Rmarkdown posts using: Addins > New Post > <>.
When I click done, there is no file in the editor or in the filesystem, and the Console reports:
blogdown:::new_post_addin()

Listening on http://127.0.0.1:4288
C:\Users\82105\Desktop\blogdown2\content\en\post\2020-07-16-afsf.en.md created
Warning in file(con, "r") :
  cannot open file 'content/post/2020-07-16-afsf.en.md': No such file or directory
Warning: Error in file: cannot open the connection
  91: file
  90: readLines
  87: hugo_toYAML
  86: new_content
  85: blogdown::new_post
  84: observeEventHandler
  13: shiny::runApp
  12: shiny::runGadget
  11: eval
  10: eval
   4: eval
   3: eval
   2: sys.source
   1: blogdown:::new_post_addin

My hugo version is 0.73.0.
The link of theme I'm using is hugo-theme-zdoc theme
Thank you.


text:
Q: Converting movieclip into sprite/bitmap I have expanded class, movieclip type. It's built from some other movieclips and in the process it uses them.
So I have a question. To lower the memory, how can I convert the output effect of this movieclip into a sprite? I mean it's appeareance changes partially, since all children change their look oh their own.
How do I do this in the best way? And is it easy to do?

redpajama_set_name: RedPajamaStackExchange


text:
Q: individual activities include API call can I use fragment to reduce the activity In my App for Tablet! welcome activity, login activity, registration activity, password activity, starter activity with viewPager,
Message to send activity, scanning activity,
fill in form details activity, payment activity its about 25 activities with 25 layouts, 30 XML in Drawable for components background
and few images,fonts as of now
My Question is Since these individual activities include API call can I use fragment to reduce the activity, just because now
my app is 3.31 MB it further may increase and by reducing activity increases performance of my app, So which is best Fragment or Activity? Thanks in advance

A: Using fragments certainly helps since they make your code very modular and reusable. If you have multiple parts of the screen that are similar in nature, you can simply use fragments to create them. In terms of the api calls and the business logic, you could consider using MVVM architecture for your app. That way you can have a common ViewModel for fragments that make similar api calls and in doing so you make the business logic somewhat reusable too. Some resources that you might find useful for MVVM:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93viewmodel
https://developer.android.com/topic/libraries/architecture/viewmodel
Previous Stackoverflow post about fragments and app size:
How to reduce android activity and app size?
It does sound like using fragments would be the way to go for your app too as opposed to using 25+ activities.


text:
Q: The correct layout for mathematical derivations I am writing my 2nd TeX document. Therefore I am still at the beginning. I have a chapter inside my Appendix, which is dealing with small derivations. However, I am not quite sure if my layout/form is correct.
Based on one comment of this post I avoid the use of \Leftrightarrow
Here is a short MWE of one derivation.
\documentclass[a4paper,12pt]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage{amsthm}
\usepackage{mathtools}
\usepackage{aligned-overset}

\newcommand{\Lagr}{\mathcal{L}}
\newcommand{\matr}[1]{\mathbf{#1}}
\newcommand{\X}{\matr{X}} %Matrix von X
\newcommand{\y}{\matr{y}} %y als voller Vektor
\newcommand{\yct}{\ubar{\y}^\mathbf{T}} %Zentriert
\newcommand{\betahat}{\hat{\beta}} %betahat

\begin{document}
\begin{flalign*}
\Lagr(\beta_{0},\beta) &=\min\limits_{\beta_{0}, \beta} \left\{ \frac{1}{2} \sum_{i=1}^N\left(y_{i}-\beta_{0} - \sum_{j=1}^p\beta_{j}\tilde{x}_{ij}\right)^2  +\lambda\sum_{j=1}^p\left|\beta_{j}\right| \right\} &\\
&= \min\limits_{\beta_{0}, \beta} \left\{ \frac{1}{2} \sum_{i=1}^N\left(y_{i}-\beta_{0} - \sum_{j=1}^p\beta_{j}(x_{ij}-\bar{x}_{j})\right)^2  +\lambda\sum_{j=1}^p\left|\beta_{j}\right| \right\}  &
\end{flalign*}
\vspace*{-1cm}
\begin{flalign*}
&\frac{\partial \Lagr}{\partial \beta_{0}} \overset{!}{=}0 \\
&-\sum_{i=1}^N\left(y_{i}-\betahat_{0} - \sum_{j=1}^p\betahat_{j}(x_{ij}-\bar{x}_{j})\right) = 0 \\
& -\sum_{i=1}^{N}y_i + N \betahat_{0}+\sum_{i=1}^N\left(\sum_{j=1}^p\betahat_{j}x_{ij}\right) - N\sum_{j=1}^{p}\betahat_{j}\bar{x}_{j} =0 \\
& -\frac{1}{N}\sum_{i=1}^{N}y_i +\betahat_{0}+  \sum_{j=1}^p\left(\betahat_{j}\frac{1}{N}\sum_{i=1}^N x_{ij} \right) - \sum_{j=1}^p\betahat_{j}\bar{x}_{j}=0 \\
& -\bar{y}+\betahat_{0}+\sum_{j=1}^p\betahat_{j}\bar{x}_{j}-\sum_{j=1}^p\betahat_{j}\bar{x}_{j}=0\\
& \betahat_{0} =\bar{y}\\
\intertext{\textnormal{Aus der Annahme, dass $\y$ zentriert ist $\frac{1}{N}\sum_{i=1}^{N}\tilde{y}_{i}=0$, folgt}}
&\betahat_{0}=0  &
  \end{flalign*}
\end{document}

The code can certainly be written more elegantly, but I am primarily interested in the optical layout of the derivation. I would be very grateful for help and tips.

A: I can suggest some improvements.

*

*There's no need to stack two flalign* environments.

*There's no need for \intertext.

*\left( and \right) should be \biggl( and \biggr).

*Also \left\{ and \right\} might benefit from the above; see the first and second line to see the difference; with \left and \right you get oversized braces.

*There's no need for \limits after \min.

*^2 after a big parenthesis should be ^{\!2}.

*&- should be &{-} in order for the minus sign to be "unary" and so left aligned.

\documentclass[a4paper,12pt]{scrartcl}
\usepackage[ngerman]{babel}
\usepackage{amsthm}
\usepackage{mathtools}
\usepackage{aligned-overset}

\newcommand{\Lagr}{\mathcal{L}}
\newcommand{\matr}[1]{\mathbf{#1}}
\newcommand{\X}{\matr{X}} %Matrix von X
\newcommand{\y}{\matr{y}} %y als voller Vektor
\newcommand{\yct}{\ubar{\y}^\mathbf{T}} %Zentriert
\newcommand{\betahat}{\hat{\beta}} %betahat

\begin{document}
\begin{flalign*}
&\begin{aligned}
\Lagr(\beta_{0},\beta) &=\min_{\beta_{0}, \beta} \left\{ \frac{1}{2} \sum_{i=1}^N\biggl(y_{i}-\beta_{0} - \sum_{j=1}^p\beta_{j}\tilde{x}_{ij}\biggr)^{\!2}  +\lambda\sum_{j=1}^p\left|\beta_{j}\right| \right\} &&\\
&=\min_{\beta_{0}, \beta} \biggl\{ \frac{1}{2} \sum_{i=1}^N\biggl(y_{i}-\beta_{0} - \sum_{j=1}^p\beta_{j}(x_{ij}-\bar{x}_{j})\biggr)^{\!2}  +\lambda\sum_{j=1}^p\left|\beta_{j}\right| \biggr\}
\end{aligned} && \\
&\frac{\partial \Lagr}{\partial \beta_{0}} \overset{!}{=}0 \\
&{-}\sum_{i=1}^N\biggl(y_{i}-\betahat_{0} - \sum_{j=1}^p\betahat_{j}(x_{ij}-\bar{x}_{j})\biggr) = 0 \\
&{-}\sum_{i=1}^{N}y_i + N \betahat_{0}+\sum_{i=1}^N\biggl(\sum_{j=1}^p\betahat_{j}x_{ij}\biggr) - N\sum_{j=1}^{p}\betahat_{j}\bar{x}_{j} =0 \\
&{-}\frac{1}{N}\sum_{i=1}^{N}y_i +\betahat_{0}+  \sum_{j=1}^p\biggl(\betahat_{j}\frac{1}{N}\sum_{i=1}^N x_{ij} \biggr) - \sum_{j=1}^p\betahat_{j}\bar{x}_{j}=0 \\
&{-}\bar{y}+\betahat_{0}+\sum_{j=1}^p\betahat_{j}\bar{x}_{j}-\sum_{j=1}^p\betahat_{j}\bar{x}_{j}=0\\
&\betahat_{0} =\bar{y}
\end{flalign*}
Aus der Annahme, dass $\y$ zentriert ist $\frac{1}{N}\sum_{i=1}^{N}\tilde{y}_{i}=0$, folgt
\begin{flalign*}
&\betahat_{0}=0  &&
\end{flalign*}
\end{document}


text:
Q: how to make List using List? I have to make List<List> using List
  List<String> list = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' , '11', '12', '13', '14', '15', '16', '17', '18' , '19', '20', '21', '22', '23', '24', '25'];

list.length will be no more than 25.
have to divide by 5 like
  int divide;

  divide = word.length ~/ 5;

and have to make List<List>
I don't know how to do it.
have to be
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20],[21, 22, 23, 24, 25]]

if list.length is 23 have to be
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20],[21, 22, 23]]

A: You can try this one
List dataList = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' , '11', '12', '13', '14', '15', '16', '17', '18' , '19', '20', '21', '22'];
List chunkList = [];
int chunkSize = 5;
for (var i = 0; i < dataList.length; i += chunkSize) {
    chunkList.add(dataList.sublist(i, i+chunkSize > dataList.length ? dataList.length : i + chunkSize));
  }
print(chunkList);

A: I think this is the best one, you can try like below
List<List<String>> _getListInList(List<String> data) {
    final chunks = <List<String>>[];
    final chunkSize = 5;

    for (var i = 0; i < data.length; i += chunkSize) {
      chunks.add(
        data.sublist(
          i,
          i + chunkSize > data.length ? data.length : i + chunkSize,
        ),
      );
    }

    return chunks;
  }

Just Copy and Paste :D


text:
Q: angularJS: naming conventions on getter and setter methods with cached data I'm having trouble naming my service functions, this is the situation:
I have the data object that stores all data coming from an API. I need a set function that GET's the data from the api and SETs the data object in this service. I need a GET function that returns said data object.
And finally there is the SET function that saves new data coming from the service consumer (e.g. a controller) to my data object and sets off a POST/PUT to the API.
function dataService() {

    var data = {};

    var service = {
        get: function() {
            return data;
        },
        setOrGet: function() {

            // GET schema from API and .then
            data = apiResponse;

        },
        set: function(newData) {
            data = newData;
            // PUT new data to API
        }
    }

}

I don't know how to name the setOrget function because technically it sets the data object but it GETs the data from the API. The Service of course has the regular set and get function as well.
Is there a recommended naming approach?


text:
Q: In delphi, how do you embed Excel in a form and show excel components on the component pallette? Years ago I remember installing excel and office components onto the component palette in delphi 5.  It was either through activeX or COM, or a typelib, there was some way to install the components.   the components I think you could drag and drop onto the form and then a spreadsheet would be embedded into your app (or microsoft word, etc.).
The only information I can find on the internet is about using OLEcontainers... which is a component in the system tab of delphi 5.  However I do not remember it being an OLEcontainer when I used components for embedding excel, I rather remember installing actual excel and office components onto the component palette somehow... the components may have been generated from an ocx file or a typelib, I do not remember.  Where does one find or obtain the files to generate the excel and office components on the component palette?  are they ocx and do they come with my copy of MS Office that I have on my computer?
Are there excel COM or activex components that one can install? Am I remembering correctly, or is the only way to use excel through OLEcontainer component?
Edit: it may have also been an automation server component for excel or office

A: You can do this:
In FormCreate (or OnActivate..)
OleContainer1.CreateLinkToFile( Edit1.Text, false );

This is the result:

A: Figured out how to at least import the excel components into delphi component palette (but these are not for embedding spreadsheet). Many people click "import activex control" but that will not import an excel spreadsheet component since the excel components are a type library import.
You cannot import the excel activex control the way you would think using "import activex control" menu item, rather you can import the type library instead.
Go to the main menu and click Project -- Import Type Library
Scroll down and find Microsoft Excel 14.0
(or whatever version of excel you have...)
then install.
The components appear on the component palette under activex tab.
Those are for automation. For OLE embedding, it seems that Ole container is the way to go.


text:
Q: Sending a PriorityQueue over Socket in Java sends an empty queue I have two programs - Server and a Client. Basically the job of the server is to maintain an ArrayList of objects of some class 'Item'. Items can be added to the ArrayList or existing items can be altered on the Client app's request. Occasionally the Client App has to receive some of the Items that are contained in the list and that is where the problem comes from. The Item Class has a PriorityQueue of other objects (that are serializable) as an instance variable. The problem is that when the server sends some items the client receives everything but the priority queue for each item is empty (all the other instance variables of the Item objects are received correctly).
Now the code:
This is the part of the Item Class that is connected to the problem:
public class Item implements Serializable
{
    ...Some instance variables...
    PriorityQueue<Bid> pq;

    public Item(...)
    {
        pq = new ProrityQueue<Bid>();
    }

    public void addStuff(Stuff bid)
    {
        this.pq.add(bid);
    }

    ...other methods...
}

To send the ArrayList that the client requested I just to this on the server side
ObjectOutputStream oos = new ObjectOutputStream(serverSocket.getOutputStream);
oos.writeObject(someArrayList<Item>);

and on the client side
ObjectInputStream ois = new ObjectInputStream(serverSocket.getInputStream);
ArrayList<Item> tempList = (ArrayList<Item>) ois.readObject();

I find it really strange that the client receives every single object it has to receive and all of its instance variables including the PriorityQueue but the PriorityQueue is empty. Why are the Objects in the PriorityQueue the only thing that is not received by the Client? Is there something extra I should know about sending a List of objects that have some collection of other objects within them over a socket?
EDIT: I am posting part of the code for further details. In fact for the communication between the server and the client I use ClientCommunications Class and ServerCommunication Class that handle everything so that the two apps don't have to deal with the sockets.
To send some of the items that are requested by the client I have
ArrayList<Item> list = handleItemsRequest(rim);
//this uses the server output stream to transfer an object to the client's output stream
comms.sendItems(list);

Code for the sendItems(list) method:
public void sendItems(ArrayList<Item> items)
{
    try
    {
        //oos is the output stream of the server socket
        oos.writeObject(items);
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
}

where handleItemsRequest() is a method that takes some constraints and then return only the items that match them:
public ArrayList<Item> handleItemsRequest(RequestItemsMessage rim)
{
    //it is the new array list that consist of items matching the conditions
    ArrayList<Item> it = new ArrayList<Item>();
    //items is the arrayList maintained by the server
    for (Item item : items)
    {
       if (item.matchesConditions)
       {
           it.add(item);
       }
    }

    //it contains all the right items and the priorityQueue for each item has everything that it has to have
    return it;
}

Then the client app receives the list by calling
//this comms variable is different from the one in the server and is a par of a different class
ArrayList<Item> list = comms.receiveItems();

Code for the receiveItems():
public ArrayList<Item> receiveItems()
{
    try
    {
        ArrayList<Item> list = (ArrayList<Item>) ois.readObject();
        return list;
    }
    catch(ClassNotFoundException | IOException e)
    {
        e.printStackTrace();
    }

    return null;
}

Now the client has all the items that had to be sent but their priority queues are empty.
There is much more code but it is not relevant to this problem and I needn't post it all.
SOLUTION It turns out that before sending the list the OutputStream of the server has to be reset. Otherwise the client would keep getting the old instance again and again. Big thanks to EJP for pointing out the problem!

A: Do you ever close the stream? Try calling oos.close() after oos.writeObject().


text:
Q: Match light-shaded colors to plot themes for RegionPlot I have a problem very similar to the one in the following topic:
Match colors to plot themes. I want to extract the color of a plot for the corresponding legend. However, as I use a RegionPlot I am interested in the color of the region.

However, when I use
Charting`ResolvePlotTheme["Scientific", RegionPlot]

I only get information on the color of the lines between the regions.

Is there a way to extract the color of the regions?


text:
Q: How to show the specific image from PhotoLibrary?
Possible Duplicate:
display image from URL retrieved from ALAsset in iPhone

In my Application I need to get specific image from Photo Library,
with use of didFinishPickingMediaWithInfo i am able to get the Imagename and ImagePath.
I am storing Imagename, ImagePath in Database.
But, how to show that specific image with use of the Imagename or ImagePath in Imageview from Photo Library?

A: Please make use of ALAssetLibrary. To do this, add the AssetsLibrary.framework to your project and write the below code.
Your file name should look like assets-library://asset/asset.JPG?id=1000000194&ext=JPG
NSString *fileName = @"assets-library://asset/asset.JPG?id=1000000194&ext=JPG";

typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);

ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
    ALAssetRepresentation *rep = [myasset defaultRepresentation];
    CGImageRef iref = [rep fullResolutionImage];
    UIImage *images = nil;

    if (iref)
    {
        images = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];

        //doing UI operation on the main thread
         dispatch_async(dispatch_get_main_queue(), ^{

         yourImageView.image = images;

     });

    }
};

ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
{
    NSLog(@"can't get image");
};

NSURL *asseturl = [NSURL URLWithString:fileName];

ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
               resultBlock:resultblock
              failureBlock:failureblock];

Note:
After the upgrade to iOS 5 and a code refactoring to make use of ARC, you will get an error as

invalid attempt to access ALAssetPrivate past the lifetime of its
  owning ALAssetsLibraryrefactoring to make use of ARC

To resolve this, add a static method to retrieve a shared instance of ALAssetLibrary class.
+ (ALAssetsLibrary *)defaultAssetsLibrary {
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library;
}

Then, access it using [MyClass defaultAssetsLibrary];
[[MyClass defaultAssetsLibrary] assetForURL:asseturl
                   resultBlock:resultblock
                  failureBlock:failureblock];

A: If you have image path with you than you can use the following code. Lets take imagePath as NSString Variable that contains image path including image name.
   NSData *thedata=[[NSData alloc]initWithContentsOfFile:imagePath];
     UIImageView *img=[[UIImageView alloc]initWithImage:[UIImage imageWithData:thedata]];

Hope it helps.


text:
Q: Need different color of span in anchor for a:link, same for a:hover I have a link in which a span is embedded containing a "less than" arrow < followed by a nbsp and some text:
< back to overview

I want the entire anchor to be gray text except for the < which should be white. The entire anchor should be orange text on hover but I can't get that to work... I wonder if it's possible just by using CSS, but I doubt it.
Styling (currently closest attempt):
.smallbutton {
    background-color: #AAAAAA;
    border-radius: 8px 8px 8px 8px;
    color: white;
    display: inline-block;
    height: 20px;
    text-align: center;
    width: 20px;
}
.smallbutton:hover {
    background-color: #DDDDDD;
    color: inherit;
}
a:link, a:visited {
    color: gray;
    text-decoration: none;
}
a:active {
    color: #FC930A !important;
    text-decoration: none;
}
a:hover, a:focus {
    color: #F7C41F !important;
    text-decoration: none;
}

The problem is, I expected the !important to override white but it doesn't...
Here is the jsfiddle: http://jsfiddle.net/2GX2Y/
The colors that are on the < should be there when just hovering over the containing  tag, not just the < itself.

A: I think if you change
.smallbutton:hover

to
a:hover .smallbutton

then you'll have what you want. But I may have misunderstood the question.
Just let me know!
Here is the example http://jsfiddle.net/tRRRV/1/


text:
Q: Orderby desc multiple properties in Neo4jClient Suppose I have 4 photos and I want to return a list sorted first on Rating desc, second on RatingsCount desc. Below cypher query gives me the correct result:
MATCH (n:`Photo`) WHERE n.RatingsCount > 0 RETURN n.Rating, n.RatingsCount ORDER BY n.Rating DESC, n.RatingsCount DESC LIMIT 20

Id 1-Rating 9-Ratingscount 1
Id 3-Rating 7-Ratingscount 2
Id 2-Rating 7-Ratingscount 1
Id 4-Rating 2-Ratingscount 1
Unfortunately I cannot translate it to Neo4jClient. Below query gives me a photolist ordered by Rating ascending and Ratingscount descending:
var query = await graphClient.Cypher
            .Match("(photo:Photo)")
            .Where((PhotoEntity photo) => photo.RatingsCount > 0);
            .ReturnDistinct((photo) => new
            {
                Photo = photo.As<PhotoEntity>()
            })
            .OrderByDescending("photo.Rating", "photo.RatingsCount")
            .Limit(20)
            .ResultsAsync;

Id 4-Rating 2-Ratingscount 1
Id 3-Rating 7-Ratingscount 2
Id 2-Rating 7-Ratingscount 1
Id 1-Rating 9-Ratingscount 1
If I change order of Rating and RatingsCount I get the photos in an even stranger order :) Any clue of what I am doing wrong here?
var query = await graphClient.Cypher
                .Match("(photo:Photo)")
                .Where((PhotoEntity photo) => photo.RatingsCount > 0);
                .ReturnDistinct((photo) => new
                {
                    Photo = photo.As<PhotoEntity>()
                })
                .OrderByDescending("photo.RatingsCount", "photo.Rating")
                .Limit(20)
                .ResultsAsync;

Id 1-Rating 9-Ratingscount 1
Id 2-Rating 7-Ratingscount 1
Id 4-Rating 2-Ratingscount 1
Id 3-Rating 7-Ratingscount 2

A: I took a look at Neo4jClient's source and OrderByDescending() simply string.join()s its arguments with commas and adds 'DESC' at the end. In other words: it sorts ASC on every property except for the last. I agree that this is counter intuitive so I tend to avoid it.
You can use OrderBy() instead:
OrderBy("photo.RatingsCount DESC, photo.Rating DESC")


text:
Q: Ordering events in jquery I have a construct like this.......

        Friends

I removed the inner contents as it is too lengthy... and i have a jquery like this...
$(document).ready(function() {
    $('.drop_head').each(function(i, e) {
        $('.dropper', e).click(function() {
            $('.drop_list', e).slideToggle(1500);
        });
    });

    $('.dropper').click(function(e) {
        $(e.target).parent().removeClass('leaf_class');
        if ($(e.target).parent().height() < 300) $(e.target).parent().addClass('leaf_class');
    });
});

Now what happens is, each time the dropper is clicked, a leaf class is added to the right_top_block and then a slideDown(as part of slideToggle) on the correspoding drop_list is done( I have many such).... Now if it is clicked again the leaf class is removed from the right_top_block and then a slideUP(as part of slideToggle) on the corresponding drop_list is performed. But what i really want is, when a slideUp is performed, i want the slideToggle to complete and then i want the leaf_class to be removed. How do i change the order of the event execution? I guess due to the delay 1500 i am specifying in the toggle is the cause for this. While don't want to loose the slow transition that it gives, i want that to be completed and then the leaf class to be removed. How do i do this?

A: First, two remarks about the code in your question:

*

*The code that runs on click is split into two event handlers: one responsible for the slide animation and the other for the class change. That's quite confusing and actually makes the problem more complex. It would be easier if these two handlers were merged into one, or if one handler was performing the whole slideDown() operation sequence and the other the whole slideUp() sequence.

*You're using e.target with an element that doesn't seem to contain any descendant from where a click event would bubble up. That's perfectly valid in itself, but using this instead would be shorter and make your intent clearer.
Now, let's look at your requirements. It looks like you want leaf_class to be added before the slideDown() animation starts, but only removed after the slideUp() animation completes.
You can achieve that in a simpler way with a pair of handlers bound to the toggle event, and explicit calls to slideDown() and slideUp() instead of slideToggle().
$('.dropper').toggle(function() {
    var $dropHead = $(this).parent();
    $dropHead.addClass("leaf_class");
    $(".drop_list", $dropHead).slideDown(1500);
}, function() {
    var $dropHead = $(this).parent();
    $(".drop_list", $dropHead).slideUp(1500, function() {
        $dropHead.removeClass("leaf_class");
    });
});

A: If I've understood what you're asking, then you're looking for a callback function to your slideToggle function:
$('.drop_list', e).slideToggle(1500, function() {
    //Do stuff after slide is complete
});

The callback function is executed upon completion of the slide animation. See the jQuery docs for more information.


text:
Q: I need rainfall_parameters to be 7 statements, how can I alter the specific function from the 8 it currently has and still have the program work? """A program to read a CSV file of rainfalls and print the totals
   for each month.
"""

from os.path import isfile as is_valid_file

def filename():
    """get's the filename"""
    infile = input('Input csv file name? ')
    while not is_valid_file(infile):
        print('File does not exist.')
        infile = input('Input csv file name? ')
    return infile

def read_file(file):
    """reads the file"""
    datafile = open(file)
    data = datafile.read().splitlines()
    datafile.close()
    return data

def rainfall_parameters(data):
    """organises data into month and num_days and returns a list of
    (month, rainfall) tuples"""
    results = []
    for line in data:
        columns = line.split(',')
        month = int(columns[0])
        num_days = int(columns[1])
        total = total_rainfall(columns, num_days)
        results.append((month, total))
    return results

def total_rainfall(columns, num_days):
    """gets the total rainfall"""
    total = 0
    for col in columns[2:2 + num_days]:
        total += float(col)
    return total

def print_results(results):
    """prints the monthly total rainfalls"""
    print('Monthly total rainfalls')
    for (month, total_rain) in results:
        print('Month {:2}: {:.1f}'.format(month, total_rain))

def main():
    """Prompt the user to provide a csv file of rainfall data, process the
       given file's data, and print the monthly rainfall totals.
       The file is assumed to have the month number in column 1, the number
       of days in the month in column 2, and the floating point rainfalls
       (in mm) for that month in the remaining columns of the row.
    """
    global_file = filename()
    global_cols = read_file(global_file)
    global_results = rainfall_parameters(global_cols)
    print_results(global_results)

main()

A: Seems like an odd requirement, but you can remove a couple local variables:
def rainfall_parameters(data):
    """organises data into month and num_days and returns a list of
    (month, rainfall) tuples"""
    results = []
    for line in data:
        columns = line.split(',')
        #month = int(columns[0])  # no longer needed
        #num_days = int(columns[1])  # no longer needed
        total = total_rainfall(columns, int(columns[1]))  # move num_days
        results.append((int(columns[0]), total))  # move month
    return results


text:
Q: What is the significance of the unit step function? In my textbook in the Riemann integration chapter there is a definition:
The unit step function $I$ is defined by $I(x)=0$ if $x\le 0$ and $I(x)=1$ if $x>0$.
I'm not sure why this was introduced;what is the point of this?
Is there something special having to do with Riemann integrability?

A: The reason (or at least one of the reasons) the unit step function (and the Dirac delta for that matter) is extremely important is that it occurs all the time in the physical sciences and engineering.
Basically, it's the function we use when something "switches on", but the timeframe over which it does so is not resolvable -- it happens too quick to measure.  So we just say it happens "instantaneously" and we use the non-continuous unit step function.  -- Because this is a very common phenomenon, this function is very good at modelling real life.
It's probably introduced in the section on integrability -- as opposed to in differential equations, when it's usually introduced -- to show you that it is possible to have Riemann integrable functions with no antiderivative.


text:
Q: Image load event with automatic image reloading in case of error How to build <img> load event with automatic image reloading in case of error?
Image is created by way:
 var Img = $(document.createElement('img'));
 Img.on('load',function(){
  // Some code, this handler must be saved
 });
 Img.attr('src',path);
 Img.appendTo(...

Where it used: http://vseslava.ru, big circle on index.

A: you can use from this code:
$('#image1')
    .load(function(){
        $('#result1').text('Image is loaded!');
    })
    .error(function(){
        $('#result1').text('Image is not loaded!');
            // in this case you must reload image with jQuery
    });

this is simple,because you has image url and you can reload that and replace that in image.
Update
$("img").load(function(){
        $('#result1').text('Image is loaded!\n');
    })
    .error(function(){
        $('#result1').text('Image is not loaded!\n');
        // in this case you must reload image with jQuery
        var imgSrc = $(this).attr('src');
        $(this).attr('src',imgSrc);
});

Try Demo


text:
Q: From the isomorphic image to the commutative semigroup of natural numbers under addition I read here that $(N', +')$  is the Inverse Completion of Natural Numbers.
I want to get the inverse scheme: starting from the isomorphic image of an element $[[(a, b)]]_⊠$ of $\dfrac {N \times N} \boxtimes$ to get $(N,+)$: the commutative semigroup of natural numbers under addition.
I try to understand which role have the definition of heap in this "construction" from the set of integers to the set of natural numbers

the isomorphisms between two algebras sharing a common structure form a heap

From what I understand the isomorphic image gives me a copy of the natural numbers but in another set, not the natural numbers outside Z. Is there a construction to "eliminate" the $Z-$isomorphic version (=equipped with a heap?) of natural numbers to get the $N-$natural numbers (without heap?)?
Sorry if I am confused, but I am trying to understand the usefulness of a set of natural numbers as an isomorphic image with respect to the set of natural numbers which is not as an isomorphic image of Z, but only as an independent set, without a shared heap structure with Z.


text:
Q: Why are my videos playing speeded up with no audio, but work fine if I log in as a guest? Since the start of this week I have been experiencing a glitch in the multimedia on my Samsung R518 laptop. I have 2 problems:

*

*Videos in every player are speeded up around 2 or 4 times (including youtube.com (both HTML5 and flash variants), any other video on the web and videos on my laptop played by Totem Media Player), exception is VLC player, but 2nd problem does concern even that.

*There is no sound - simple as that (with or without headphones plugged in).

These all problems are now, and has not seen before, I upgraded to Ubuntu 10.10 after it was possible, and from start I didn't have anything from this - it just started in this week. I haven't even putted new software in. I have more or less solved the question (kind of) - I just logged in as a guest - and it all works, but when I make a new user - it does not.
Please help me.
Some stats below:
sudo lshw -c sound
  *-multimedia
       description: Audio device
       product: RV710/730
       vendor: ATI Technologies Inc
       physical id: 0.1
       bus info: pci@0000:01:00.1
       version: 00
       width: 32 bits
       clock: 33MHz
       capabilities: pm pciexpress msi bus_master cap_list
       configuration: driver=HDA Intel latency=0
       resources: irq:48 memory:cfeec000-cfeeffff
  *-multimedia
       description: Audio device
       product: 82801I (ICH9 Family) HD Audio Controller
       vendor: Intel Corporation
       physical id: 1b
       bus info: pci@0000:00:1b.0
       version: 03
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list
       configuration: driver=HDA Intel latency=0
       resources: irq:47 memory:fc200000-fc203fff

sudo lshw -c video
 *-display
       description: VGA compatible controller
       product: M92 LP [Mobility Radeon HD 4300 Series]
       vendor: ATI Technologies Inc
       physical id: 0
       bus info: pci@0000:01:00.0
       version: 00
       width: 32 bits
       clock: 33MHz
       capabilities: pm pciexpress msi vga_controller bus_master cap_list rom
       configuration: driver=radeon latency=0
       resources: irq:46 memory:d0000000-dfffffff ioport:2000(size=256) memory:cfef0000-cfefffff memory:cfe00000-cfe1ffff

A: If you can play the videos with another User Account, it must be a personal setting. If it is a setting of vlc for example, you may reset the settings by deleting the
~/.vlc/
completely and start it again. Does this work? If not, i have no idea which system settings may cause such a problem.


text:
Q: how to get list of selected nodes in angular ivh tree view? I am new this ivh tree, https://github.com/iVantage/angular-ivh-treeview
I have been successfully able to configure this library, however I am not able to get the list of selected nodes, is there a way to get list of selected nodes programmatically?

A: The easiest way is to use ivhTreeviewBfs to collect selected nodes.
var selectedNodes = []
ivhTreeviewBfs(myTree, function(node) {
  if(node.selected) {
    selectedNodes.push(node)
  }
})

Note that you can use ivhTreeviewOptions to get the appropriate "selected" attribute if you want to be fully generic. Also, folks will often want to only collect the top-most selected node for a given tree branch. In this case you can return false in the callback passed to ivhTreeviewBfs and that node's children will not be visited.
You can read more about the bfs service here.


text:
Q: Cesium handling Multiple polygons with callback i draw 2 polygons using callback method
Consider i have 2 polygons ABC and DEF a. When i dragin corners of ABC polygon it works perfectly. when i drag second polygon i-e i draged DEF then ABC disappers and DEF is there.
if i have 3 polyons when i drag corners of 3rd polygon first and second polygons both disappers.
here is sandcastle code click me
can someone guide me what's am i doing wronge here is my code ....
const viewer = new Cesium.Viewer("cesiumContainer");
var scene = viewer.scene;

var polygonCollection = [];
var Poly_pointsCollections = [];

var Poly_coordiantesArray = [
    [72.35433701166211, 52.57522385967319, 96.18442795152974, 44.89719893727921, 72.39011732046649,
        39.86453159141635
    ],
    [67.29773654341213, 32.88259716109294, 69.14234015976554, 32.98282610463128, 69.19404079866142,
        31.354623867578226, 66.85127436871454, 31.712787322338162, 66.55451189733644, 32.6854597580088
    ]
];
var Poly_nameArray = ["aaaaa", "bbbbb"];

var loadedPolyCollection = [];
for (var i = 0; i < 2; i++) {
    loadPoly(Poly_coordiantesArray[i], Poly_nameArray[i]);
}

var selectionPolygonPoints = [];

var loadedPoly;

function loadPoly(coordinate, myArray) {

    loadedPoly = viewer.entities.add({
        id: "poly_" + myArray,
        name: myArray,
        polygon: {

            hierarchy: new Cesium.CallbackProperty(function() {
                    return {
                        positions: new Cesium.Cartesian3.fromDegreesArray(coordinate)
                    }
                },
                false),

            material: Cesium.Color.fromBytes(221, 240, 235, 160),
        }

    });
    console.log(loadedPoly);
    console.log(loadedPolyCollection);
    loadedPolyCollection.push(loadedPoly);

    console.log("loadedPoly ", loadedPoly);

    for (var i = 0; i < coordinate.length; i = i + 2) {
        draw_Zone_Corner_points(coordinate[i], coordinate[i + 1], myArray);
    }

    viewer.flyTo(loadedPoly);

}

function draw_Zone_Corner_points(lon, lat, name) {

    var pointGeometry = viewer.entities.add({
        name: "Polypoint_" + name,
        description: [lon, lat],
        position: Cesium.Cartesian3.fromDegrees(lon, lat),
        point: {
            color: Cesium.Color.SKYBLUE,
            pixelSize: 10,
            outlineColor: Cesium.Color.YELLOW,
            outlineWidth: 3,
            disableDepthTestDistance: Number.POSITIVE_INFINITY, // we can see points arounds earth
            //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        },
    });
    Poly_pointsCollections.push(pointGeometry);
}
var selectedPolygonCoordinates = [];

function newArrayForZone(pickedEntity) {

    selectedPolygonCoordinates = [];
    var selected_Entity_Name = pickedEntity.id._name;
    for (var i = 0; i < Poly_pointsCollections.length; i++) {
        var current_Entity_Name = Poly_pointsCollections[i]._name;

        if (current_Entity_Name == selected_Entity_Name) {
            var [y, x] = Poly_pointsCollections[i]._description._value;
            selectedPolygonCoordinates.push(y, x);
        }
    }

}

function UpdatepolygonWithPoints(pickedEntity) {

    var Newpoints = pickedEntity.id.position._value;
    var carto = Cesium.Ellipsoid.WGS84.cartesianToCartographic(Newpoints);
    var lon = Cesium.Math.toDegrees(carto.longitude);
    var lat = Cesium.Math.toDegrees(carto.latitude);

    var [y, x] = pickedEntity.id._description._value;

    for (var i = 0; i < Poly_pointsCollections.length; i++) {
        if (selectedPolygonCoordinates[i] === y) {
            selectedPolygonCoordinates[i] = lon;
        }
        if (selectedPolygonCoordinates[i] === x) {
            selectedPolygonCoordinates[i] = lat;
        }
    }
    pickedEntity.id._description._value = [lon, lat];

    var entityName = pickedEntity.id._name;
    entityName = entityName.split("_");

    for (i = 0; i < loadedPolyCollection.length; i++) {

        if (entityName[1] == loadedPolyCollection[i]._name) {

            var poly_entity = loadedPolyCollection[i];
            console.log("this.loadedPolyCollection[i] ", loadedPolyCollection[i]);
            poly_entity._polygon._hierarchy = new Cesium.CallbackProperty(function() {
                return new Cesium.PolygonHierarchy(new Cesium.Cartesian3.fromDegreesArray(
                    selectedPolygonCoordinates));
            }, false);

        }

    }

}

var ZoneMoment = true;
// Points_DragAndDrop
document.getElementById("cesiumContainer").addEventListener("click", function() {

    if (ZoneMoment) {

        var rightEntityPicked = false;
        var dragging = false;
        var pickedEntity;
        var mouseDroped = false;
        var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        handler.setInputAction(
            function(click) {
                if (ZoneMoment) {
                    console.log('LEFT down ');
                    var pickedObject = scene.pick(click.position);
                    if (Cesium.defined(pickedObject) && pickedObject.id) {
                        var entityName = pickedObject.id._name;
                        entityName = entityName.split("_");
                        if (entityName[0] === 'Polypoint') {
                            rightEntityPicked = true;
                        }
                        if (rightEntityPicked) {
                            dragging = true;
                            scene.screenSpaceCameraController.enableRotate = false;
                            pickedEntity = pickedObject;
                        }
                    }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_DOWN
        );
        handler.setInputAction(
            function(movement) {
                if (ZoneMoment && dragging) {
                    var cartesian = pickedEntity.id.position.getValue(Cesium.JulianDate
                        .fromDate(
                            new Date()));
                    var cartographic = scene.globe.ellipsoid.cartesianToCartographic(cartesian);
                    var surfaceNormal = scene.globe.ellipsoid.geodeticSurfaceNormal(cartesian);
                    var planeNormal = Cesium.Cartesian3.subtract(scene.camera.position,
                        cartesian,
                        new Cesium
                        .Cartesian3());
                    planeNormal = Cesium.Cartesian3.normalize(planeNormal, planeNormal);
                    var ray = viewer.scene.camera.getPickRay(movement.endPosition);
                    var plane = Cesium.Plane.fromPointNormal(cartesian, planeNormal);
                    var newCartesian = Cesium.IntersectionTests.rayPlane(ray, plane);
                    var newCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        newCartesian);
                    cartographic.longitude = newCartographic.longitude;
                    cartographic.latitude = newCartographic.latitude;
                    pickedEntity.id.position.setValue(scene.globe.ellipsoid
                        .cartographicToCartesian(
                            cartographic));

                }
                if (dragging) {
                    mouseDroped = true;
                }
            },
            Cesium.ScreenSpaceEventType.MOUSE_MOVE
        );
        handler.setInputAction(
            function() {
                if (ZoneMoment && rightEntityPicked && mouseDroped) {
                    console.log('Left up ');
                    dragging = false;
                    mouseDroped = false;
                    scene.screenSpaceCameraController.enableRotate = true;

                    newArrayForZone(pickedEntity);
                    UpdatepolygonWithPoints(pickedEntity);
                }

            },
            Cesium.ScreenSpaceEventType.LEFT_UP
        );
    }
});

A: I am still looking for a better answer. for time being I did a long method.

*

*initially when polygon are drawn I changed it to Static polygon.

*On right clicked I get that entity and deleted that and recreate a dynamic polygon same as static but using callback. note I don't allow multiple polygon to edit at once

*you can play with dynamic polygon after that user saves the polygon and it converts back to static.

*Now user can click on some other polygon and repeat step 1.


text:
Q: How to update and display data summed up from DB by BLoC pattern in flutter? debt_dao.dart
Future totalAmount() async {
    final db = await dbProvider.database;
    var result = await db.rawQuery("SELECT SUM(amount) as Total FROM $debtDetailsTable");
    var total = result[0]['Total'];
    print(total); // It prints expected value ex. 1400
    return total;
  }

debt_repository.dart
Future getTotalAmt() => debtDao.totalAmount();

debt_bloc.dart
getTotalAmount() async {
    await _debtRepository.getTotalAmt();
  }

I want to display the output here, while doing like below, it prints null only.
debt_details.dart
Widget build(BuildContext context) {
    int _total;

    void calculateTotal() {
      _total = debtBloc.getTotalAmount();
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(_total.toString()), // Total should show/updated here
      ),

And one more thing, I have a form whenever i add data in form, total should be updated.
debt_form.dart
saveDetails() async {
await debtBloc.getTotalAmount(); // Even this prints null only
}

As i am new to flutte struggling for long. Pls guide me in right way. Thanks in advance.

A: well I don't have any idea what pattern of BLOC did you use, but from my case I used the rxdart for using the BLOC pattern.
Assume that your DB is something like this
Future<double> totalAmount() async {
    final db = await dbProvider.database;
    var result = await db.rawQuery("SELECT SUM(amount) as Total FROM $debtDetailsTable");
    double total = result[0]['Total'];
    return total;
}

then in your bloc.dart
final BehaviorSubject<Future<double>> _totalAmount = BehaviorSubject<Future<double>>();
Observable<Future<double>> get totalAmount => _totalAmount.stream;

Future<double> getTotalAmount(){
    final totalAmount = totalAmount();
    _totalAmount.sink.add(totalAmount);
}

then in your main.dart
Widget build(BuildContext context) {
int _total;

bloc.getTotalAmount();

return Scaffold(
  appBar: StreamBuilder(stream: bloc.totalAmount, builder:(Buildcontext context, Asyncsnapshot<Future<double>> snapshot){
    if(!snapshot.hasdata){
        // return no data
    }

    return FutureBuilder(future: snapshot.data, builder:(Buildcontext context, Asyncsnapshot<double> amountSnapshot){
        if(!amountSnapshot.data){
            // return no data
        }

        return AppBar(
    title: Text(_total.toString()), // Total should show/updated here

    })
  }),
}

Hope this sample code can help you solve this problems


text:
Q: point to point line-of-sight verification with barrier python I'm trying to create code that does calculation to know if the line is passing through the rectangle (obstacle), since I only know the position of sta1 and sta2 and I also know the x_min, x_max and y_min, y_max of the rectangle.

sta1 position(x,y) = (1,5) sta2 position(x,y) = (5,1)
retangle x_min = 3 retangle x_max = 4
retangle y_min = 2 retangle y_max = 3
I already have the function that returns the position of the stations:
sta1.position
(1,5)

I also already have the code to get the Euclidean distance between the points:
distance sta1 sta2
example: 20

That is, I need a code where given two points (x, y), and an obstacle that is a rectangle (x,_min, x_max, y_min, y_max), the output of the code informs if there is a line of sight or if the obstacle is in the middle of the way.
Some help in python doing this calculation would help.

A: I solved using the equation of the line:
# line/rectangle intersection (obstacle)

# node coordinates
source_x = 1
source_y = 5

destination_x = 5
destination_y = 1

# rectangle vertices

vertices_x = [3, 3, 4, 4]
vertices_y = [3, 2, 3, 2]

# Reduced equation of the line
# y = ax + b

# 1 - find the slope
# a = y2 - y1/x2 - x1

a = (destination_y - source_y) / (destination_x - source_x)

# 2 - find the linear coefficient

b = source_y - (a * source_x)

# f(x) = -(a*x) + y-(b)

signal_first = ''
result = ''
signal = ''
for i in range(0, 4):
    fx = -(a * vertices_x[i]) + vertices_y[i] - (b)
    if i == 0:
        value = fx
        if value > 0:
            signal_first = 'positive'
        elif value < 0:
            signal_first = 'negative'
    if fx > 0:
        signal = 'positive'
    elif fx < 0:
        signal = 'negative'

    if signal != signal_first:
        result = 'stations have no line of sight'

print(result)


text:
Q: How to prove this is a Group? On class, my teacher said that,if set $G$ is equipped with an operation: $G\times G\to G:(a,b)\to ab$ that satisfies:
(i) $(ab)c=a(bc)$ $\forall a,b,c\in G$
(ii) $\exists e\in G$ s.t. $ae =a$ $\forall a\in G$
(iii) $\forall a\in G$,$\exists a^\prime$ s.t. $aa^\prime =e$
Then G and this operation forms the group.
I've tried to prove $ae=ea$ or $a^\prime a=aa^\prime$ but it always forms a cycle...How cna I prove this? Any help and hints will be appreciated!
Best regards!


text:
Q: MongoDB: $push Multiple Objects, and $pop Multiple Objects in Single Update Imagine a MongoDB document with an array of 100 objects. And we want to keep the array length fixed at 100. When a batch of new objects arrives (could be 1, 5, 10, etc.), we want to update the array with new objects, while removing an equal amount of old objects so the array length will stay fixed. I've opted to reading the array from MongoDB into my app, making some modifications, then using $set to update the array:
var newData = [
  { ... },
  { ... },
  { ... },
  { ... },
  { ... }
];
var oldData = Collection.findOne({exchange: 'The Exchange', market: 'The Market'}).data;
newData = newData.concat(oldData).slice(0, 100);
Collection.update(
  {
    exchange: 'The Exchange',
    market: 'The Market'
  },
  {
    $set: {
      data: newData
    }
  }

Is it possible in MongoDB to $push the new on to the front, while simultaneously using $pop to remove an equal amount of objects off the back?

A: Well the answer is both "yes" and "no" to put it in slightly confusing terms. What you cannot do is both $push and $pull operations on the same array in a singular update. This is not allowed for the "same path" of operations because neither $push or $pull is really determined to occur in any order within the current update syntax.
However in your specific context, that is not what you are asking. To do what you want, MongoDB supports the $slice modifier which can be used along with $each. This will effectively "limit" the total size of the array as new items are added to it.
Following your example:
Collection.update(
    { "exchange": "The Exchange", "market": "The Market" },
    { "$push": { "data": { "$each": newData, "$slice": 100 } } }
)

That effectively limits the size of the array to the first 100 members whilst adding the new items to it.
Take note though that this may not be supported in the client version of "minimongo" as implemented by meteor. What you can do though is execute this on the server, and expose the method via publish. There are plenty of examples to show you how to use publish.

A:
Is it possible in MongoDB to $push the new on to the front, while simultaneously using $pop to remove an equal amount of objects off the back?

Yes, using $slice:
$push: {
    data: {
       $each: [ { ... }, { ... } ], // your batch
       $slice: -100 // maximum array size
    }
 }

For an example, see http://docs.mongodb.org/manual/tutorial/limit-number-of-elements-in-updated-array/


text:
Q: Struggling with enabling a PostGIS database on Mac I have installed PostGIS on the mac using the binaries available on http://www.kyngchaos.com/software:postgres
Postgres v 9.1.3
PostGIS v 2.0
After that I want to enable postgis for my database. I tried using CREATE EXTENSION query. But it error'ed out saying that the extension is not available. I then tried
sudo -u postgres psql -d [your database] -f /usr/local/pgsql/share/contrib/postgis-2.0/postgis.sql
Password:
SET
BEGIN
psql:/usr/local/pgsql/share/contrib/postgis-2.0/postgis.sql:69: ERROR:  could not access file "$libdir/postgis-2.0": No such file or directory

How can i make $libdir expand into the path which i found by executing
$ pg_config --pkglibdir
/usr/lib/postgresql

The /usr/lib/postgresql does NOT contain postgis-2.0.
Digging around for a few more hours I found a hacky solution:
export PATH=/usr/local/pgsql/bin:$PATH

This makes the pg_config magically change to:
$ pg_config --pkglibdir
/usr/local/pgsql-9.1/lib

And then I hardcode that path into the postgis.sql file. But I want to know why $libdir doesnt resolve automatically.

A: I get the same error after updating postgres with a working postgis install. Although this does not answer the original question, I'm adding this answer since the error is the same. The postgis .so files will not be in the postgres package directory (pg_config --pkglibdir) after a new postgres install. These files need to be there:
$ ls -l /usr/local/Cellar/postgresql/9.2.3/lib | grep postgis
-rwxr-xr-x  1 tee  wheel   585416 Feb 24 14:39 postgis-2.0.so
-rwxr-xr-x  1 tee  wheel   434752 Feb 24 14:39 rtpostgis-2.0.so

The simplest solution is to reinstall postgis after a postgres update:
brew uninstall postgis
brew install postgis

A: When you run psql, you're probably running the binary that's installed on OSX by default in /usr/bin. Run 'which psql' to be sure. Altering your $PATH like that changes which pg_config you're using. That's not a hacky solution to change your $PATH like that, it's perfectly OK. I recommend installing Postgres and PostGIS using homebrew though.


text:
Q: SPA + Backend + Office365 SSO I am building an application consisting of the following

*

*SPA (Provides a front end for the user to perform actions) - app.myservice.com - React JS

*API (Provides the core business logic and is called by the SPA) - api.myservice.com - Node JS
What I would like to do is allow people to "Signup" to my application (as a whole) using Office 365.
However.... I want the API to generate JWT tokens which the SPA will use to communicate with the API in the future. I do not want the SPA to have Office365 specific tokens.
The process would look like this at a high level:

*

*User goes to app.myservice.com

*User clicks "Signup"

*User is redirected to Office365 to provide login details

*Office365 redirects to my API

*API creates a local user in its database

*API generates a JWT

*API returns JWT to SPA

*SPA calls API using JWT to perform actions.

What is unclear to me, is what OAuth2/OpenID flow type to use in order to achieve this.
Further this, I would like to understand if my approach has any flaws in general.
Many Thanks

A: In step 3 above, I think your SPA should redirect to Azure AD, which is where the user signs in. Your SPA will then receive an Azure AD token and can send it to the API. The API can potentially read user info and create a user if required. APIs should not issue their own tokens or receive redirects. Not sure if this will 100% meet your requirements but it is the standard pattern for the 3 legged SPA and API OAuth 2.0 based dance.


text:
Q: Using python, how to save a valid audio file from bytes? I am working with speech recognition library in Python and trying to save an audio file after submiting to the API that recognize it. So, my problem comes when I want to save that audio to a file.
import speech_recognition as sr

r = sr.Recognizer()
mic = sr.Microphone()

print('Recording...')
with mic as source:
    audio = r.listen(source)

with open("audio_file.wav", "wb") as file:
    file.write(audio.frame_data)

The audio_file.wav have a size approximately of 210kb(about 4 or 5 seconds recording)
when I try to reproduce the audio file.wav, the player throws an error saying that can not play the audio... due to a codec problem.
My question are:
am I missing save a headers or something like that?
Is there another way to saves audio bytes into a file?
Edit
My answer is in this question Wav file from microphone on Python

A: Change audio.frame_data to audio.get_wav_data().


text:
Q: jquery mobile: Is there a way to add a ticker in footer? I am making an mobile app and would like to add a ticker which will run non-clickable, static, pre-defined text or icons.
Can somebody give some pointers regarding this?

A: You might try to use: SLY: http://darsa.in/sly/examples/horizontal.html
Centered horizontal style with long animation time might do the job. With setInterval that will trigger next item action you should be able to do the ticker.


text:
Q: Saving document scans as PDF using Office Lens I have Office Lens (version 2.22) on my iPhone Xs.
I can't seem to save documents that I scan as PDF files. Office Lens saves them on OneDrive as JPG files and there are no settings anywhere that I could find.
Is there a way to save them as PDF?

A: OfficeLens offeres 4 different ways to scan something

*

*Whiteboard

*Document

*Business Card

*Photo

If you select the "Photo" mode, the result will be a JPG file, which by its very nature will not be easy to convert to PDF.
If you select the "Document" mode, OfficeLens will try to recognize the text and save it in a text format, which can easily be converted to PDF on a PC. Some elements of the original may not make it into the result though, like logos and non-text elements.
If OfficeLense cannot recognize the text, the result of a "Document" scan may still be a JPG.
But when you select where to store the result, the list includes "PDF". If you select that option, the image will be in a PDF file.
For more information about OfficeLens on iPhone, please refer to this Microsoft Support article, which has screenshots and step by step instructions.

A: too many words... Here's what you need to do:

*

*Define at least one page from the pile of photos as a "Document" (icon at the top of photo allows you to select the type). If there are no "document" pages in the bunch, it will not allow you saving PDF. That's famous MS's user-friendliness.

*Clicking next, select PDF. By default it sends to onedrive. But if you hold the option with a finger, then you can choose a local storage (fixed location in device/documents)

*don't forget to rename

*save - real, fine looking multipage PDF will be created.

Unfortunately, on Galaxy device/documents is not accessible from Skype, so you may have to move it somewhere, like SD-storage location, where Skype can pick it up.


text:
Q: SSL certificate issues when communicating with Ably I'm on a Windows system and when I try connecting to Ably, I'm getting the following errors(s):
  cURL error: SSL certificate problem: self signed certificate in certificate chain
  SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

What am I doing wrong?

A: This error is caused by out of date root certificates on your server or local machine.  In order to fix this problem, follow the instructions from one of the related issues:
PHP SSL certificate problem
Ruby certificate verify failed


text:
Q: Is there a forcing extension $M[G]$ of $M$ that adds a new $\omega$-sized subset to $\omega_2$ without adding any new subsets of $\omega$? I should add that the forcing extension must preserve the cardinals $\aleph_1$ and $\aleph_2$.
Note that such a forcing extension cannot add any new $\omega$-sized subsets to $\omega_1$, and also cannot be $\omega$-distributive.
If necessary, you may assume $M \models GCH$.
I suppose that the question arises from my wondering about if a forcing extension not add any new subsets of $\omega$, must it also not add any new $\omega$-sized subsets to anything else?
Thanks.

A: You might want to look into Namba forcing.
This forcing changes the cofinality of $\omega_2$ to be countable, and assuming $\sf CH$ it does that without adding new reals. In particular $\omega_1$ is preserved.

A: If you insist that both $\omega_1$ and $\omega_2$ are preserved then this is impossible. The reason is that, since $\omega_2$ is preserved and, in particular, remains regular in $M[G]$, any countable subset $X$ of it in the extension must be bounded. But given a bound $\alpha<\omega_2$, we can fix in $M$ a bijection $f\colon \omega_1\to\alpha$. Then $X\subseteq\omega_2$ is new iff $f^{-1}[X]\subseteq\omega_1$ is new, but as you state (or following a version of Noah's argument), there can be no new subsets of $\omega_1$.
If you allow $\omega_2$ to be collapsed then Asaf's Namba forcing suggestion works (at least under CH). Allowing $\omega_1$ to be collapsed doesn't really make sense, since collapsing it will just add a real.
Interesting things start to happen when you try to replace $\omega_2$ with larger cardinals $\kappa$. If you want cardinals to be preserved, the argument above tells you that $\kappa$ cannot remain regular (or even of uncountable cofinality) in the extension (in particular, this cannot work for any successor $\kappa$). Jensen covering voodoo then says that you should really have something like a measurable running around. But if we have a measurable $\kappa$ then Prikry forcing at $\kappa$ is exactly the type of thing you are looking for: it preserves cardinals, does not add bounded subsets of $\kappa$, but does add an (unbounded) countable subset to $\kappa$.


text:
Q: Adding ffmpeg terminal code as a quick action I created a terminal code to add timestamps to a video, now I want to add this code as quick action using automator.
ffmpeg -i example.mp4 -vf "drawtext=fontfile=Arial.ttf: text='%{frame_num}': start_number=1: x=(w-tw)/2: y=h-(2*lh): fontcolor=black: fontsize=65: box=1: boxcolor=white: boxborderw=5" -c:a copy example-timestamp.mp4

I want to right click a video and select a quick action to create new version of my video with timestamp. Should I add this code automator with quick action option or another? Should I change the code?
This is the code I tried to add but it did't work.
ffmpeg -i "$@" -vf "drawtext=fontfile=Arial.ttf: text='%{frame_num}': start_number=1: x=(w-tw)/2: y=h-(2*lh): fontcolor=black: fontsize=65: box=1: boxcolor=white: boxborderw=5" -c:a copy "$@-converted.mp4"


text:
Q: Grid an image with opencv python with respect to image size I am trying to have a grid over a picture using the cv2.line method. Right now, I am doing a for loop that goes to the width of the image so I can put a couple of vertical lines across my image. However, after I run and compile the code, I get a window with a blue picture
img = cv2.imread("target.PNG")

height, width, channels = img.shape
for x in range(0, width -1, 1):
     cv2.line(img, (x, 0), (x, height), (255, 0, 0), 1, 1)

cv2.imshow('Hehe', img)
key = cv2.waitKey(0)

Right now, this is for the vertical lines only. I will later add the horizontal ones once I get this working. It outputs a full blue screen rather than grids. I tried playing with the number according to the beginning and end of (x,y) coordinates.

A: You are drawing blue lines to entire image without skipping any pixel, set step size of your range to something like 20. For example:
img = cv2.imread("target.PNG")
GRID_SIZE = 20

height, width, channels = img.shape
for x in range(0, width -1, GRID_SIZE):
     cv2.line(img, (x, 0), (x, height), (255, 0, 0), 1, 1)

cv2.imshow('Hehe', img)
key = cv2.waitKey(0)


text:
Q: How to use the values of a list that is inside another list as arguments of a function in Python I am very new to Python.  I have a function DISTANCE(lat1, long1, lat2, long2) that calculates the distance between 2 points.
Then I have a list called POINTS, where each value is another list which contains those four values.
I would like to obtain the sum of the results of the function DISTANCE for all the values inside POINTS.
Can anybody help me with that?  Thanks!

A: sum(DISTANCE(*p) for p in POINTS)

The * here is the syntax for Unpacking Argument Lists, also called the splat operator.  This passes the contents of an iterable as the positional arguments to a function, so if p were [1, 2, 3, 4], DISTANCE(*p) would be the same as DISTANCE(1, 2, 3, 4).

A: How about:
totalDistance = sum(DISTANCE(lat1, long1, lat2, long2) for (lat1, long1, lat2, long2) in POINTS)

A: sum([DISTANCE(*args) for args in POINTS])

What this one-liner does is use a list comprehension on POINTS, applying each item in it as a list to DISTANCE, like this:
args = [1, 2, 3, 4]
DISTANCE(*args) == DISTANCE(1, 2, 3, 4)

The call to sum takes a list itself and returns the sum of all the items within.
A side suggestion: name your functions in all lowercase.  PEP 8 has a lot of good style suggestions for making readable Python code.

A: use for-in loop if you're new to python:
result=[]
for item in POINTS:
    res=DISTANCE(*item)
    result.append(res)
print(sum(result))

if you're confused about what's * here, you should read this


text:
Q: zabbix trigger for difference between 2 values from 2 fields I am trying to figure out how to have Zabbix pull values from 2 fields, compare them and trigger if  the  difference between them exceeds a certain value

A: If one is always larger than the other and using a threshold of 13:
{host:item1.last()}-{host:item2.last()}>13

If their relative sizes are unknown, cannot think of anything nicer but this:
({host:item1.last()}-{host:item2.last()}>13) or ({host:item2.last()}-{host:item1.last()}>13)

A: You can collect the two fields as standard items (snmp values, agent values etc), then create a calculated item with their difference and appy to it your triggers.


text:
Q: Merge two Json files with awk in bash I try to merge two json files in a one file, but with one condition, e.g : if the file 1 has for example : testa:result>fail and the file b contains the same line but with a different result e.g : testa:result>pass, i would like that the file 1 it will be update with the results from file 2, i have this line with awk command but it only merge the files without this condition :
awk 'BEGIN{print "{"} FNR > 1 && last_file == FILENAME {print line} FNR == 1 {line = ""} FNR==1 && FNR != NR {printf ","} FNR > 1 {line = $0} {last_file = FILENAME} END{print "}"}' json_files/* > json_files/all_merged.json

Please I need help with this.

A: I would suggest use python for the task. Consider this example:
import json
from pprint import pprint

fileName1 = "file1.json" # file1 contains something like { "Testname": "color", "result": "fail" }
fileName2 = "file2.json" # file2 contains something like { "AnotherTestname": "color2", "result": "pass" }
fileNameTo = "file3.json"

def visualize(data, prompt):
    print(prompt)
    pprint(data)
    raw_input("Press <Enter> to continue: ") # this line pauses the execution

def loadData(fname):
    with open(fname, "r") as f:
        return json.load(f)

jd1 = loadData(fileName1)
visualize(jd1, "Data from %s" % fileName1)
jd2 = loadData(fileName2)
visualize(jd2, "Data from %s" % fileName2)
jd3 = jd1.copy() # create a copy of data from file1, this step can be avoided if you don't need unmodified jd1
visualize(jd3, "Data after copying")
jd3.update(jd2) # merge copy of data from file1 with file2, updating corresponding keys
visualize(jd3, "Data after merging")
with open("file3.json", "w") as f3:
    json.dump(jd3, f3)

This version of script gained some "interactivity", it let you control data state on each step of execution. I've just checked it performs data merging as expected. Please try to run it against your test data and look at the output.


text:
Q: In spring integration, how do I catching different exceptions? In spring integration I have a simple tcp client pipe: a gateway, a tcp outbound gateway a service activator plus an error channel. In the tcp-connection-factory there is a simple interceptor. The error channel very simple, I implemented the tcp-connection-event-inbound-channel-adapter with this filter:

*

*org.springframework.integration.ip.tcp.connection.TcpConnectionExceptionEvent.

So my error handler very simple,looks like this :
public class TcpErrorHandler {
    public void onException(){
        System.out.println("Exception!!! ");
    }
}

It works, because when I have a Socket close Exception ( the server side I close the connection ) , the application writes "Exception!!!" to the console, but other hand, it doesn't work, when I have connection time out exception.
My questions are : How do I get all most relevant exceptions for me:

*

*Runtime Socket close Exception

*Connection time out exception

*Other exceptions

Are there any catching mechanism ?
Here is a snipet from my bean config:
<!-- Client side -->

<int:gateway id="gw"
    service-interface="hu.gmxdev.climaxreplica.service.SimpleGateway"
    default-request-channel="outputchannel" />

<int-ip:tcp-connection-factory id="client"
    type="client" host="localhost" port="10001" single-use="true"
    so-timeout="2000" deserializer="climaxDeserializer"
    interceptor-factory-chain="customInterceptorFactoryChain"/>

<int:channel id="outputchannel" />

<int-ip:tcp-outbound-gateway id="outGateway"
    request-channel="outputchannel" reply-channel="replychannel"
    connection-factory="client" request-timeout="2000" reply-timeout="2000" />

<int:service-activator input-channel="replychannel"
    method="reply" ref="echoService" id="serviceactivator">
</int:service-activator>

<int:channel id="replychannel"></int:channel>

<bean id="customInterceptorFactoryChain"
        class="org.springframework.integration.ip.tcp.connection.TcpConnectionInterceptorFactoryChain">
        <property name="interceptors">
            <array>
                <bean class="hu.gmxdev.climaxreplica.service.CustomInterceptorFactory"/>
            </array>
        </property>
</bean>

<!-- Error channel -->

<int-ip:tcp-connection-event-inbound-channel-adapter id="event"
    error-channel="errorChannel"
    event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionExceptionEvent" />

<int:channel id="errorChannel"></int:channel>

<int:service-activator ref="tcpErrorHandler" method="onException"
    input-channel="errorChannel">
</int:service-activator>

And here is my error handler :
public class TcpErrorHandler {
    @Autowired
    private ApplicationContext appContext;

    public void onException(TcpConnectionExceptionEvent event){
        MainService mainService = appContext.getBean(MainService.class);
        mainService.setSuccess(3);
        System.out.println("Exception!!! ");
        System.out.println(event.getCause().getMessage());
    }
}

The interceptor is here :
public class CustomInterceptor extends TcpConnectionInterceptorSupport{

    public CustomInterceptor () {
        System.out.println("catched_constructor1");
    }

    public CustomInterceptor (ApplicationEventPublisher applicationEventPublisher) {
        super(applicationEventPublisher);
        System.out.println("catched_constructor");
    }

    @Override
    public boolean onMessage(Message<?> message) {
        System.out.println("catched_message");
        return super.onMessage(message);
    }

    @Override
    public void send(Message<?> message){
        System.out.println("catched_send");
        MessageHeaders mh = message.getHeaders();
        try {
            super.send(message);
        }
        catch (Exception e) {
            System.out.println("catched_send_exception");
        }
    }

    @Override
    public void close() {
        String id = getConnectionId();
        System.out.println("catched_closed" + id);
        super.close();
    }

}

And my "caller" :
success = gateway.send("fooooooo");

A: You can define an error channel, that you provide to your inbound adapter. Here is an example:
    <int:channel id="error-channel"></int:channel>
    <int-ws:inbound-gateway id="gateway" error-channel="error-channel"
    request-channel="in"  marshaller="marshaller" unmarshaller="marshaller"
    reply-channel="out" />

Now all exception that are thrown downstream will be catched by this error-channel.
You can then define a service activator with this error channel as an input:
 <int:service-activator  input-channel="error-channel"
        ref="exceptionHandler" method="handleError" output-channel="outError"></int:service-activator>

And this activator refers to a bean that defines error handling logic.

A: Actually <tcp-connection-event-inbound-channel-adapter> send to the channel a Message with TcpConnectionExceptionEvent (in your case) as payload.
Therefore your subscriber (your TcpErrorHandler) can accepts TcpConnectionExceptionEvent as a method argument.
In that method you can do further logic, e.g. extract the original Exception from that IntegrationEvent.
There are several places in the IP module when TcpConnectionSupport.publishConnectionExceptionEvent is used.
If you say that you don't catch time out exception, it will great if you share the logs on the matter. I wonder which place we don't try...catch on the SocketTimeoutException...
UPDATE
<int-ip:tcp-connection-event-inbound-channel-adapter channel="events"
    event-types="org.springframework.integration.ip.tcp.connection.TcpConnectionExceptionEvent"/>

<service-activator input-channel="events" ref="tcpErrorHandler"/>

public class TcpErrorHandler {

   public void onException(TcpConnectionExceptionEvent event) {
       System.out.println("Exception!!! ");
       event.getCause();
       ....
   }

}

This should work.
UPDATE2
According to your code:
try {
   super.send(message);
}
catch (Exception e) {
    System.out.println("catched_send_exception");
}

Don't you think that it is bad to suffocate an Exception there?
From other side: would you mind switching on DEBUG logging level for the org.springframework.integration category and share here the logs, when you are sure that your tcpErrorHandler should be invoked?
From other side try <int-ip:tcp-connection-event-inbound-channel-adapter> without event-types at all. I mean let's see, if it handle any IpIntegrationEvent.


text:
Q: Function overloding in Swift func performOperation(operation: (Double, Double) -> Double){
    if operandStack.count >= 2 {
        displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
        enter()
    }
}

func performOperation(operation: Double -> Double) {
    if operandStack.count >= 1 {
        displayValue = operation(operandStack.removeLast())
        enter()
    }
}

The error shown is " Method 'performOperation' with Objective-C selector 'performOperation:' conflicts with previous declaration with the same Objective-C selector "
This error is shown in second function.
I want to use two functions with same name but different input types, but Xcode is showing an error. How can I correct the error?

A: Objective-C does not support method overloading. When you inherited UIViewController you inherited NSObject and made the class interopable to Obj-C. Swift on the other hand does support overloading, that's why it works when you remove the inheritance.


text:
Q: Ngx-chips custom theme doesn't work awesome component. I am using the latest version of ngx-chips with Angular 5. I tried to make custom theme the same as here , but it doesn't work. Here is my .scss file:
@import '~ngx-chips/core/styles/core/_core.scss';

$foundation-primary: #1779ba;
$foundation-primary-dark: darken($foundation-primary, 10%);

// this is the container's theme
$foundation-theme: (
container-border-bottom: 1px solid $foundation-primary
);

// this is the tag's theme
$foundation-tag-theme: (
background: $foundation-primary,
background-focused: $foundation-primary-dark,
background-active: $foundation-primary-dark,
background-hover: $foundation-primary-dark,
color: #fff,
color-hover: #fff,
border-radius: 2px
);

// this is the delete icon's theme
$foundation-icon-theme: (
fill: #fff,
fill-focus: #eee,
transition: all 0.35s
);

// apply theme to the container
:ng-deep .ng2-tag-input.foundation-theme {
@include tag-input-theme($foundation-theme);
}

// apply theme to the tags
:ng-deep .ng2-tag-input.foundation-theme tag {
@include tag-theme($foundation-tag-theme);
}

// apply theme to the delete icon
:ng-deep .ng2-tag-input.foundation-theme tag delete-icon {
@include icon-theme($foundation-icon-theme);
}

Also i found the same issue, but there was no answer. What am i doing wrong?

A: use '::ng-deep' instead of ':ng-deep'


text:
Q: Unable to understand d3js zoom functionality The following SIMPLE :) code gives following error. Please help me what mistake I am making to ZOOM on onClick on the Circle ?
Similarly I will be very thankful if someone can give some idea that if i want to zoom to 3rd Circle DIRECTLY without clicking on it; what should I do ?
ERROR: Uncaught TypeError: Cannot read property 'apply' of undefined
    at qr.call (d3.min.js:2)
    at SVGCircleElement.clicked (index.html:52)
    at SVGCircleElement.<anonymous> (d3.min.js:2)

And here is the code.
    <!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1,maximum-scale=1" />
        <title>Zoom & Pan</title>
        <link rel="stylesheet" type="text/css" href="styles.css" />
        <script type="text/javascript" src="d3.min.js"></script>

        <style type="text/css">

        </style>
    </head>

    <body>

        <script type="text/javascript">
            var width = 600, height = 350;
            var data = [
                { "r": 10, "cx": 100, "cy": 150 },
                { "r": 30, "cx": 200, "cy": 150 },
                { "r": 15, "cx": 300, "cy": 150 }

            ];
            var svg = d3.select("body").append("svg")
                .attr("width", width)
                .attr("height", height)
                .call(
                        d3.zoom()
                        .scaleExtent([1, 7])
                        .on("zoom", zoom)
                );

            const g = svg.append("g");

            g.selectAll("circle")
                .data(data)
                .enter()
                .append("circle")
                //.attr("fill", function (d) { return d.color; })
                .attr("fill", (d, i) => d3.interpolateRainbow(i / 3))
                .on("click", clicked)
                .attr("r", function (d) { return d.r; })
                .attr("cx", function (d) { return d.cx; })
                .attr("cy", function (d) { return d.cy; });

            function clicked(d,i,nodes) {
                console.log(nodes);

                svg.transition().duration(750).call(
                    zoom.transform,
                    d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-d.cx, -d.cy),
                    d3.mouse(svg.node())
                );

            }

            function zoom() {
                g.attr("transform", d3.event.transform);
            }

        </script>

    </body>

    </html>

A: The issue is that zoom.transform is not a thing. You have created a function called zoom, if that is important then you'll need to create another variable called something else, e.g. zoomer, probably in window scope, like width and height:
var zoomer = d3.zoom();

Then in your click handler change zoom.transform to zoomer.transform:
function clicked(d,i,nodes) {
  console.log(nodes);

  svg.transition().duration(750).call(
    zoomer.transform, //change here
    d3.zoomIdentity.translate(width / 2, height / 2).scale(40).translate(-d.cx, -d.cy),
    d3.mouse(svg.node())
  );
}

If you don't need the zoom function, then delete that and create the zoom variable like the zoomer one above and don't change the click handler.


text:
Q: using jquery in angularjs? I was working on angularjs and i got strucked in using jquery with angularjs.
Here is my html code.....

here is my js code............
$( function() {

  var packery = $('.packery').packery();

  console.log(packery);

  packery.on( 'click', function( event ) {
    // remove clicked element
    packery.packery( 'remove', event.target );
  });
});

Please help me convert this jquery code to work in angularjs. I am new to jquery, I tried many ways to solve this.
Thanks in advance...

A: For a simple click event you need ng-click within your template described  at https://docs.angularjs.org/api/ng/directive/ngClick
No need for jQuery in this case

A: I assume you have included jQyery
       $.noConflict();
       jQuery(function() {
           jQuery('.packery').on('click',function(){
              jQuery(this).remove();
           });
       });

Fiddle

A: If you want to simply remove the clicked element, use this:
Your HTML:

   .......

Your Controller:
function myController( $scope ){
   $scope.remove=function($event){
       $event.target.remove();
  }
}

Check our the Fiddle example.

A: This is a good use case for an Angular directive. You can use an html attribute to specify which element the jQuery plugin should be applied to:
angular.module("mymod")
.directive("packery", function(){
  return {
    link: function(scope, element, attrs) {
      $('[packery]').packery().on('click', function(event){
        $(element).packery('remove', event.target);
      });
    }
  }
});

Then, whenever you want this jQuery plugin to be applied to an element, you simply give that element the packery attribute:

...


text:
Q: Correct color profile and saving? Thumbnail creation? I've never had this issue SRGB and everything looks good on screen, then on upload my reds turn like ... brownish pink.
Edit: adding this just incase someone suggests monitor calibration or something. This is Octobers upload folder via FTP. Something is up with the thumbnail creation here.


text:
Q: Preg_match_all patterns except I am trying to get all occurrences of a specific tag from a text field, and retrieve only part of it's content

TEXT TO RETRIEVE HERE

EVERYTHING ELSE

The issue I have is that not in every case does a BR tag show up, so when it does, I want to exclude it + everything following it

EVERYTHING ELSE

I tried the following preg_match_all, but no luck:
preg_match_all('/
(.*?)
.*<\/h4>/ims', $text, $match)

A: Try:

.*?(?=
|$)

with "dot matches line-break"  and ^$ don't match at line break options enabled
If you need to ensure that the closing tag exists at the end, you can try:

.*?(?=(?:
.*
)|(?:
))

A: I think you need something like this,

((?:(?!
).)*)(?=
|<\/h4>)

It captures the value after the
 tag which are not of
 zero or more times. And it must be followed by a
 tag or
 tag.
DEMO


text:
Q: Easiest way to add custom properties to existing controls in winform? I have a grid of Panel Controls in Winform.
I would like for those panels to contain a custom string and custom int property.
What would be the easiest way to achieve that?
One way would probably be extending the Panel control, but I do not want to do big changes to the control, just to add 2 custom properties.
I am using .NET 4.0
Any pointers you can give to me will be appriciated.

A: If these are properties of the class, then deriving from Panel and creating a custom implementation are the best bet, especially if you are using this on multiple forms or multiple projects. You could "cheat" by adding extension methods, but setting up individual getter and setter methods to implement properties is a bit more pain than you have to go through.

A: You answered your own question:

One way would probably be extending the Panel control...

Just add your properties and start using the control.


text:
Q: Is there a general algorithm to decide whether an integer value is attainable by a quadratic form? I'm not sure if I phrased the question correctly, but let's say that due to a result called 15 theorem that "if a positive definite quadratic form with integer matrix represents all positive integers up to $15$, the it represents all positive integers". As I'm new to the theory of quadratic forms (I only read, partially, the first lecture of "THE SENSUAL (quadratic) FORM" by Conway and Fung), I'm interested by the question of checking whether an integer value is retrieved as a result of a quadratic form.
More formally, for any fixed $n \in \mathbb{N}^*$, given $A \in \mathcal{M}_n(\mathbb{Z})$ positive definite and $k \in \mathbb{N}$, is there a general algorithm to find (or decide whether there exists) $x \in \mathcal{M}_{n \times 1}(\mathbb{R})$ such that $x^T A x = k$?
Correct me if I'm wrong, but from a "numerical" point of view, I think one can find the roots of the multivariate polynomial $E(x) = x^T A x - k$, and check for each root whether it is an integer. This may be able to solve using some traditional multivariate polynomial root finding algorithms (which I don't know, and I'm not sure if it works). Is there any algorithm that specifically answer this problem (numerically, algebraically, or combinatorially)?
At first, it looks as if it is an NP problem, since given $x \in \mathcal{M}_{n \times 1}(\mathbb{R})$ (in particular, I'd rather say $\mathcal{M}_{n \times 1}(\mathbb{Q})$ instead), one can verify the equation $x^T A x = k$ easily. However, due to something like this (The Uncracked Problem with 33 - Numberphile), I'm afraid that $x$ might be very large, and hence, might contain information bigger than polynomial on $n$.
Edit: To ask for a solution in $\mathbb{R}^n$, this looks like I'm asking the wrong question. Since it is positive definite, I can descend ($\mathbb{R}^n$-wise) the "well" to find the minimum real $m > 0$ representable by the form, then any integer $k \geq m$ is representable by the form at some point in $\mathbb{R}^n$ due to continuity and unboundedness of the form. So maybe the interesting question is to find solutions in $\mathbb{Q}^n$ or $\mathbb{Z}^n$. Note that I also found this Wikipedia article on Hilbert's 11th problem, which I haven't yet understood it completely. Further explanations are appreciated.
Edit 2. No. The original "descend the well" algorithm only works on integral binary quadratic forms, but in this case the interesting question lies on a more general setting of multivariate (more than 2 variables) quadratic forms. But I guess there should be something that works the same, i.e., some algorithm that gives the minimum real value represented by a quadratic form. Hmm... I don't know.
Edit 3. As suggested by Gerry Myerson, I'm editing this to explicitly state the question as follows:
Problem. For $n \in \mathbb{N}^*$ fixed, given symmetric positive definite $A \in \mathcal{M}_n(\mathbb{Z})$, and given $k \in \mathbb{N}$. Is there a general algorithm to find $x \in K^n$ such that $x^T A x = k$?
Question 0. For $K = \mathbb{R}$ (answered by Gerry Myerson in the comments)
Question 1. For $K = \mathbb{Q}$.
Question 2. For $K = \mathbb{Z}$.


text:
Q: override a method but return should be different in C#? I have one interface like below.
public interface IUser
{
    List<AppUser> GetAllUser();
}

and implementation.
public class ObjUser:IUserDao
{
    public virtual List<AppUser> GetAllUser()
    {
        throw new NotImplementedException();
    }
}

This works fine.
Now i would like inherit ObjUser in CUser class
public class CUser:ObjUser
{
   public override List<ExtAppUser> GetAllUser()
   {
       List <ExtAppUser> extendeduser=new List<ExtAppUser>() ;
       return extenduser;
   }
}

And ExtAppUser is inherited from AppUser class.
public class ExtAppUser:AppUser
{
     ///// Extend the properties.
}

But i get compile error as return type should be same. How to handle in C#? I believe it is possible in Java.

A: You are asking for a way to corrupt the type system.  A simple example of the failure mode is:
public AddUser(IUser users) {
    var newuser = new AppUser("hans');
    users.GetAllUser().Add(newuser);
}
...
var obj = new ObjUser();
foo.AddUser(obj);

If this code could execute then the List<ExtAppUser> would contain an element of type AppUser.  Which is a direct violation of the promise that the list can only contain ExtAppUser elements.
This is of course not good.  Type checking exists to prevent accidents like this.
This is a general problem called "covariance".  C# version 4 added some support for it, described in this MSDN page.  That isn't otherwise going to get you anywhere as long as you let IUser.GetAllUser() return a mutable object, you'll have to tone down the return type to a much lesser type like IEnumerable.  Which is okay because nobody can corrupt the object through that interface type, it only permits reading from the underlying object.  Whether that's applicable to your design is impossible to tell.


text:
Q: Modeling Attrition: Imbalanced Training First of all, let me say I am new to Machine Learning and am eager for any sort of feedback. I am attempting to create a predictive attrition model, and my training and test data each have ~ 17% records for leaving. My goal would be to produce a "good" model for predicting attrition.

*

*Is this considered imbalanced? Do I need to use SMOTE or some sort of resampling here?

*If yes, I know that in order to use SMOTE, I must do it to the training set only, but I am unsure of how to re-sample while simultaneously cross-validating?

*Once the model is constructed, what are "acceptable" levels for accuracy/precision/recall? Should I care about other things as well?

Here is the code I have used for SMOTE:
# Create training and test data sets
# Ensure results are repeatable
set.seed(7)
training <- createDataPartition(t_final2$attrit,times = 1,p=0.5) %>% unlist()
train_data <- t_final2[training,]
test_data <- t_final2[-training,]

# use SMOTE to artificially upsample attrits in our data set
train_data %<>% as.data.frame()
train_data <- SMOTE(attrit ~., train_data,k=10,perc.over= 100,perc.under = 350)
table(train_data$attrit)
  0    1
3227 1844

Next, I used a XGBoost model:
train <- setDT(train_data)
test <- setDT(test_data)

labels <- train$attrit
labels <- as.numeric(labels)-1
ts_label <- test$attrit
ts_label <- as.numeric(ts_label)-1

new_tr <- model.matrix(~.+0,data=train[,-c("attrit"),with=F])
new_ts <- model.matrix(~.+0,data=test[,-c("attrit"),with=F])

dtrain <- xgb.DMatrix(data=new_tr,label=labels)
dtest <- xgb.DMatrix(data=new_ts,label=ts_label)

# Set Parameters
params <- list(booster = "gbtree", objective = "binary:logistic", eta=0.3, gamma=0, max_depth=6, min_child_weight=1, subsample=1, colsample_bytree=1)

# use cv to tune model, and return cv error
set.seed(7)
xgbcv <- xgb.cv(params = params, data = dtrain, nrounds = 150, nfold = 5, showsd = T, stratified = T, print_every_n = 10, early_stopping_rounds = 10, maximize = F)

# Result
Stopping. Best iteration:
[63]    train-error:0.080457+0.005289   test-error:0.174126+0.018541

# Model Training
xgb1 <- xgb.train (params = params, data = dtrain, nrounds = 63, watchlist = list(val=dtest,train=dtrain), print_every_n = 10, early_stop_round = 10, maximize = F,eval_metric = "error")
xgbpred <- predict(xgb1,dtest)
xgbpred <- ifelse(xgbpred > 0.5,1,0)

# Look at Confusion Matrix
confusionMatrix(xgbpred,ts_label,positive = '1')

Results are in screenshot below. I know that my recall is low, I was hoping to improve the model. Any feedback is appreciated!

A: *

*It depends on who you ask. If people have a background in fraud detection or something, they would consider < 1% to be imbalanced. But I have seen papers that consider 17% somewhat imbalanced (see Table V here: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.1903&rep=rep1&type=pdf). I would say it isn't what most people would consider a class imbalance problem; but, in the end, the data don't really care what you label the size of the minority class. I would try out SMOTE, upsampling, and downsampling. Those tend to appear the most-mentioned in reviews of class imbalance. The unbalanced package in R provides a number of good functions (https://cran.r-project.org/web/packages/unbalanced/unbalanced.pdf). Of course, it would be helpful to compare models when you did no sampling techniques so that you could deem if they were really necessary.

*For cross-validation, you would do the sampling technique on the training set and not on the test set. If you did this using 5-fold CV, imagine you then have folds labeled A, B, C, D, and E. First, you would do SMOTE on A - D, train the model on A - D, test on E. Second, you would do SMOTE on A - C and E, train on A - C and E, then test on D. Each time, you would save whatever scores you want. There is definitely a way to code this in a clever way that could be parallelized (perhaps a package, like caret, has already done something like this?), but that's how I see CV working in this context.

*If you are concerned about class imbalance, then accuracy really shouldn't be much of a concern to you. I take it that you are particularly interested in predicting those 17% of cases, right? If you have a specific cost in mind (such that one of those 17% is 5 times as important as the majority class), then you could change a cost matrix. Otherwise, you could look at precision, recall, F1 score, and perhaps AUC(ROC).
Some references to get you started:

*

*Branco, P., Torgo, L., & Ribeiro, R. (2015). A survey of predictive modelling under imbalanced distributions. Retrieved from https://arxiv.org/abs/1505.01658.

*Longadge, R., Dongre, S., & Malik, L. (2013). Class imbalance problem in data mining: Review. Retrieved from https://arxiv.org/abs/1305.1707.

*Galar, M., Fernández, A., Barrenechea, E., Bustince, H., & Herrera, F. (2012). A review on ensembles for the class imbalance problem: Bagging-, boosting-, and hybrid-based approaches. IEE Transactions on Systems, Man, and Cybernatics—Part C: Applications and Reviews, 42(4), 463-484. Retrieved from http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.1903&rep=rep1&type=pdf

*Weiss, G. M., McCarthy, K., & Zabar, B. (2007). Cost-sensitive learning vs. sampling: Which is best for handling unbalanced classes with unequal error costs? DMIN, 7, 35-41. Retrieved from http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.9601&rep=rep1&type=pdf


text:
Q: How to convert a query into eloquent hi I write an query in query builder like below but want to convert it an eloquent
$courses = Course::
                ->join('course_reveiws', 'courses.id', '=', 'course_reveiws.course_id')
                ->join('users', 'courses.user_id', '=', 'users.id')
                ->select(DB::raw('avg(star) as average'))
                ->groupBy('course_reveiws.course_id')
                ->orderBy('star', 'desc')->where('courses.category_id',$id)
                ->get();

I need to get result like these using some relationship in eloquent but using above query builder I cannot achieve the below results. Where I have two method user and enrolls and I want to get it
{
      "id": 1,
      "category_id": 1,
      "subcategory_id": 3,
      "user_id": 2,
      "lang_id": 19,
      "title": "Laravel and Vue.js - Fullstack Web Development (2020)",
      "slug": "laravel-and-vuejs-fullstack-web-development-2020",
      "duration": "5H",

      "reveiw": 0,
      "special_commission": null,
      "total_enrolled": 21,
      "reveune": 6.86667,
      "thumbnail": "/uploads/courses/thumbnails/laravel-and-vuejs-fullstack-web-development-2020.png",
      "created_at": "2020-04-27 10:56:33",
      "updated_at": "2020-06-08 04:02:59",
      "enrolls_count": 4,
      "user": {
        "id": 2,
        "role_id": 2,
        "name": "instructor",
        "username": "instructor",
        "email": "instructor@lms.com",
        "email_verify": "1",

        "facebook": null,
        "currency_id": 2,
        "special_commission": 69,
        "payout": "PayTm",
        "payout_icon": "/uploads/payout/pay_4.png",
        "payout_email": "demo@paytm.com",
        "added_by": 0,
        "created_at": null,
        "updated_at": "2020-06-04 10:07:26"
      },
      "enrolls": [
        {
          "id": 7,
          "user_id": 3,
          "course_id": 1,
          "purchase_price": 10,
          "coupon": null,
          "discount_amount": 0,
          "reveune": 4,
          "status": 1,
          "created_at": "2019-04-10 07:16:01",
          "updated_at": "2020-05-10 07:16:01"
        },
      ]
    }