text:
Q: Subclassed QWebView doesn't react to Hyperlink Clicks This is in Python/PySide.
I am trying to create my own Parental WebBrowser by overloading the PySide.QtWebKit.QWebView widget. Then whenever someone clicks a link on the widget I check to see if we are going to an invalid website, if not we proceed, if yes then I redirect to a generic page.
So I have subclassed the PySide.QtWebKit.QWebView, but I am not receiving notification of when a link is clicked. I have overridden the linkClicked function but the function never runs when a link is clicked?
What am I doing wrong? Why cant my function run/react to the hyperlink click "event"? Do I need to override the webpage object & not this class to react to link clicks?
import PySide.QtWebKit
import sys
from PyQt4 import QtGui

class BrowserWindow( PySide.QtWebKit.QWebView ):
    # Class Variables:

    def __init__( self, _parent ):
        """ Constructor: """

        super(BrowserWindow, self).__init__()
        PySide.QtWebKit.QWebView(None)

    def linkClicked(self, arg__1):
        """ Post: """

        #print("LINK CLICKED")
        #text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
        #    'Enter your name:')

        self.load("http://yahoo.com")

def main():

    app = QtGui.QApplication(sys.argv)

    view = BrowserWindow(None) #PySide.QtWebKit.QWebView(None)
    view.load("http://google.com")
    view.show()

    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

A: There are several problems with the code you posted. Firstly, you are importing both PySide and PyQt4, which is not a good idea. Secondly, QWebView.linkClicked is a signal, not a protected method, so you can't override it. Thirdly, you are passing a string to QWebView.load, when you should be passing a QtCore.QUrl.
However, aside from those problems, you also need to set the linkDelegationPolicy on the web page in order to override its link handling.
Here's an edited version of your code which should fix all the problems:
from PySide import QtCore, QtGui, QtWebKit

class BrowserWindow(QtWebKit.QWebView):
    def __init__(self, parent=None):
        super(BrowserWindow, self).__init__()
        self.linkClicked.connect(self.handleLinkClicked)

    def handleLinkClicked(self, url):
        print(url.toString())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    view = BrowserWindow()
    view.load(QtCore.QUrl("http://google.com"))
    view.page().setLinkDelegationPolicy(
        QtWebKit.QWebPage.DelegateAllLinks)
    view.show()
    sys.exit(app.exec_())


text:
Q: Is eigenvector_centrality present in igraph 0.9.10? When looking for eigenvector_centrality in igraph 0.9.10 (the version I'm using) I couldn't find it:
https://igraph.org/python/api/0.9.10/
Then I've looked API reference for 0.9.8 and found it:
https://igraph.org/python/api/0.9.8/igraph._igraph.GraphBase.html#eigenvector_centrality
I'm trying to calculate Eigenvector centralities for some graphs and I'm getting the following message on Excel (using xlwings):
AttributeError: module 'igraph' has no attribute 'eigenvector_centrality'
Can anyone help me? Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel eloquent sort by role name on relationship model I'm stuck with a problem where I have to sort / order a collection of models by their relationship's data.
I've got it setup like this:
Models:
User, Team, TeamUser, Role
The TeamUser model is a pivot model / table (containing user_id and team_id.
If it's worth mentioning I am also using spatie/laravel-permissions for the roles.
How would I go forth when I  want to sort the users in a team by their role.name?
I'm talking about the users() relation in the Team model (see further down for code sample).
Some users have the role team-leader and most have the role team-seller. I've tried doing a ordinary ..->sortBy('role.name') but that doesn't seem to work. Thanks in advance if anyone could help me out.
User.php
/**
 * Team relation
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function team()
{
    return $this->belongsToMany('App\Team', 'team_users', 'user_id', 'team_id');
}

Team.php
/**
 * User relation
 *
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function users()
{
    return $this->belongsToMany('App\User', 'team_users', 'team_id', 'user_id')->withTimestamps();
}

A: if you want to order the result based on nested relation column, you must use a chain of joins:
$values = Team::query()
      ->leftJoin('users', 'users.team_id', '=', 'teams.id')
      ->leftJoin('model_has_roles', function ($join) {
          $join->on('model_has_roles.model_id', '=', 'users.id')
               ->where('model_has_roles.model_type', '=', 'app\Models\User');
      })
      ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.role_id')
      ->orderBy('roles.name')
      ->get();

i have tried it, it work just fine.
please note that if you want to order by multiple columns you could add 'orderBy' clause as much as you want:
->orderBy('roles.name', 'DESC')->orderby('teams.name', 'ASC') //... ext


text:
Q: Get XML content from XmlNodeList I have a question that may seem very simple, but it's giving me a headache. I have this XML file that has multiple entries, like:
    <books>
     <book>
      <id>1</id>
      <firstCover>
       <author name="**" age="**" />
       <title name="zz" font="yyy" size="uuu"/>
      </firstCover>
      <lastCover>
      </lastCover>
     </book>
     <book>
      <id>2</id>
      <firstCover>
       <author name="**" age="**" />
       <title name="zz" font="yyy" size="uuu"/>
      </firstCover>
      <lastCover>
      </lastCover>
     </book>
</books>

Now, in order to get the XML content for first cover of book with id=1, I do this:
XmlNodeList b = root.SelectNodes("/books/book[contains(id,1)]/firstCover");

Then I would really need to take the whole content of what's inside the firstCover for that book :
<author name="**" age="**" />
<title name="zz" font="yyy" size="uuu"/>

and insert it into an XmlElement. This is where I'm stucked. I know I can do it with a foreach loop in XmlNodeList, but is there a more simple way?

A: I'm guessing you want to actually insert it into an XMLElement in another XMLDocument.
Is this what you are looking for?
XmlDocument sourceDoc = new XmlDocument();
//This is loading the XML you present in your Question.
sourceDoc.LoadXml(xmlcopier.Properties.Resources.data);
XmlElement root = sourceDoc.DocumentElement;

XmlElement b = (XmlElement)root.SelectSingleNode("/books/book[contains(id,1)]/firstCover");

XmlDocument destDoc = new XmlDocument();
XmlElement destRoot = destDoc.CreateElement("base");
destDoc.AppendChild(destRoot);
XmlElement result = destDoc.CreateElement("firstCover");

result.InnerXml = b.InnerXml;
destRoot.AppendChild(result);

destDoc.Save("c:\\test.xml");


text:
Q: Nuxt project with vuetify2 throws error for deployment I have a nuxt project and migrated 1 month ago to vuetify 2.0 from vuetify 1.5. Everything has worked perfectly for development after yarn generate or yarn build. However, when I decided to publish the project, I got errors related to sass loader after yarn generate.
I tested nuxt project with vuetify 2 and got different errors about sass loader.
I wonder if there is any problem, how it worked in development, and what is exactly happening in build or generate command that the errors were thrown. What should I do to resolve the issue?
I think I found the origin of the error: In nuxt-config.ts, the file that I have in
styleResources: {
    scss: ['@/assets/sass/variables.scss']
  },

includes:
@import 'responsiveStyle';
$bg-color: white !important;
$primary-color: #1caefa !important;
$accent-color: #6c7293 !important;

I get this error: https://ibb.co/H7VvRVt
If I remove @import 'responsiveStyle, this error would raise:
https://ibb.co/KVQ08S9
This is a sample project including the error after yarn-generate command: https://github.com/nargesmomenyan/nuxt-vuetify2

A: Go to this link
and see what you have to do to successfully migrate from 1.5 to 2,
there has been a lot of changes already.
See here

A: The problem was related to the @nuxtjs/style-resources module according to this issue:
https://github.com/nuxt-community/vuetify-module/issues/82
I upgraded this module to version 1.0.0 and the error went away.


text:
Q: .NET WebAPI and http basic authentication I created a WEBAPI solution and I am creating the HTML pages to access all the functions of that web service. I am using http basic authentication.
I got these options

*

*Save the username and password in a Javascript vars and send them every time I call any of the WEBAPI functions.

*Send the username and password the first time, create a token on the server and send it back to the client, then save it as a cookie and use it every time I call any of the WEBAPI functions.

*Dont use HTTP basic authentication.

What is the best way to handle this?
Thanks

A: You don't want to send the username / password on every call for security reasons.Token based authentication would be the way to go and you can use the built in identity authentication for that.
The best tutorial I have found for that is http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

A: There's nothing wrong with using basic authentication as long as it is done over a secure channel.  If you send the username and password on every call, your api will need to access the database on every call just to authenticate the user.  If you send a token when the user is authenticated, then you remove the need to access the database on subsequent calls.
Using a token also allows you to take advantage of an identity provider such as Thinktecture's IdentityServer to provide single sign on.  If you have more than a few systems, it will allow users to log in one time and then access any of the applications and it can greatly simplify security.


text:
Q: jQuery Carousel Stuck (Twitter Bootstrap) I've implemented Twitter Bootstrap's Carousel jQuery plugin here:
http://zarin.me/circlefive/dashboard.html (see the responses tab)
The carousel usually functions, but occasionally gets stuck. It especially happens when you interact with the other tabs and then using the responses tab. I think it has to do with the tabs..
Does anyone know why the carousel is getting stuck?
Thanks!

A: The issue is along the lines of what @Francesco Frassinelli pointed out in the comment, namely that when the carousel is using CSS3 transitions (basically any browser but IE), if a carousel is hidden when a transition ends, the $.support.transition.end event is never fired.  This will cause the carousel to get suspended in the sliding state and short-circuit all it's functionality.
In Issue #1887 @fat threw in his suggestion for preventing it from getting stuck in the first place:

"You'll need to pause the slide show and resume it before/after toggling the display."

I also suggested a workaround for when using a carousel in a modal in Issue #3351, which could easily be adapted for your use case:
$('a[href="#responses-1"]').on('shown', function () {
    var $carousel = $('.carousel');

    if ($carousel.data('carousel') && $carousel.data('carousel').sliding) {
      $carousel.find('.active').trigger($.support.transition.end);
    }
});

This basically just unlocks the carousel when it becomes visible if it happens to be suspended.
Since this poor behavior occurs across many differently scenarios, I made a suggestion in Issue #3351 as to the feasibility of a potential permanent solution which could be integrated directly into the bootstrap-carousel.js plugin code. If anyone thinks that is a good idea, or have other ideas as to how to accomplish it, that issue is still open, so feedback is welcome.

A: If you inspect the behaviour of the carousel in chrome you can the carousel if still running when you change tab.
And because the carousel is not in the active tab a display: none; is applied to parent div of the carousel. This may be the cause of your problem. (you end up like the screenshot)
I think it can be fixed by triggering .carousel('pause') when clicking on the 3 first tab and .carousel('cycle') on the last tab before showing the content related to the tab.


text:
Q: co-compactness of fractional ideals associated to smooth projective geometrically connected curve over a finite field Let $X$ be a smooth projective, geometrically connected curve over $\mathbb{F}_q$, where $q = p^m$ is a prime power. Fix a closed point $\infty\in X$ and set $d_\infty = [\kappa(\infty):\mathbb{F}_q]$. Let $k = \mathbb{F}_q(X)$ be the function field over $\mathbb{F}_q$ and $A = \mathcal{O}_X(X-\{\infty\})$ be the section over the affine piece. Let $v_\infty$ be the normalized valuation at $\infty$ and $k_\infty$ the completion of $k$ w.r.t. $v_\infty$.
Prove that $k_\infty/I$ is compact, where $I\subseteq k$ is a non-trivial $A$-fractional ideal.
In David Goss' book, he says that the compactness of $k_\infty/I$ simply follows from Riemann-Roch theorem. I'm wondering how. I'm trying to look at the case $X = \mathbb{P}^1$ and $I = A$, then $A = \mathbb{F}_q[t]$, $k = \mathbb{F}_q(t)$ and $k_\infty = \mathbb{F}_q((t))$. So, $k_\infty/I \cong \frac{1}{t}\mathbb{F}_q[\![\frac{1}{t}]\!] $, which is clearly compact as a profinite group. This argument also extends to integral ideals $I\subseteq A$. But I'm wondering if it is related to Riemann-Roch. If so, how?


text:
Q: Style-Loader useable feature won't work in Webpack 2.x I'm using Webpack ^2.2.1 and the Style-Loader ^0.13.2.
The rule for .css files from my Webpack config looks like:
            {
                test:       /\.css$/,
                use: [
                    { loader: 'style-loader', options: { useable: true } },
                    { loader: 'css-loader' }
                ]
            }

Now when I asynchronously import (former require.ensure, System.import) a css file, you were receiving an object instead the raw css data, with methods attached to it: use() and unuse() (because, the useable option is set to true).
    import( './mod1.css' ).then( cssRaw => {
        setTimeout(() => {
            // let's assume an async use case
            cssRaw.use();
        },3000);
    });

However, this won't work any more for me (Uncaught TypeError: cssRaw.use is not a function).
In fact, the object that import (former System.import) provides here, does not own such methods.
Is there anything I'm doing wrong here or did anything change in Webpack 2.x?
This exact code worked properly beforehand.

As it was mentioned in the answers so far, passing over the loader-string as
{ loader: 'style-loader/useable' }

work just as expected. If that is the supposed way to go, I guess the "recommended configuration for style-loader in 2.x" is pretty wrong.

I submitted an issue on the Webpack github page which was accepted was fixed today (https://github.com/webpack-contrib/style-loader/pull/185/commits).

A: Change your loader configuration to the following:
{
    test: /\.css$/,
    use: [
        { loader: 'style-loader/useable' },
        { loader: 'css-loader' }
    ]
}

Useable seems to not be an option, but a loader in itself, available within the style-loader module directory.


text:
Q: can fstream objects be used inside a class? I have the following class definition... and I'm wondering about the fstream objects.
#ifndef CLIENTLIST_H
#define CLIENTLIST_H
#include <string>
#include <vector>
#include <fstream>
using namespace std;

class ClientList
{
private:
// A structure for the list
struct ListNode
    {
        char gender;
        string name;
        string phone;
        int numInterests; // The number of interests for the client
        vector<string> interests; // list of interests
        string match;
        struct ListNode *next;  // To point to the next node
    };

    ListNode *head;            // List head pointer
    string name;

    void detach(string); // to unmatch the corresponding client

public:
    // Constructor
    ClientList();

    // Destructor
    ~ClientList();

    // Linked list operations
    void appendNode(char, string, string, int, vector<string>, string, fstream &);
    string interestCompare(vector<string>, string, fstream &);
    void unmatch(string, ClientList, fstream &);
    void printMatch(fstream &);
    void printFree(fstream &);

};
#endif

This is about the fifth different way I've tried to use fstream objects in the class, but none of them worked, got all different kinds of errors.
Here is an example of a function of how I'm implementing most recently
//**************************************************
// appendNode appends a node containing the        *
// value pased into num, to the end of the list.   *
//**************************************************
void ClientList::appendNode(char gen, string nm, string ph, int numIntr,
                            vector<string> intr, string mch, fstream &dates)
{
    dates.open("dates.txt", ios::out | ios::out);
    ListNode *newNode;  // To point to a new node
    ListNode *nodePtr;  // To move through the list

    // Allocate a new node and store data in it.
    newNode = new ListNode;
    newNode->gender = gen;
    newNode->name = nm;
    newNode->phone = ph;
    newNode->numInterests = numIntr;
    newNode->interests = intr;
    newNode->match = mch;
    newNode->next = NULL;

    // If there are no nodes in the list
    // make newNode the first node.
    if (!head)
        head = newNode;
    // Otherwise, insert newNode at end.
    else
    {
        // Initialize nodePtr to head of list.
        nodePtr = head;

        // Find the last node in the list.
        while (nodePtr->next)
            nodePtr = nodePtr->next;

        // Insert newNode as the last node.
        nodePtr->next = newNode;
    }

    dates << "\nClient: " << newNode->gender << ", " << newNode->name << ", "
          << newNode->phone << ", " << newNode->numInterests << ", ";
    for (int index = 0; index < newNode->numInterests; index++)
        dates << newNode->interests[index] << ", ";
    dates << newNode->match << ".\n";

    cout << "\n\nAPPENDED\n\n";
    dates.close();
}

and this is an example of how I call it from main()
//append to file
    if (gender == tolower('m'))
    {

        match = Female.interestCompare(interests, name, dates); // compare the vector of interests to the client interests
        // in the female list

        Male.appendNode(gender, name, phone, numInterests, interests, match, dates);
    }

But like I said, this is just one of my attempts, and it seems that no matter how I try to get the class to open the file and write to it, the program crashes or does something that is not the postcondition.
So, I'm wondering if it is even possible to use file streams inside classes. And if so, what do I need to keep in my in order to do it.
NOTE: I'm not necessarily looking for a specific implementation, I'm more curious about the "why" behind the implementation. I would like to know what I need to keep in mind so I can, in the future, be able to know what I'm doing.

A: It should be possible.
Perhaps there's something wrong with the fstream you're passing in.  Double check 'dates'.
fstream inherits fail() from ios.  It can be used to check whether your fstream is OK.  You could use is_open() to check whether the file opened properly.
#include <assert.h>

// stuff...
fstream dates("dates.txt", fstream::in | fstream::out);
if (dates.is_open())
{
    cout << "dates.txt opened ok" << endl;
}
dates.close();

if (gender == tolower('m))
{
    assert(dates.fail() == false);

    match = Female.interestCompare(interests, name, dates);

    assert(dates.fail() == false);

    Male.appendNode(gender, name, phone, numInterests, interests, match, dates);
}

at least when it fails, you'll get a line number and can debug from there.
Also, I'm guessing you meant to change the second ios::out
ClientList::appendNode(...)
{
    //dates.open("dates.txt", ios::out | ios::out);
    dates.open("dates.txt", ios::in | ios::out | ios::app);
    ...
}


text:
Q: Loop invariant for pivot sort I'm trying to figure out if the algorithm is correct using loop invariants (Using the initialization, maintenance and termination method.) as well as getting the assertion and post-condition for it. I have something but I'm unsure if its the correct way of approaching it as there is uncertainty about the output of one of the values at any point in the algorithm (mid depends on if arr[sweep]

int partition(int arr[], int first, int last) {
    int mid = first;
    int pivot = arr[first];
     for (int sweep = first+1; sweep <= last; sweep++) {
        // Assertion: . . .
        if (arr[sweep] < pivot) {
            int tmp = arr[sweep];
            arr[sweep] = arr[mid+1];
            arr[mid+1] = tmp;
            mid++;
        }
    }
    // Post: . . .
     arr[first] = arr[mid];
     arr[mid] = pivot;
    return mid;
}

I've managed to come up with this:
I:
First=0
Last=Length-1
Mid=0
M:
At the start of the loop, where i is now i + 1
First=0
Last=Length-1
Sweep = first + 2
Mid= i + (first)= i (where i's value depends on if arr[sweep]

Sweep= Last+1
Mid = (last+1)+ (first) = (last + 1)+ (0 ) = Last + 1 (if all values were arr[sweep]

//Assertion: Before every loop mid= first + i where i is how many times arr[sweep]

//post-condition: arr[first..mid-1] will be less than arr[mid],
arr[mid+1...last] > arr[mid]. Sweep = last + 1.
I'm new to loop invariants, I hope i'm doing this correctly. Any advice would be immensely helpful. :)


text:
Q: C# - Office API returning 400 "69 {"error":{"code":"RequestBodyRead","message":"Cannot read the value '0' as a quoted JSON string value."}} 0 " I'm trying to send email using the Office 365 API, I can't use the Microsoft.Office365 packages for sending, as they don't currently support our authentication, but I do have a valid token to access the API, get requests work perfectly, but when I try to post to "https://outlook.office.com/api/v2.0/me/sendmail" I get the above error. While I can't use the send functions provided in Microsoft.Office365 I am using the message object to create my emails then serializing and posting.
public void SendMail(string Subject, string Body) {
    HttpClient client = new HttpClient();
    string accessToken = userCache.UserAccessToken;
    Uri uri = new Uri("https://outlook.office.com/api/v2.0/me/sendmail");
    client.DefaultRequestHeaders.Add("User-Agent", agent);
    client.DefaultRequestHeaders.Add("client-request-id", requestGuid);
    client.DefaultRequestHeaders.Add("return-client-request-id", "true");
    client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
    List<string> recipients = new List<string>();
    recipients.Add(userCache.Email);

    #region Create Email Message
    Message email = new Message();
    email.Body = new ItemBody();
    email.Body.Content = Body;
    email.Body.ContentType = 0;//0=text, 1=html
    email.From = new Recipient();
    email.From.EmailAddress = new EmailAddress();
    email.From.EmailAddress.Address = userCache.Email;//set from email to email of current logged in user

    email.Importance = Importance.Normal;
    email.Sender = email.From;
    email.Subject = Subject;
    email.ToRecipients = recipients;
    #endregion
    try {
        dynamic mailObject = new ExpandoObject();
        mailObject.Message = email;
        mailObject.SaveToSentItems = "true";
        HttpResponseMessage hrm = client.PostAsJsonAsync<Object>(uri, mailObject as ExpandoObject).Result;
    } catch (Exception e) { }
}

This submits the json below to the API:
{
    "Message": {
        "Subject": "Products",
        "Body": {
            "ContentType": 0,
            "Content": "Products"
        },
        "BodyPreview": null,
        "Importance": 0,
        "HasAttachments": null,
        "ParentFolderId": null,
        "From": {
            "EmailAddress": {
                "Name": null,
                "Address":"andrew.branoff@paretobiz.com"
            }
        },
        "Sender": {
            "EmailAddress": {
                "Name": null,
                "Address": "andrew.branoff@paretobiz.com"
            }
        },
        "ToRecipients": [
            {
                "EmailAddress": {
                    "Name": null,
                    "Address": "andrew.branoff@paretobiz.com"
                }
            }
        ],
        "CcRecipients": [],
        "BccRecipients": [],
        "ReplyTo": [],
        "ConversationId": null,
        "UniqueBody": null,
        "DateTimeReceived": null,
        "DateTimeSent": null,
        "IsDeliveryReceiptRequested": null,
        "IsReadReceiptRequested": null,
        "IsDraft": null,
        "IsRead": null,
        "WebLink": null,
        "Attachments": [],
        "ChangeKey": null,
        "Categories": [],
        "DateTimeCreated": null,
        "DateTimeLastModified": null,
        "Id": null
    },
    "SaveToSentItems": "true"
}

As far as I can tell this is what the API is looking for, since I used their own object to build it, but it seems to reject what I send no matter what I do. I have tried serializing first using
JsonConvert.SerializeObject(mailObject, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

to not send the null values, figuring it might not accept values, even null, for things it calculates like the body preview, but no change.

A: Most likely the specified error occurs since the provided JSON payload is invalid.
The issue is related with this line:
email.Body.ContentType = 0;//0=text, 1=html

ContentType property of Microsoft.OutlookServices.ItemBody accepts string values (not integer): Text or HTML, for example:
email.Body.ContentType = "Text";

A: The error indicates that you are sending an integer value 0 when the API expects a string value.  And in fact the documentation here shows that Message.Body.ContentType as well Message.Importance should be strings, e.g:
  "Body": {
    "ContentType": "Text",
    "Content": "Products"
  },

You are likely sending integer values for these properties because, in your c# classes, they are enums.  If you want to serialize enums as strings by name, you need to use StringEnumConverter.
You could set it directly on the property as an attribute, e.g.:
public class Body
{
    [JsonConverter(typeof(StringEnumConverter))]
    public ContentType ContentType { get; set; }

    public string Content { get; set; }
}

You could also configure HttpClient to use this converter for all enums as explained in this answer.

A: Thanks to the help given by the other answers, I found my solution, to modify the way Json.net serializes the object. I'm posting the exact solution to help anyone else with this issue later on.
var settings = new JsonSerializerSettings();
settings.Converters.Add(new StringEnumConverter());
settings.NullValueHandling = NullValueHandling.Ignore;
string json = JsonConvert.SerializeObject(emailObject, Newtonsoft.Json.Formatting.None, settings);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");


text:
Q: Slick carousel add separate captions from img alt tag I have a slick carousel where I'm trying to create separate captions from the img alt tags. However its not working and I'm not getting any errors.
I'd like to get the caption from the img alt tag of each and then wrap them in a separate div, which then changes as you go through the images within the carousel
Markup below:

jQuery(document).ready(() => {
   var helpers = {
        addZeros: function (n) {
            return (n < 10) ? '0' + n : '' + n;
        }
    };

    $('.carousel-module').each(function (index, sliderWrap) {
        var $sliderParent = $(this).parent();
        var $slider = $(sliderWrap).find('.carousel-gallery');
        var $caption = $('.carousel-caption');

        $slider.slick({
            dots: false,
            arrows: false,
            speed: 900,
            autoplay: true,
            autoplaySpeed: 4000,
            fade: true,
            cssEase: 'linear'
        });

        if ($(this).find('.item').length > 1) {
          $(this).siblings('.carousel-numbers').show();
        }

        $(this).on('afterChange', function(event, slick, currentSlide){
          $sliderParent.find('.carousel-numbers .active').html(helpers.addZeros(currentSlide + 1));

            var slideCaption = $('.carousel-gallery .slick-slide img').attr('alt');
            $(this).parent().parent().parent().append('
' + slideCaption + '
');
        });

        var sliderItemsNum = $(this).find('.slick-slide').not('.slick-cloned').length;
        $sliderParent.find('.carousel-numbers .total').html(helpers.addZeros(sliderItemsNum));
    });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css" rel="stylesheet"/>

        01 /

A: Here is clean code:

jQuery(document).ready(() => {
  const addZeroPad = (val) => val.toString().padStart(2, "0");

  $(".carousel-module").each(function() {
    const $module = $(this);
    const $slider = $module.find(".carousel-gallery");
    const $caption = $module.find(".carousel-caption");
    const $slides = $slider.find(".carousel__item");
    const $numbersElem = $module.find(".carousel-numbers");
    const $totalNumElem = $module.find(".carousel-numbers .total");
    const $activeNumElem = $module.find(".carousel-numbers .active");

    const changeCaption = (value) =>
      $caption.html('
' + value + "
");

    if ($slides.length) {
      $slider.on("init", function(event, slick) {
        console.log(slick.$slides.length);
        $totalNumElem.text(addZeroPad(slick.$slides.length));
        $numbersElem.show();
        const slideCaption = $(slick.$slides.get(0)).find("img").attr("alt");
        changeCaption(slideCaption);
      });

      $slider.on("afterChange", function(event, slick, currentSlide) {
        $activeNumElem.text(addZeroPad(currentSlide + 1));
        const slideCaption = $(slick.$slides.get(currentSlide))
          .find("img")
          .attr("alt");
        changeCaption(slideCaption);
      });

      $slider.slick({
        dots: true,
        arrows: true,
        autoplay: true,
      });
    }
  });
});
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Document</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
  <link href="https://fonts.googleapis.com/css2?family=Jost:wght@400;600;700&display=swap" rel="stylesheet" />
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap-grid.min.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css" rel="stylesheet" />
  <link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css" rel="stylesheet" />

01 /

A: For start, I made your carousel work here in a snippet. I can get the current slide using the .slick-active class (although there are other ways). Then I get the attribute alt and update the .caption element.

jQuery(document).ready(() => {
  var helpers = {
    addZeros: function(n) {
      return (n < 10) ? '0' + n : '' + n;
    }
  };

  $('.carousel-module').each(function(index, sliderWrap) {
    var $sliderParent = $(this).parent();
    var $slider = $(sliderWrap).find('.carousel-gallery');
    var $caption = $('.carousel-caption');

    $slider.slick({
      speed: 900,
      autoplay: true,
      autoplaySpeed: 4000,
      fade: false,
      cssEase: 'linear'
    });

    if ($(this).find('.item').length > 1) {
      $(this).siblings('.carousel-numbers').show();
    }

    $(this).on('afterChange', function(event, slick, currentSlide) {
      $sliderParent.find('.carousel-numbers .active').html(helpers.addZeros(currentSlide + 1));
      var slideCaption = $('.carousel-gallery .slick-slide.slick-active img').attr('alt');
      $(this).closest(".carousel-module").find('.carousel-caption').text(slideCaption);
    });

    var sliderItemsNum = $(this).find('.slick-slide').not('.slick-cloned').length;
    $sliderParent.find('.carousel-numbers .total').html(helpers.addZeros(sliderItemsNum));

  });
});
.carousel-module {
  width: 200px;
  margin: 20px;
}

img {
  width: 100%
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.css" integrity="sha512-wR4oNhLBHf7smjy0K4oqzdWumd+r5/+6QO/vDda76MW5iug4PT7v86FoEkySIJft3XA0Ae6axhIvHrqwm793Nw==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

      01 /

      Hello world


text:
Q: Reactive array is empty I'm using Meteor CollectionFS to upload files. I'm using ephmer:reactive-array to store the file IDs after they're stored in the collection. The following is the code:
Template.myFileHandler.created = function () {
    this.fileIds = new ReactiveArray();
}

I upload the files as specified in the CollectionFS documentation:
Template.myFileHandler.events = function () {
    'submit #myFileForm': function (event, template) {
        for(var i = 0; i < fileList.length; i++) {
            var fsFile = FS.File(fileList[i]);
            UserDocuments.insert(file, function (err, fileObj) {
                Template.instance().fileIds.push(fileObj._id);
            });
        }
        console.log(Template.instance().fileIds.get().length)
    }
}

When I do the console.log, I'm getting the length: 0. How do I store the IDs in the reactive array?

A: You are just passing a callback in your insert function. But the callback is asynchrous, and will only execute after the insert is done.
So your code is still working. Try putting your console.log in your callback like that :
Template.myFileHandler.events = function () {
    'submit #myFileForm': function (event, template) {
        for(var i = 0; i < fileList.length; i++) {
            var fsFile = FS.File(fileList[i]);
            UserDocuments.insert(file, function (err, fileObj) {
                Template.instance().fileIds.push(fileObj._id);
                console.log(Template.instance().fileIds.get().length); // Here it will show 1
            });
        }
        console.log(Template.instance().fileIds.get().length); // Here, the insert hasn't happened yet
    }
}


text:
Q: Div Contents on one line? How do I get the contents of my DIV to all stay on one line?
I've seen other posts, but I can figure out what I'm doing wrong?
here is a link to the page with an issue:
http://www.heatx.org/productcart/pc/viewCategories.asp?idCategory=2

A: I believe the issue is due to the images inside the div. Set display:inline to those images.

A: Given your link start by adding float: left; to #pcIconBarRight img and #pcIconBar a. This should address your question.
EDIT:
Then change this:

And this:

EDIT2:
To display two divs in one row you could do this:

Total:

159 USD

Note: the width: 200px; you should set the width big enough for the inner div's to fit, otherwise it will break the second div to the next line.

A: Please add this into your bottom of css file
table{
margin: 0 auto;
}

to align your site in center
your menu is not appeared !

A: A little bit late for answering OP's question. This will be useful for other people having the same problem.
So to get all the elements to appear on a single line the easiest way is:

*

*Set white-space: nowrap;overflow-x: auto; on the parent element.

*Set display: inline-block  on all child elements.

Result:

Fiddle

   Some label
  <select style="display: inline-block">
    <option value="0">aaaaa</option>
    <option value="1">bbbbbb</option>
    <option value="2">ccccccccc</option>
  </select>
  Another label:
  <input type="text" style="display: inline-block;width:200px;" />
  NOTE: some other text


text:
Q: Help me Verifying that the equation is integrable and finding its solution How can I verify that the equation is integrable and that find its solution;
$$2y(a-x)dx+[z-y^2+(a-x)^2]dy-ydz=0$$
Honestly, I tried too much, but I got too strange results,thus I couldnt show my efforts here so sorry. Thank you for helping.

A: Hint:
1-Verify that
$$
curl \left(2y(a-x),\,z-y^2+(a-x)^2,\,-y\right)=(0,0,0)
$$
Actually, it is not true. May be there is a typo. I believe the second component of the vector field is $-[z-y^2+(a-x)^2]$.
2- Find the potential of the vector field $\left(2y(a-x),\,-[z-y^2+(a-x)^2],\,-y\right)$.
edit:
You need a function $f$ such that $\nabla f(x,y,z)=\left(2y(a-x),\,-[z-y^2+(a-x)^2],\,-y\right)$. Then
$$
f(x,y,z)=\int 2y(a-x)\,dx+C(y,z)=-y(a-x)^2+C(y,z)
$$
If we derive in $y$
$$
-[z-y^2+(a-x)^2]= f_y(x,y,z)=-(a-x)^2+C_y(y,z)
$$
then
$$
C(y,z)=-zy+\frac{y^3}{3}+B(z)
$$
and
$$
f(x,y,z)=-y(a-x)^2-zy+\frac{y^3}{3}+B(z)
$$
Now, if we derive in $z$:
$$
-y=f_z(x,y,z)=-y+B'(z)
$$
Then...


text:
Q: jQuery blur event not working why blur event in the below code is not working and the alert box pop-ups as soon as the document is ready and not wait for blur event. give me suggestion to fix it... Thanks...

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("[type=text]").blur(cc("[type=text]"));
    $("[type=email]").blur(cc("[type=email]"));
    function cc(s){
        alert("Value: " + $(s).val());
    }
});
</script>
</head>
<body>
<input type="text" id="test" value="rev"><br>
<input type="email" id="test" value="mail@example.org">
</body>
</html>

A: blur() function take function as a parameter. In your code you pas result of cc function execution.
You should use anonymous functions:
$(document).ready(function(){
    $("[type=text]").blur(function() { cc("[type=text]"); });
    $("[type=email]").blur(function() { cc("[type=email]"); });
    function cc(s){
        alert("Value: " + $(s).val());
    }
});


text:
Q: How do you set the V value of HSV mat in Opencv Java? I want to remove the shadows from the input image. Based from what I found, I need to set the V value of HSV to 200. But this code is not working for me in opencv android studio. Please help me understand what I'm doing wrong here.
 public Mat fixIntensity(Mat inputImage) {
        Mat hsvImg;
        Imgproc.cvtColor(inputImage, hsvImg, Imgproc.COLOR_RGB2HSV);
        Mat channel[3];

        Core.split(hsvImg, channel);
        channel[2] = Mat(hsvImg.rows, hsvImg.cols, CV_8UC1, 200);//Set V
        //Merge channels
        Core.merge(channel, 3, hsvImg);
        Mat rgbImg;
        Imgproc.cvtColor(hsvImg, rgbImg, CV_HSV2BGR);

        return rgbImg;
}


text:
Q: Assignment to part of a multi-dimentional array in VHDL I want to change some of the elements in an array, but can figure out how to do it.
This line: sig3(1) <= (11, 12); gives me an error
entity t1 is
end entity;

architecture testbench of t1 is

    type type3 is array(1 to 2, 1 to 2) of integer;

    signal sig3 : type3;

begin
    process is
    begin
        -- sig3 <= ((11, 12), (13, 14));  -- this works
        sig3(1) <= (11, 12);   -- get error:  "Incompatible types for assignment."
        wait;
    end process;
end architecture;

A: The way you have defined the array unfortunately precludes the method you favour of assigning:
If you decalre a type like this:
type type3 is array(1 to 2, 1 to 2) of integer;
signal sig3 : type3;

Assignments have to fully specify the index:
sig3(1,1) <= 11;
sig3(1,2) <= 12;

You can define a 2d array as a array of 1-d arrays though
type type4 is array(1 to 2) of integer;
type type5 is array(1 to 2) of type4;
signal sig5 : type5;

You can now assign it like this:
sig5(1) <= (11,12);

Unfortunately, you can't work so easily in the other dimension.


text:
Q: CRM 2015 read "dirty" value from unsaved form I'm creating new account record. The easiest way is to fill account id (vat number or something similar) and push button. Button run some javascript. Javascript read value of account id and fill the rest (call some external ws and fill account name, address and so on).
But I need to read this unsaved account id. Standard
Xrm.Page.getAttribute("accId").getValue();

can read only saved values.
Via debugger I found the right value, so I wrote simple function, which returns it.
Here it is:
function getDirtyValue(attName) {
    var control = Xrm.Page.ui.controls.get(attlName);

    if (control != null && control.$1G_1 != null) {
        return control.$1G_1.$3V_0;
    }
    else {
        return null;
    }
}

It works but is there some official way to get this value?
(language correction welcome)

A: You could avoid this trick by adding a function, called when the form loads, and sets the value of the field into a global variable. You can access that variable in the on change event of that field.
Keep in mind that Microsoft does not support methods that are not present in the SDK and they might change. So if they change the property you are using, and your code is already in production, you'll end up having some problems.
Hope it helps,
Cheers


text:
Q: Upload R package to local repository Is there any R method or function for uploading a personal R package to CRAN local repository?
I think if you move your tar.gz, or your compiled code (windows) to appropiate directory /bin/windows or /src/contrib it would work.
But, is there any function already done for that? Any "upload" function? I have read CRAN doc and google but I have not found a solution.
If I go to IP_LOCAL_REPO:PORT and click on "web form" for submitting packages, these packages are uploaded to my local?
Thanks!


text:
Q: Proof that something is undefined? How can one tell the difference when the result is undefined or math just doesn't know how to provide a value for that particular equation? (the value still exists however)
For example, how could one prove that by definition division by zero is undefined; it's not that math doesnt' know the value, the value just doesn't exist.

A: Whether something is defined or not is a matter of, well, definition. Division by zero is undefined because we explicitly exclude it from the definition of division. The reasons we exclude it from the definition are varied, of course, but it's not a matter of lack of knowledge.
It is not quite clear what you mean by "provide a value"; there are numbers which we can prove cannot be explicitly described in terms of a terminating algorithm (that is, there is no Turing Machine that will produce the number). But does that mean we do not provide a value?
We cannot write down exactly a number that solves the equation $x^2-2=0$. We cheat when we say the solutions are $\sqrt{2}$ and $-\sqrt{2}$ because... what does "$\sqrt{2}$" mean? It means "the positive real number that is a solution to $x^2-2=0$". Does that mean we "don't know how to provide a value"?
On the other hand, there are equations which we may genuinely not know whether they have solutions of a special kind or not.  For a long time, it was unknown whether there were any positive integers $a$, $b$, and $c$, and a positive integer $n\gt 2$, such that $a^n+b^n=c^n$. Now we know there are none.

A: We don't "prove" that such statements are undefined, we "choose" not to define them, because we believe that in some contexts it doesn't make sense to do so. For instance, over the real numbers, we choose not to divide by zero because there is no explicit interest in doing so. But over the complex numbers, it makes great sense to say that $1/0 = \infty$, and in some contexts it is very important to understand what it means.
For instance, over real numbers, if we would try to define $1/0$ by continuity, we would suggest $1/0 = \lim_{x \to 0} \frac 1x$, but this limit doesn't exist. However, if we take the same definition over $\overline{\mathbb C}$, it works! The limit exists and is worth $\infty$ in the compactification of the complex plane. We don't prove that something is undefined, we just don't define it when we don't want to. That's the big idea.
Hope that helps,

A: In the real numbers we can prove that division by zero is not only undefined but cannot be defined at all. Why? Because we would like the real numbers to have certain properties which are not consistent with the idea of division by zero.
We do can prove the "undefinability" by showing that if division by zero were possible to define we could derive a contradiction (e.g. $1=2$), and contradictions are bad. So we avoid things which prove contradictions.
To see that indeed this is the case suppose that $\frac10$ was defined, then $0\times\frac10=0$ since everything times zero is zero; on the other hand $\frac10\times0=1$ because we multiply a number by its inverse. Therefore $0=1$... contradiction!

On the other hand, we can prove that a continuous function $f$ which satisfies: $$\lim_{x\to\infty} f(x)=\infty,\text{ and }\lim_{x\to-\infty}f(x)=-\infty$$
Has at least one root, that is there exists some $c\in\mathbb R$ such that $f(c)=0$. Even though we don't know what $f$ is or how to find this $c$.
Why can we prove that? If we assume that this is not the case then we can once again derive contradiction in one form or another.


text:
Q: How to properly construct a long command line with a mix of single and double quotes? I've got a long list of commands strung together (aws cli, jq, cut, sed) that works for me with which I'm trying to now run within a bash script. I'm having problems with the single and double quotes.
If I ran this manually it would be the following:
aws \
  --profile app-prod \
  --region us-east-1 ec2 describe-instances \
  --filter 'Name=tag:ChefRole,Values=foo_bar' \
           'Name=instance-state-name,Values=running' \
| jq -r '.Reservations[].Instances[] | [.InstanceId, .Tags[].Value] | @csv' \
| cut -d ',' -f1 \
| sort > sort.out;sed 's/"//g' sort.out

In my script I'm trying to pass in parameters the region and Values
I've tried this:
awsCLI(){
    cmd=$(aws --profile app-prod --region ${region} ec2 describe-instances --filter 'Name=tag:ChefRole,Values='${component}'| jq -r '.Reservations[].Instances[] | [.InstanceId, .Tags[].Value] | @csv' | cut -d ',' -f1 | sort > "${_sorted}";sed 's/"//g' "${_sorted}")
}

Placing in the variable - cmd=$(commands here) has worked for me before in other scripts, but not this time.
I also tried just running as is:
aws --profile app-prod --region ${region} ec2 describe-instances --filter 'Name=tag:ChefRole,Values='${component}'| jq -r '.Reservations[].Instances[] | [.InstanceId, .Tags[].Value] | @csv' | cut -d ',' -f1 | sort > "${_sorted}";sed 's/"//g' ${_sorted}"

Either of these didn't work for me. Please advise on best practice for this. Should I break this out? How would you build this long command?
Thanks you.
(Editor's note: first code block split by \ and indented; A.T.)

A: I was actually trying to eliminate the eternally long horizontal scroll bars from your question, but then decided to convert it into an answer, maybe it actually solves your problem (if not, just tell, will delete):
awsCLI(){
  cmd=$(aws \
    --profile tealium-prod \
    --region "${region}" ec2 describe-instances \
    --filter 'Name=tag:ChefRole,Values='"${component}" \
  | jq -r '.Reservations[].Instances[] | [.InstanceId, .Tags[].Value] | @csv' \
  | cut -d ',' -f1 \
  | sort > "${_sorted}" \
  ; sed 's/"//g' "${_sorted}" \
  )
}

I think the main problem was superfluous single tick around Values='"${component}". In general you can concatenate strings by juxtaposition, all you have to remember is that "" expand the variables, whereas '' do not.
The root cause was non-existent indentation. Look up what the backslash in the end of the line does, it will make your life much easier.

A: If you have the ability to use Python, the boto3 library is very easy to use. The issue with multiple types of quotation marks becomes moot.


text:
Q: How to force TeamCity to only work on signed commits in GitLab Currently, we are using GitLab Enterprise Edition 9.5.1 and TeamCity Professional 2017.1.2 (build 46812). The build agent has a line like
git pull --verify-signature
Our group would like to have TeamCity verify gpg signature without having an explicit pull command.
How do you configure TeamCity to do this?

A: Absent input from the community, here is the first working kludge.
First build step
The first lines in the first TeamCity build step are:
git verify-commit HEAD~0

export VERIFY_EXIT_CODE=$?

if [ "$VERIFY_EXIT_CODE" -eq "0" ]
then
  echo "Git commit GPG signature is VERIFIED"
else
  echo "Git commit GPG signature is NOT VERIFIED"
  build stop
fi

GPG signature verified
When the commit has a verified GPG signature, the output resembles this:
[12:17:54] Step 1/3: Verify GPG signature on commit (Command Line)
[12:17:54][Step 1/3] Starting: /home/*******/Applications/TeamCity/buildAgent_***_1/temp/agentTmp/custom_script5468853061762530637
[12:17:54][Step 1/3] in directory: /home/*******/Applications/TeamCity/buildAgent_***_1/work/c8edabae02b7df61
[12:17:54][Step 1/3]
[12:17:54][Step 1/3] git verify-commit HEAD~0
[12:17:54][Step 1/3] gpg: Signature made Tue 05 Sep 2017 12:15:59 PM MDT using RSA key ID 71F1FCB8
[12:17:54][Step 1/3] gpg: Good signature from "My Name (*** gpg key) <******@*****.***>"
[12:17:54][Step 1/3]
[12:17:54][Step 1/3] export VERIFY_EXIT_CODE=$?=0
[12:17:54][Step 1/3] Git commit GPG signature is VERIFIED
[12:17:54][Step 1/3] Process exited with code 0

GPG signature unverified
When the commit has no verified GPG signature, or TeamCity can't find the public key, the output looks like this:
[12:10:37] Step 1/3: Verify gpg signature on git repository (Command Line)
[12:10:37][Step 1/3] Starting: /home/*******/Applications/TeamCity/buildAgent_***_1/temp/agentTmp/custom_script4984466249864504039
[12:10:37][Step 1/3] in directory: /home/*******/Applications/TeamCity/buildAgent_***_1/work/c8edabae02b7df61

[12:10:37][Step 1/3] git verify-commit HEAD~0
[12:10:37][Step 1/3] Git repository is NOT VERIFIED
[12:10:37][Step 1/3]
[12:10:37][Step 1/3] export VERIFY_EXIT_CODE=$?=1
[12:10:37][Step 1/3] Git repository is NOT VERIFIED
[12:10:37][Step 1/3]
[12:10:37][Step 1/3] build stop
[12:10:37][Step 1/3] /home/*******/Applications/TeamCity/buildAgent_***_1/temp/agentTmp/custom_script4984466249864504039: line 19: build: command not found
[12:10:37][Step 1/3] Process exited with code 127
[12:10:37][Step 1/3] Process exited with code 127
[12:10:37][Step 1/3] Step Verify gpg signature on git repository (Command Line) failed
[12:10:37][Step 1/3] Error message is logged


text:
Q: TypeError: .push is undefined I have created a redux datastore where I want to basically store the index of pets which where liked by a user or disliked by a user. I am facing an issue where I am getting error where TypeError: .push is undefined. I am following a  basic redux tutorial mentioned here, https://www.youtube.com/watch?v=KcC8KZ_Ga2M
I am confused by the fact that I array is first defined and then undefined as I push integer in the array.
ProfileApp.js
class ProfileApp extends React.Component {
  constructor(props) {
    super(props)
   .........(Truncated for brevity)
   .........(Truncated for brevity)
   }
   componentWillMount() {

   .........(Truncated for brevity)
   this.props.likePets(this.state.currentIndex);
   .........(Truncated for brevity)
   this.props.dislikePets(this.state.currentIndex);

   }
   function mapStateToProps(state){
     return {
       likedPets: state.likedPets,
       dislikedPets: state.dislikedPets
     }
   }
   function mapDispatchToProps(dispatch){
     return{
       likePets: (i)=> dispatch({type:'LIKE_PETS'}),
       dislikePets: (i)=> dispatch({type:'DISLIKE_PETS'})
     }

   }
   export default connect(mapStateToProps)(ProfileApp)

App.js
import  ProfileApp  from './src/ProfileApp';
import {Provider} from 'react-redux';/
const initialState = {
  likedPets: [],
  dislikedPets: []

}
const reducer = (state = initialState, action) =>{

console.log(state.likedPets)
console.log(state.dislikedPets)

  switch (action.type){

    case 'LIKE_PETS':
    return{likedPets: likedPets.push(action.index)}
    case 'DISLIKE_PETS':
    return{dislikedPets:dislikedPets.push(action.index)}
  }
  return state

}

const store = createStore(reducer);
export default class App extends React.Component {

  render() {
    return (
    <Provider store = {store}>
      <ProfileApp></ProfileApp>
    </Provider>

    )
  }
}

output when I first compile this code on console is as follows:
during initial load:
Array []
Array []
Running application "main" with appParams:.....(Trimed)

Useraction: Like a pet
Array []
Array []

Useraction: like  other pet
1
undefined

A: You need to pass in your mapDispatchToProps in connect:
export default connect(mapStateToProps)(ProfileApp)

to
export default connect(mapStateToProps, mapDispatchToProps)(ProfileApp)

You need to spread your state in the reducer:
return{likedPets: likedPets.push(action.index)}

to
return{...state, likedPets: likedPets.push(action.index)}

otherwise you are overwriting the state in the store with an object that doesn't have your dislikedPets on it.
Also the push method of arrays returns the length of the array. Replace that with
likedPets: [...state.likedPets,action.index]

To get an array that is the current state (likedPets) with action.index added onto it.


text:
Q: How to determine which WFS server software is being used? I want to display WFS data from the following OGC compliant service:
http://gis.arso.gov.si/wfs?STORE=ARSOGIS
I haven't been successful yet, so now I'm wondering which WFS server software is being used by arso.gov.si.
How can I find out what's running on their servers?

A: Having poked around further it looks like a home brew system for example the class throwing the (spurious) error when you use service = wfs instead of WFS is si.bron.GISRepSystem.WFSExportServlet.WFSRequest.WFSRequestImpl isGetCapabilitiesGET
Combining the inability to handle case in the request with the completely wrong SRS listed in the capabilities file it looks like a badly implemented home brew WFS which would explain why you can't connect to it.
I'd suggest contacting the owner but they skipped that part of the capabilities response.

A: Linux  Apache/2.2.9 (Debian) mod_ssl/2.2.9 OpenSSL/0.9.8g 24-Oct-2010 IP 193.2.208.18    Agencija Republike Slovenije za okolje (ARSO)
see:
http://uptime.netcraft.com/up/graph?site=http://gis.arso.gov.si/

A: Looks like a ArcServer based on it's inability to answer a simple request with out an error :-)
But it really shouldn't matter as WFS is a standard designed to hide implementation details.

A: According to the HTTP response, they are running Oracle Application Server:
Server: Oracle-Application-Server-10g/10.1.2.0.2 Oracle-HTTP-Server OracleAS-Web-Cache-10g/10.1.2.0.2 (N;ecid=3264503745971,0)
My guess would be Oracle Spatial or GeoServer.


text:
Q: Multiple condition on same column inside Linq where How can I write a linq query to match two condition on same column in the table?
Here one person can be assigned to multiple types of works and it is store in PersonWorkTypes table containing the details of persons and their worktypes.
So I need to get the list of persons who have both fulltime and freelance works.
I have tried
people.where(w => w.worktype == "freelance" && w.worktype == "fulltime")

But it returns an empty result.

A: You can try this
public class Person {
    public string Name {get;set;}
    public List<PersonWorkType> PersonWorkTypes {get;set;}
}

public class PersonWorkType {
    public string Type {get;set;}
}

public static void Main()
{
    var people = new List<Person>();
    var person = new Person { Name = "Toño", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" } } };
    var person2 = new Person { Name = "Aldo", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };
    var person3 = new Person { Name = "John", PersonWorkTypes = new List<PersonWorkType>() { new PersonWorkType { Type = "freelance" }, new PersonWorkType { Type = "fulltime" } } };

    people.Add(person);
    people.Add(person2);
    people.Add(person3);

    var filter = people.Where(p => p.PersonWorkTypes.Any(t => t.Type == "freelance") && p.PersonWorkTypes.Any(t => t.Type == "fulltime"));

    foreach(var item in filter) {
        Console.WriteLine(item.Name);
    }
}

This returns person that contains both types in PersonWorkTypes

A: w.worktype=="freelance"
w.worktype=="fulltime"

These are mutually exclusive to each other, and therefore cannot both be true to ever satisfy your AND(&&) operator.
I am inferring that you have two (or more) different rows in your table per person, one for each type of work they do. If so, the Where() method is going to check your list line-by-line individually and won't be able to check two different elements of a list to see if Alice (for example) both has en entry for "freelance" and an entry for "fulltime" as two different elements in the list. Unfortuantely, I can't think of an easy way to do this in a single query, but something like this might work:
var fulltimeWorkers = people.Where(w=>w.worktype=="fulltime");
var freelanceWorkers = people.Where(w=>w.worktype=="freelance");
List<Person> peopleWhoDoBoth = new List<Person>();
foreach (var worker in fulltimeWorkers)
{
   if (freelanceWorkers.Contains(worker)
      peopleWhoDoBoth.Add(worker);
}

This is probably not the most efficient way possible of doing it, but for small data sets, it shouldn't matter.

A: AS already said, && operator means, that BOTH conditions has to be met. So in your condition it means that you want worktype type to by freelanceand fulltime at the same time, which is not possible :)
Most probably you want employees that have work type freelance OR fulltime, thus your condition should be:
people.Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")

Or, if person can be set more than once in this table, then you could do:
people
  .Where(w=>w.worktype=="freelance" || w.worktype =="fulltime")
  // here I assume that you have name of a person,
  // Basically, here I group by person
  .GroupBy(p => p.Name)
  // Here we check if any person has two entries,
  // but you have to be careful here, as if person has two entries
  // with worktype freelance or two entries with fulltime, it
  // will pass condition as well.
  .Where(grp => grp.Count() == 2)
  .Select(grp => grp.FirstOrDefault());


text:
Q: How to unarchive a interaction microsite In Salesforce Marketing Cloud, does anyone know how to remove the archive setting on a Microsite interaction? I had previously selected to archive it, but now need to make the site visible to consumers again. Is there anyone that knows how best to accomplish this?

A: I believe only way is to contact global support. Even then I am not positive they can remove it. You likely will need to create a new interaction though - https://help.exacttarget.com/en-US/documentation/exacttarget/content/microsites/


text:
Q: WCF response: Omit SOAP Structure I developed a perfectly working .NET WCF web service that produces a SOAP response.
My problem is the SOAP format of the response, cause my final customer is not able to use my web service. (He expects just the body content of the response.)
In order to explain better the situation, I have recreated a WCF demo called "Calculator"; a simple web service which performs the Sum of two numbers. (1+1)
When I test the web service on SOAP UI, I have the following response:
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <s:Header>
      <o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <u:Timestamp u:Id="_0">
            <u:Created>2015-03-30T14:31:44.759Z</u:Created>
            <u:Expires>2015-03-30T14:36:44.759Z</u:Expires>
         </u:Timestamp>
      </o:Security>
   </s:Header>
   <s:Body>
      <SumResponse xmlns="http://MY-PC">
         <SumResult>2</SumResult>
      </SumResponse>
   </s:Body>
</s:Envelope>

While, my final customer wants to receive the following response: (all through a new wsdl)
<?xml version="1.0" encoding="UTF-8"?>
<SumResponse xmlns="http://MY-PC">
    <SumResult>2</SumResult>
</SumResponse>

Is there any way to omit the SOAP format in the response of the WCF web service ? (possibly using .NET standard system libraries)
If there isn't, there is any way to achieve the final result remaining in .NET ?
Note:
I should use the .NET framework 4.0, and the response should have:
content type 'text/xml; charset=utf-8' (like SOAP 1.1 format)

A: You can try to use the message dispatcher, however i am not sure you would want to do this, If you create an interface your client could easily get the full answer but get back an object with just the values.
Anyway, with the message inspector you can edit the message you are about to send, here is an example:
//First you will need to implement 2 interfaces
//IDispatchMessageInspector or IClientMessageInspector and IServiceBehavior or IEndpointBehavior

public class MustUnderstandMessageInspector : IDispatchMessageInspector
{

    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        //Here you can use the ref request(Remember it is a ref, careful what you do with it)
        //request is the message you just received
        SaveInDatabase(request);
        return null;
    }

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
        //reply is a ref like request and it is the message you are sending
        throw new NotImplementedException();
    }
}

// To be able to implement your MessageInspector in your service you need to create a behavior.
//this behavior will have to be added to your server.

public class UnderstandBehavior : IServiceBehavior
{

    void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
    {
        //throw new NotImplementedException();
    }

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        //This will Add your inspector to every dispatcher inside serviceHostBase
        //you will have to use the one your service is on
        foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
        {
            foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
            {
                epDisp.DispatchRuntime.MessageInspectors.Add(new MustUnderstandMessageInspector());
            }
        }
    }

    void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
        //throw new NotImplementedException();
    }
}

Once you have both interfaces done you will have to add the behavior to your service.
{
        svcHost = new ServiceHost(typeof(Service), eventendpoint);
        svcHost.AddServiceEndpoint(typeof(IService), new WSHttpBinding, "Endpoint");
        //Add Service Behavior
        UnderstandBehavior behavior = new UnderstandBehavior();
        svcHost.Description.Behaviors.Add(behavior);
        //////
        svcHost.Open();
        textBox1.Text = textBox1.Text + "\n\nService is Running";
        svcHost.Close();
}

As shown you can also edit incoming messages you just have to use the message inspector you want.


text:
Q: How to test build.sbt code? I've got a moderately simple but slightly tricky sbt setup code I want write a few tests for. I would, however, like it to stay in build.sbt.
For the time being I've moved it to an object (in project/), referenced it in the build.sbt as well as in the tests in project/src/test/scala.
But is it possible for code in build.sbt to be tested?

A: According to the advice in the SBT docs:

The recommended approach is to define most configuration in .sbt files, using .scala files for task implementations or to share values, such as keys, across .sbt files.

So since this sounds like testable code, and not static configuration, your best bet is to leave it in a Scala file.
I'm sure there's a way to manually evaluate the SBT DSL if you really, really want to, but you'll probably have to dig deep into the docs or the SBT source. I can't help you there, though.


text:
Q: Kohana 3.3.2 Controller in subfolder I'm starting with Kohana and i don't understand why i have this error ...
 Kohana_HTTP_Exception [ 404 ]: The requested URL api/v1/welcome was not found on this server.

 SYSPATH/classes/Kohana/Request/Client/Internal.php [ 89 ]

 if ( ! class_exists($prefix.$controller))
 {
    throw HTTP_Exception::factory(404,
    'The requested URL :uri was not found on this server.',
    array(':uri' => $request->uri())
    )->request($request);
 }

 // Load the controller using reflection
 $class = new ReflectionClass($prefix.$controller);

My .htaccess
# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

My Route
Route::set('api','api/v1(/<controller>(/<id>)(/<custom>))'
)->defaults(
    array(
        'directory' =>'api/v1',
        'controller' => 'welcome',
        'id'         => FALSE,
        'action'     => 'index',
    )
);

My Controller: Controller/api/v1/Welcome.php
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Api_v1_Welcome extends Controller {

    public function action_index()
    {
        $this->response->body('hello, world!');
    }
} // End Welcome

Am i missing something ??? Why the class_exist on my controller class return FALSE ???

A: Kohana 3.3.2 => The entire code is now case sensitive
Route::set('api','api/v1(/<controller>(/<id>)(/<custom>))'
)->defaults(
    array(
        'directory' =>'Api/V1',
        'controller' => 'Welcome',
        'id'         => FALSE,
        'action'     => 'index',
    )
);


text:
Q: how can i create a countdown timer where the user inputs any number and display it from that number to zero? How can I create a countdown timer where the user inputs a time in seconds and display it from that number to zero in javascript?
var userChoice = parseInt(prompt("Type in time to countdown"));
var timer = setInterval(countDown, 1000);

// this is what i have
function countDown() {
   console.log(counter);
   counter--;
   if (counter < 0) {
      clearInterval(timer);
      console.log("END");
   }
}

A: Your mistake was: counter is never defined. Replace it with userChoice and it works perfectly the way you did it:
var userChoice = parseInt(prompt("Type in time to countdown"));
var timer = setInterval(countDown, 1000);

function countDown() {
   console.log(userChoice);
   userChoice--;
   if (userChoice < 0) {
      clearInterval(timer);
      console.log("END");
   }
}

A: The timer only fires once.  Be sure to place the following line at the end of your countDown function so it will get called again:
timer = setTimeout(countDown, 1000);


text:
Q: How to overwrite the existing CSV file with new file while export from MYSQL I have to export the MySQL table data into CSV file for every 5 minutes with same file location and file name.
I run the following query to export:
SELECT *  INTO OUTFILE ' c:/newfolder/matrix.csv ' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' FROM tablename

When I export the data, first time it exported correctly, but second time it shows the error "SQL Error(1086) File:' c:/newfolder/matrix.csv ' already exists". I need to overwrite the existing file.
Can any one help to solve this problem?

A: I guess you are using a SELECT ... INTO OUTFILE statement.
According to documentation the file cannot exists or the statement will fail:

The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file...

Use a file with a mysqldump instead and put in crontab
*/5 * * * * /path/to/your/file/backup.sh


text:
Q: WPF datagrid as user control I need help with binding.  Its WPF MVVM pattern.  I have placed a datagrid and three ICommand buttons 'Add', 'Modify', 'Delete' buttons, in a UserControl (UC).  The add, modify, delete buttons are to facilitate operations to the datagrid.  Calling this UC 5 times in a XAML window (Main window).  The button controls are handled in the view model of the main XAML window.  For instance, AddStudent for Add button, ModifyStudent for Modify button and DeleteStudent for Delete button.  But there is only one handler for all the 5 instance of the UC.  For instance, click on the Add button from any of the 5 instances of the UC, it calls the same AddStudent function.
But the problem is, the 5 UC instance has to bind to 5 different Students class,  Engineering,  Medical,  Architecture and so on.
 here is Student entity containing student details.
So when I click on the Medical Student datagrid's Add button, a dialog would popup asking for student details that should be inturn added to the Medical Student's datagrid.  Same goes to other 4 datagrids.  All these should be done in view model.  But the problem is, since all the 5 instances call the same AddStudent method, the new student added is reflecting in all 5 datagrids.  I want to be able to bind the respective Student list to its corresponding datagrid control.  Need help with the binding.
PS:  I have made the ITemsSource of the UC a Dependency Property.
Student is not an interface. Its an entity class.
public class College
{
    private string code;
    private string name;

    private Student engineering;
    private Student medical;
    private Student nursing;
    private Student architecture;
    private Student fashionDesign;

     public Student Engineering
     {
         get
         {
             return engineering;
         }
         set
         {
            SetField(ref engineering, value, () => Engineering);
         }
     }
 }

Where Student is a class. Unfortunately, I dont have the liberty to change it to an Interface. Any other way to bind each of these to its corresponding datagrid.

A: How you have written that college class makes it look like each college can only have 1 of each type of student? surely a college would have a whole list of students, and what if you're asked to add more courses? you're going to end up with grids everywhere and a big mess.
My suggestion would be to add a StudentType (as an enum) onto your student class.
So my enum:
public enum TypeOfStudent
{
    Engineering,
    Medical,
    Computing,
    Fashion
}

Add it as a property to your student class:
public class Student
{
    public TypeOfStudent StudentType;

    //and other details as required...
}

Then you just need a list of students in your College class and only one set of buttons on your form. For the add student method to know what type of student you want to add, then on your form where your asking for students info add a simple combobox containing your enum values for the user to select from would work.
public class College
{
    //property that contains ALL of the students
    public ObservableCollection<Student> Students

    //property containing the a filtered list of students. Your grid will bind its itemssource to
    //this property. You will need to set this property to equal students on initial load up so
    //it will display all students
    public IEnumerable<Student> FilteredStudents { get { return _filteredStudents; } }

    //property that returns the values in your enum which you can bind a combobox's itemsource to
    public IEnumerable<TypeOfStudent> StudentTypes
    {
        get { return Enum.GetValues(typeof(TypeOfStudent)).Cast<TypeOfStudent>(); }
    }

    //property that stores the selected student type which should be bound to a combobox's
    //selecteditem.
    public TypeOfStudent SelectedStudentType {  get; set + Raise PropertyChanged stuff;  }

    //property storing the selected filter for type of student
    public TypeOfStudent SelectedFilter {get; set + raise propertychanged; }

    //method for adding a student to your list of students
    public void AddStudent()
    {
        this.Students.Add(new Student
        {
            StudentType = this.SelectedStudentType
        });
    }

    //method of applying a filter
    public void FilterStudents()
    {
        _filteredStudents = this.Students.Where(s=>s.StudentType == this.SelectedFilter);
    }
}

As for getting your one datagrid to show students of a specific type. If you give the user a combobox with a list of student types, then when they select something you can use the filter students method to update the grid.
Now there are a few things i've left out. For example you would probably want some kind of 'All' option in the filter. And you'll need to do some raise property changed events on the lists etc. but what i've written should make the whole thing more manageable.


text:
Q: R na.omit - single vs multiple files - list files vs read.csv? Read 1 file and omit Na's:
z <- read.csv(file="C:/data/specdata/002.csv", header=TRUE, sep=",")
newdata <- na.omit(z)

newdata works as it should and shows no NAs.
Read multiple files in directory:
files <- list.files(path = "C:/data/specdata/", pattern='^\\d+.csv')
lst <- lapply(files, read.csv,header=TRUE)
newdata <- na.omit(lst)

I get the same results for lst and newdata, i.e. NAs are still present. Do you know why?

A: when you are calling na.omit(lst), na.omit will try and omit missing values from the list lst.  I suspect what you want to do is:
newdata <- lapply(lst,na.omit)

Alternatively, if the data.frames in lst all have the same structure, you might want to rbind() them togeather before calling na.omit, as in:
newdata <- na.omit(do.call(rbind,lst))


text:
Q: Computational complexity of solving linear diophantine equations? Is there any good complexity upper bound for checking satisfiability of a matrix system $Ax=b$ where $A\in \Bbb Z^{m\times n}$?
I found some estimate on computing the Smith Normal Form $N$ such that $SAT=N$ for invertible matrices $S$ and $T$, for example here: unfortunately, it is not very clear from the paper how the matrices $S$ and $T$ can be recovered, there is only one note at the end of Section 1 that they will do it "in the future".
I found a few other papers dealing with complexity of SNF, but either they only describe special cases (square, invertible..) or I couldn't see how to use them (without the unimodular matrices $S$ and $T^{-1}$).
I don't know whether I need to compute the Smith Normal Form at all.
The matrix I have in mind is a (co)boundary matrix between $k$- and $(k+1)$-simplices of a simplicial complex, if it helps.
Any help will be appreciated.

A: I would leave a comment but don't have the reputation: check out http://www.math.udel.edu/~lazebnik/papers/dioph2.pdf, which also looks to have several useful references (in particular http://www.math.tamu.edu/~rojas/kannanbachemhermitesmith79.pdf for algorithms to compute Smith normal form).


text:
Q: Is there a way to access a value computed using props in componentDidMount? I'm working on converting a vanilla js gsap(GreenSock) animation to react, and want to access values based on props in componentDidMount(where gsap tweens are called). The animation is based on https://codepen.io/zadvorsky/pen/dILAG, using Delaunay triangulation and tweens to explode a shattered image. How do I access said values?
Originally I had the calculations contained in if(shatter) inside render but the values of rx, ry, and delay were undefined in the tween used in componentDidMount. I moved said calculations to componentDidMount so said values would be available, but the props are not available then, even with the use of a constructor.
export class Explosion extends React.Component {

constructor(props) {
    super(props)
    this.state = {
        shatter: false
    }
}

tl0 = new TimelineMax();
tl1 = new TimelineMax();

fragmentNode = React.createRef()
containerNode = React.createRef()

componentDidMount() {

    if (this.state.shatter) {
        const triangulatedValues = triangulate({
            this.props.width,
            this.props.height,
            this.props.startX,
            this.props.startY
        })

        const {
            vertices,
            indices
        } = triangulatedValues

        const ExplosionFragments = []

        for (let i = 0; i < indices.length; i += 3) {

            let point0 = vertices[indices[i + 0]]
            let point1 = vertices[indices[i + 1]]
            let point2 = vertices[indices[i + 2]]

            let fragmentCentroid = computeCentroid({
                point0,
                point1,
                point2
            })

            let dx = fragmentCentroid[0] - startX
            let dy = fragmentCentroid[1] - startY
            let d = Math.sqrt(dx * dx + dy * dy)
            let rx = -30 * sign(dy)
            let ry = -90 * -sign(dx)
            let delay = d * 0.003 * randomRange(0.7, 1.1)

            let box = computeBoundingBox({
                point0,
                point1,
                point2
            })

        }
    }

    this.tl1
        .to(this.fragmentNode, 1, {
            z:500,
            rotationX:rx,
            rotationY:ry,
            ease:Power2.easeInOut
        })
        .to(this.fragmentNode, 0.4,{alpha:0}, 1)
    this.tl0
        .insert(this.tl1, delay)
}

render() {

    const {
        shatter
    } = this.state

    return (
        <Container
            ref={this.containerNode}
            onClick={this.handleToggleShatter}
        >
            {shatter ? (
                <div>
                    <OverlayImage
                    src="http://i67.tinypic.com/2eq9utk.jpg"
                    />
                    <canvas
                    width={width}
                    height={height}
                    ref={this.fragmentRef}>
                    </canvas>
                </div>
            ) : (
                <OverlayImage
                    src="http://i67.tinypic.com/2eq9utk.jpg"
                />
            )}
        </Container>
    )
}
}

export default Explosion

https://codesandbox.io/s/ll139x3nx7
I expect the props to be available in componentDidMount, but the error "Parsing error: this is a reserved word" gets thrown. This is just an error for a possible solution, and I'm open to any way forward.

A: When you do:
const triangulatedValues = triangulate({
    this.props.width,
    this.props.height,
    this.props.startX,
    this.props.startY
})

You're passing in an Object where the keys are this.props.width etc and the values are also this.props.width because you haven't specified any other key, so it'll try to call the key the name of the variable.
Try:
const triangulatedValues = triangulate({
    width: this.props.width,
    height: this.props.height,
    startX: this.props.startX,
    startY: this.props.startY
})


text:
Q: Typeahead.js pass dynamic additional parameters Suppose I have a form with multiple fields using typeahead.js, for some fileds I wish to pass values from previously populated form fields as part of the query. For example
<input id="First_Name" type="text">
<input id="Last_Name" type="text">

JavaScript:
$('#Last_Name').typeahead({
  name: 'typeahead',
  remote: 'Search.pl?query=%QUERY'.
  template:[
 ......
  ].join(''),
  engine: Hogan
});

Since I have multiple input boxes, some should pass the ID & value of other input boxes as part of the remote query, I wonder if there is a generic way to append the ID & value to this string only if the fields contain values.
Thanks in advance

A: You can do that. Use a replace to process the query string before it is set.
Something like:
$('#Last_Name').typeahead({
  name: 'typeahead',
  remote: {
    url: 'Search.pl?query=%QUERY',
    replace: function(url, uriEncodedQuery) {
      val = $('#First_Name').val();
      if (!val) return url;
      //correction here
      return url + '&first_name=' + encodeURIComponent(val)
    },
  template: ...,
  engine: Hogan
});

A: Old topic but can be usefull with a more detailed answer :
As @Shaked has already said, you need to use replace function
1 . If you wan to have dynamic parameters
This is the case, you wan't dynamic parameters that not be part of typehead input.
This case is not the recommanded one, bacause if you are in this situation you shouldn't need typehead.
$('#myID').typeahead({
  name: 'typeahead',
  remote: {
    url: 'search.php',
    replace: function(url, uriEncodedQuery) {
      val = $('#yourValue').val();
      if (!val) return url;
      return url + '?param=' + encodeURIComponent(val)
    },
  template: ...,
});

2 . If you want to add dynamic parameters
This case is the more interesting one. Someting you wan't to get some additionnal parameters comming from other DOM inputs that they do not part of Typehead input.
You need to use replace too but the content is different :
 $('#myID').typeahead({
      name: 'typeahead',
      remote: {
        wildcard: '%QUERY',
        url: 'search.php?query=%QUERY',
        replace: function(url, uriEncodedQuery) {
          val = $('#yourValue').val();
          if (!val) return url.replace("%QUERY",uriEncodedQuery);
          return url.replace("%QUERY",uriEncodedQuery) + '&param=' + encodeURIComponent(val)
        },
      template: ...,
    });

With this code, you will be able to get TypeHead input + some additional parameters


text:
Q: CoffeeScript: store data from jQuery Ajax call in variable I'm using CoffeeScript and jQuery, trying to get the data from an ajax call stored in a local variable so I can use it in the rest of my method. Here's my existing code:
response = null
$.ajax
  url: '/polygons'
  dataType: 'json'
  success: (data, textStatus, jqHXR) ->
    response = data

console.log response

With this code, response always stays null. All I want to do is get the data variable out of the success function and into the calling method, but I can't seem to get it out of that scope. What am I doing wrong here?

A: Ajax is asynchronous so response will not be set when you call console.log response, use response in the callback function.
response = null
$.ajax
  url: '/polygons'
  dataType: 'json'
  success: (data, textStatus, jqHXR) ->
    response = data
    console.log response

how do I make sure the script waits after this until the ajax call is complete, so it won't proceed using the null response object?

You should just do all your processing in the callback function, if you don't want to do that you can make the ajax call synchronous by changing async to false in the ajax options


text:
Q: How to store null values to dictionary c# I found that if my value in database is null the app would crash while I storing it to dictionary, here's my code:
private async Task<Dictionary<string, string>> GetProducts(long productId)
{
    return await _dbContext.Products
       .Where(prod => prod.productId == productId)
       .Select(prod => new
       {
           prod.ProductStockReferenceId,
           prod.ProductTitle
       })
       .ToDictionaryAsync(x => x.ProductStockReferenceId, x => x.ProductTitle);
}

And I've realized that if ProductStockReferenceId in database is null the app would crash, how come and what could I do to prevent this?
Thanks
Cheers

A: Depending on whether you want to retrieve also items with null ProductStockReferenceId you have two options.

Filter out records with null:
return await _dbContext.Products
       .Where(prod => prod.productId == productId && prod.ProductStockReferenceId != null)
       .Select(prod => new
       {
           prod.ProductStockReferenceId,
           prod.ProductTitle
       })
       .ToDictionaryAsync(x => x.ProductStockReferenceId, x => x.ProductTitle);

or you can create custom (must be unique) key and store problematic items there:
var nullIndex = 0;
return await _dbContext.Products
    .Where(prod => prod.productId == productId && prod.ProductStockReferenceId != null)
    .Select(prod => new
    {
        prod.ProductStockReferenceId,
        prod.ProductTitle
    })
    .ToDictionaryAsync(x => x.ProductStockReferenceId ?? $"null:{nullIndex++}", x => x.ProductTitle);

But be sure to create custom keys that won't be present in ProductStockReferenceId so DbKeys and CustomKeys will not overlap


text:
Q: file input int strings c So I'm having issues right now with my program. I'm trying to get it to open a file count the lines rewind and then go through the file to store the variables.
String String String int is the format of the file but I'm having issues after I count the lines. I can print the numbers to the screen but then I get a seg fault right after the print. I don't know why
int countLines(FILE * fin){
int count=0;
char street[100];
char city[100];
char state[3];
int zip;

do{
    fgets(street, 100, fin);
    fgets(city, 100, fin);
    fgets(state, 3, fin);
    fscanf(fin, "%d\n", &zip);
    count++;
}while(!feof(fin));

rewind(fin);

return count;

}
lines=countLines(fin); is how I call the function. What am I doing wrong?

A: Do not mix fgets() with fscanf() until you are very comfortable with these functions.  They do not play well together.  That \n in the format is a white space and will match any number of consecutive white space including multiple \n, spaces, tabs, etc.
// fscanf(fin, "%d\n", &zip);

Recommend avoiding feof() and using the return value from fgets().
feof() does not become true until a file read is attempted and fails to provide a char.  This is different than "true when none left".  Example: you read the last char of a file.  feof() is still false.  Code attempts to read more (and fails).  Now feof() is true.  (and remains true).
Do count the lines in a simple fashion and use symmetry.  Further consider more error checking.  Read the zip code line as a string and then parse it as an integer.
int countLines(FILE * fin){
  int count=0;
  char street[100];
  char city[100];
  char state[100];
  char zips[100];
  unsigned zip;

  while (fgets(street, sizeof street, fin) != NULL) {
    count++;
  }
  rewind(fin);

  if (count%4 != 0) Handle_LineCountNotMultipleof4();

  // You could return here, but let's read the file again and get the data.
  // This is likely part of OP's next step.
  for (int i=0; i<count; i += 4) {
    if ((NULL == fgets(street, sizeof street, fin)) ||
      (NULL == fgets(city,   sizeof city, fin)) ||
      (NULL == fgets(state,  sizeof state, fin)) ||
      (NULL == fgets(zips,   sizeof zips, fin)) ||
      (1 != sscanf(zips, "%u", &zip))) handle_error();
    // Remember street, city, state, still have an ending \n
    do_something(street, city, state, zip);
  }
  return count;
}

Alternatively, to count the lines use the following.  A singular difficulty occurs in reading if you have long lines, so let's check that as we go.  Take this out line length stuff if you prefer a simple answer.  You could use the Maxline+1 as you buffer size instead of a fixed 100.
  size_t Maxline = 0;
  size_t Curline = 0;
  int ch;
  while ((ch = fgetc(fin)) != EOF) {
    Curline++;
    if (ch == '\n') {
      count++;
      if (Curline > Maxline) MaxLine = Curline;
      Curline = 0;
    }
  }
  if ((Maxline + 1) > 100) TroubleAhead() ; // Trouble with future (fgets(buf, 100, fin), use bigger buffers
  rewind(fin);

A: fgets tries to read a whole line,not just a word, which seems to be what you are hoping for.
So, the buffers you are passing it arent big enough, and they won't get what you were hopign for and you are incrementign the count once for every 3 lines and fscan usually wont read a line leaving the remains of that line to interfere with your next read.
If you want to read words, try scanf, with %s. If you want to read a fixed number of chars, try fread.


text:
Q: converting date into timestamp I have date like this 25. 02. 2014 18:48:21 and I'm trying to convert it into timestamp
var someDate = '25. 02. 2014 18:48:21';
var timestamp = new Date(someDate).getTime();

but it's returning NaN since I moved files to a new domain, what can be a problem?

A: Running this within the console, creating a new date with that variable gives me Invalid Date.  Trying switching around the 25. and 02. like so:
var someDate = '02. 25. 2014 18:48:21';
var timestamp = new Date(someDate).getTime(); // 1393372101000

The format should be "Month, Day, Year, Time".

A: '25. 02. 2014 18:48:21' is not a valid date format. You'll have to convert it with regex first, like that:
var someDate = '25. 02. 2014 18:48:21';
var converted = someDate.replace(/^(\d{2}\. )(\d{2}\. )(\d{4})/, '$3. $2$1');
// converted is in format: YYYY. MM. DD.
var timestamp = new Date(converted).getTime();

A: Switching month and day will work. I also removed the dots.
var date = "25. 02. 2014 18:48:21";
new Date(date.replace(/(\d{2})\. (\d{2})\./, '$2 $1'))
// Tue Feb 25 2014 18:48:21 GMT+0100 (W. Europe Standard Time)

A: you can try something like below (if your string has always same format)
var someDate = '25. 02. 2014 18:48:21';
var arr = someDate.split(' ');
var time = arr[3].split(':');
var timeStamp = new Date(arr[2],arr[1].split('.')[0],arr[0].split('.')[0],time [0],time[1],time[2]).getTime();

It uses javascript date object constructor
var d = new Date(year, month, day, hour, minute, seconds);

which works across all browsers

A: function convertSomeDate(str){
    var d= str.match(/\d+/g),
    dA= [d[2], '-', d[1], '-', d[0], 'T', d[3], ':', d[4], ':', d[5], 'Z'].join('');
    return +new Date(dA)
}

var someDate= '25. 02. 2014 18:48:21';
convertSomeDate(someDate)

/*  returned value: (Number)
1393354101000
*/


text:
Q: What are the double angle trig formulas called? For example, what is $\sin(2x) = 2 \sin x \cos x$ called? Here are a few names I can think of:

*

*Double angle formula for sin

*Double angle formula of sin

*Sin double angle formula

*Double angle sin formula

However, none of these sound "right." Do they have proper names?

A: They are called double angle formulas. It doesn't only work for sine, there's also cosine and tangent, so in general they are called double angle formulas.


text:
Q: is there a use for &func or class::func in c++? This seems inconsistent. Why do we use &Example::func instead of Example::func? is there a use for Example::func or &exampleFunction? it doesnt seem like we can make a reference to a function so that rules out Example::func. and i cant think of a way to use &exampleFunction since exampleFunction already returns a pointer.
#include <iostream>
class Example {
public:
    void func() { std::cout <<"print me\n"; }
};
void exampleFunction() { std::cout << "print me too\n"; }
typedef void (Example::*ExampleFunc_t)();
typedef void (*ExampleFunction_t)();
int main()
{
    Example e;
    ExampleFunc_t     f  = &Example::func;
    ExampleFunction_t f2 = exampleFunction;
    (e.*f)();
    f2();
    return 0;
}

A: Because that's how the standard defines pointers to functions.
You actually always have to use the address operator & to get a pointer to a function, but for regular functions and static member function, an implicit conversion from function to pointer-to-function is defined in the standard.
This is not defined for a (non static) memberfunction because you can't obtain an lvalue to a non static memberfunction.
From the C++ standard:

4.3 Function-to-pointer conversion

*

*An lvalue of function type T can be converted to an rvalue of type
"pointer to T ." The result is a pointer to the function.

with footnote 52:

This conversion never applies to non-static member functions because
an lvalue that refers to a non-static member function cannot be obtained.

I think that they'd rather only allow &function, for consistency reasons, but that the implicit conversion is simply an artifact of the C heritage...

A: The point is using Function Pointers. For a very rough example, suppose you have a class having several member variables by which you may need to sort of the elements of an array of that class type, like this:
struct CL {
    int x, y, z;
};

bool sort_by_x(const CL& obj1, const CL& obj2);
bool sort_by_y(const CL& obj1, const CL& obj2);
bool sort_by_z(const CL& obj1, const CL& obj2);

...

CL obj[100];
...
sort(obj, obj+100, sort_by_x);
...
sort(obj, obj+100, sort_by_y);
...
sort(obj, obj+100, sort_by_z);

Here std::sort is used to sort an array of CL objects. Look at the third parameter, it's name of a function. The std::sort function can take a function pointer in third parameter, and use that function as comparator to sort the array. It is upto us how to define sort_by_* functions so that std::sort works as expected.


text:
Q: grab +1 data from same page as code Is there any coding method to grab +1 data off of the current website? Example, I know there is no API yet for Google's +1 but is there a way to search for the string posting the data on the same page as the php?
Search for aggregateCount and go to next >x< and pull between those and set it as a variable?
I've seen the button posted in a few different ways:
37.6k

2

Google's javascript posts the number of +1's but it's after code runs so I don't know if PHP can grab it that late in processes. Any other way?

A: There's indeed no API I know of, but you can request https://plusone.google.com/u/0/_/+1/fastbutton?url=yoururlencodedpage, and look for the window.__SSR = {'c':  1.0 ,'is': 0}; string. The c value is the count (as a float for some reason...). Prone to absolute breakage if Google decides to change it in the slightest. If you personnaly liked the page (and are logged in by your code for some weird reason) there's more data in window.__SSR.


text:
Q: AJAX Js Yii2 dropdown POST 500 (Internal Server Error) I'm using yii2 and a newbie in JavaScript and ajax.
I am getting this error:

jquery.js:9175 POST http://localhost/istanagroup/web/purchase-order/basepricenet 500 (Internal Server Error)

here is the controller function
public function actionBasepricenet(){
$id = $_POST['id'];
$model = MasterItem::find()->andFilterWhere(['id_master_item'=>$id])->one();
echo $model;

here is the js :
$('#purchaseorderdetail-0-id_master_item').change(function(){
  var cat = $(this).val();
  $.ajax({
    type:'POST',
    url:'http://localhost/istanagroup/web/purchase-order/basepricenet',
    data : {id:cat},
    dataType : 'text',
    success:function(res){
      console.log(res);
      $('#purchaseorderdetail-0-base_price').val(res);
    }
  });
});

A: Folowing the Yii2 documentation,

andFilterWhere adds an additional WHERE condition to the existing one but ignores empty operands.

In your case you do not have declared a where() condition. Furthermore, once the ID is always provided in the request, you could change the andFilterWhere() to a normal where(), as the following:

public function actionBasepricenet(){
  if (isset($_POST['id'])){
    $id = $_POST['id'];
    $model = MasterItem::find()->where(['id_master_item'=>$id])->one();
    var_dump($model);
  } else {
     // ID not received! Error!
  }
}