text:
Q: Prove the soundness of propositional logic without using induction? I want to prove the soundness of propositional logic without using induction. I think I can do that via a process that's basically universal introduction (i.e., demonstrate something about an arbitrary member and infer that it applies universally). As an example of this approach I've picked a new inference rule to prove.
My questions:

*

*Is my approach valid?

*Is my proof correct?

*Is it easy to understand and follow?

*Do I need to add more/less detail?

*How else can I improve it?

Proof
We want to show that $\boxed{\dfrac{\Gamma_1 ,\,\phi\vdash\psi\quad\Gamma_2,\,\lnot\phi\vdash\psi}{\Gamma_1 ,\,\Gamma_2\vdash\psi}}\def\pa {((\Gamma_1\land\phi)\longrightarrow\psi)}
\def\pb {((\Gamma_2\land\lnot\phi)\longrightarrow\psi)}
\def\ca {((\Gamma_1\land\Gamma_2)\longrightarrow\psi)}
\def\lto {\longrightarrow} \def\val#1{V_\mathscr{I}( #1 )}
\def\pli {\text{PL-interpretation, $
$\mathscr{I}$},} \def\inp{\mathscr{I}}$ is a truth preserving inference rule without using induction. To do so we'll convert the rule to an axiom schema and show that it's valid.
Conversion Rules
Symbols

*

*"," and the "$\quad$" convert to conjunction

*"$\vdash$" and the vinculum convert to implication

*$\Gamma$, with or without subscript, is a finite set of conjoined wffs, so it's simply a wff with it's own valuation rules

Valuation of $\Gamma$

*

*$\val{\Gamma}=1$ iff, for all $\gamma\in\Gamma$, it's the case that $\val{\gamma}=1$ and $\Gamma\neq\emptyset$
Conversion

*

*$\Gamma_1 ,\,\phi\vdash\psi:= \pa$

*$\Gamma_2,\,\lnot\phi\vdash\psi:= \pb$

*$\Gamma_1 ,\,\Gamma_2\vdash\psi:= \ca$

*Putting it all together, the rule converts to - $\boxed{((\pa\land\pb)\lto\ca)}$
Proof that the axiom schema is valid

*

*Assume for reductio that $\val {((\pa\land\pb)\lto\ca)}=0$

*It follows from (1) that $\val {\ca}=0$

*It follows from (2) that $\val{\Gamma_1}=1$, $\val{\Gamma_2}=1$, and $\val{\psi}=0$

*It follows from (1) that $\val{\pa}=1$

*It follows from (3) and (4) that $\val{\phi}=0$

*It follows from (5) that $\val{\lnot\phi}=1$

*It follows from (1) that $\val{\pb}=1$

*It follows from (3) and (6) that $\val{\pb}=0$, which contradicts (7) $\boxed{}$
Example Proof
$\begin{array}{lrcll}
1.&\phi&\vdash &\phi &\text{RA}\\
2.&\phi&\vdash &\lnot\psi\lor\phi &\text{1, $\lor$I}\\
3.&\phi&\vdash &\psi\to\phi &\text{2, Abbrv}\\
4.&\phi&\vdash & (\phi\to\psi)\lor(\psi\to\phi) &\text{3, $\lor$ I}\\
5.&\lnot\phi&\vdash &\lnot\phi &\text{RA}\\
6.&\lnot\phi&\vdash &\lnot\phi\lor\psi &\text{5, $\lor$I}\\
7.&\lnot\phi&\vdash &\phi\to\psi &\text{6, Abbrv}\\
8.&\lnot\phi&\vdash & (\phi\to\psi)\lor(\psi\to\phi) &\text{7, $\lor$ I}\\
9.&\emptyset &\vdash & (\phi\to\psi)\lor(\psi\to\phi) &\text{4, 8 New Rule}\\
\end{array}$

A: It's easier to use Heyting algebra lattice model to understand the usual induction proof on the height of derivations of soundness in both intuitionistic and classical logic. And every Boolean algebra is a Heyting algebra which is also distributive.

In mathematics, a Heyting algebra (also known as pseudo-Boolean algebra) is a bounded lattice (with join and meet operations written ∨ and ∧ and with least element 0 and greatest element 1) equipped with a binary operation a → b of implication such that (c ∧ a) ≤ b is equivalent to c ≤ (a → b).

In the link there's a lattice diagram, every natural deduction rule of each connective can be checked to preserve the order of such lattice according to the lattice formation definitions. But you still need to climb up the lattice for an arbitrary derivation with finite steps. But this height in the lattice doesn't correspond to the entities or terms of the domain of discourse of such a structure, so you cannot invoke "universal introduction" as a natural deduction inference rule. Back in territory with your valuation function, this height complexity corresponds to  the individual step of your proof which is not an entity of its domain of discourse (thus no universal introduction applicable here), so induction seems necessary here.


text:
Q: AngularJs delete record on nested grouped rows I'm trying to build a simple page to group record and then add a button to eliminate some records.
The problem is that the record eliminated that has the same name is deleted from the wrong grouped list. And also if a list have no grouped records should disappear, and instead is always there.
Fiddle: http://jsfiddle.net/Tropicalista/qyb6N/15/
// create a deferred object to be resolved later
var teamsDeferred = $q.defer();

// return a promise. The promise says, "I promise that I'll give you your
// data as soon as I have it (which is when I am resolved)".
$scope.teams = teamsDeferred.promise;

// create a list of unique teams
var uniqueTeams = unique($scope.players, 'team');

// resolve the deferred object with the unique teams
// this will trigger an update on the view
teamsDeferred.resolve(uniqueTeams);

// function that takes an array of objects
// and returns an array of unique valued in the object
// array for a given key.
// this really belongs in a service, not the global window scope
function unique(data, key) {
    var result = [];
    for (var i = 0; i < data.length; i++) {
        var value = data[i][key];
        if (result.indexOf(value) == -1) {
            result.push(value);
        }
    }
    console.log(result)
    console.log(Math.ceil(result.length / 10))
    $scope.noOfPages = Math.ceil(result.length / 10);
    return result;
}

$scope.currentPage = 1;
$scope.pageSize = 5;
$scope.maxSize = 2;

$scope.deleteItem = function(item){
    //code to delete here
    var index=$scope.players.indexOf(item)
    $scope.players.splice(index,1);
};

A: Here is a sample of something expanding on the tip from SpykeBytes

                    Location name
                    <input class="journey-input" id="location_{{ $index }}" type="text" ng-model="location.location_name" />
                    <button ng-show="editable" tabindex="-1" class="journey-button remove" ng-click="removeItem(journey.locations, $index)">
                        Remove location
                    </button>

Then in my controller I set up an action that takes deletes the individual item
$scope.removeItem = function(itemArray, index) {
  return itemArray.splice(index, 1);
};

A: To hide the group when nothing is listed, you need to get the filtered list and then use ng-show to drive the display. This is a bit tricky:

0" ng-repeat="team in teams| startFrom:(currentPage - 1)*pageSize  | limitTo:pageSize | filter:searchInput"> {{team}}

{{player.name}}
        <button class="btn btn-small" type="button" ng-click="deleteItem(player)">Delete</button>

However I am not seeing the problem you said about removing from wrong group. Can you let me know how to reproduce it?

A: Index won't help you here because the {{$index}} that ng-repeat provides is within the groupings. That is, each grouping restarts the $index variable.  You are going to need a unique identifier for each record though. Without that there is no way to be sure that the record you want to remove is the right one.
As far as the groupings, you can recreate the model whenever you delete something. This wouldn't work with the sample data in the Fiddle, but it works when you're dealing with a real datasource.

A: You can instead pass the index of the object if it is within ng-repeat.

redpajama_set_name: RedPajamaStackExchange


text:
Q: load latitude and longitude from API before map loads Swift 3 I'm trying to show a map with two markers with longitudes and latitudes that are retrieved from API.
the function that gets the longitudes and latitudes is called in Viewdidload
 override func viewDidLoad() {
    super.viewDidLoad()

    getCurrent()

also the code to show the map with markers in viewdidload so my full code looks something like this:
var longFamily  = ""
let latFamily = ""
var latShop = ""
var longShop = ""

override func viewDidLoad() {
    super.viewDidLoad()

    getCurrent()
    let coordinate₀ = CLLocation(latitude: CLLocationDegrees(Int(latFamily)!), longitude: CLLocationDegrees(Int(longFamily)!))
    let coordinate₁ = CLLocation(latitude: (Int(latFamily)!, longitude: (Int(longFamily)!))
    let distanceInMeters = coordinate₀.distance(from: coordinate₁) // result is in meters
    let floatDistance = Float(distanceInMeters)

    // get two markers with shop and client locations

    map.delegate = self

    // 2.
    let sourceLocation = CLLocationCoordinate2D(latitude: (Int(latFamily)!, longitude: (Int(longFamily)!)
    let destinationLocation = CLLocationCoordinate2D(latitude: (Int(latShop)!, longitude: (Int(latShop)!)

I know there is something I have to do to get the data before the map loads but not sure where. I'd appreciate your help
GetCurrent function calls API :
 Alamofire.request(url!, method: .get, parameters: param,encoding: URLEncoding.default, headers: headers).responseJSON { response in

        if let value: AnyObject = response.result.value as AnyObject? {
            //Handle the results as JSON

            let data = JSON(value)
            self.LongShop = data["shopLong"]
     // this is for family locations too

A: If you want to have the coordinates before the map loads, you want to make the API call before the view is loaded (before viewDidLoad is called). You could try viewWillAppear, but depending on the response time from the API, this may be unreliable. I would suggest making the call to the API as soon as you have the data to do so. Get param from the user or desired source before hand (possibly in a different view), and pass it to the map view in the prepareForSegue function:

*

*Add a global variable to the map view (MapViewController.swift for example)
class MapViewController {
    var param: Any?    // replace Any with the desired data type
    /* rest of MapView code */
}

*Make the API call and pass in the previous View Controller and pass it to the MapViewController
class PreviousViewController {
    var param: Any?    // replace Any with the desired data type

    override func viewDidLoad() {
        super.viewDidLoad()
        getFromAPI()    // getFromAPI being a function that makes the API call and assigns the param variable
    }

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let dest = segue.destination as? MapViewController {
            dest.param = self.param
        }
    }
}

On top of this, you can add features in which the MapViewController segue cannot be performed until param is not nil


text:
Q: Get access to ssl domain certificate I've got the SSL certificate to my domain using hosting Sprinthost. Now I want to know how can I get this certificate to encrypt and decrypt some data?
 - I'm using web-server Node.js and JavaScript for this project. Node server situated on hosting.
 - CA - Lets`Encrypt
 - Type of certificate - wildcard (domain validation).
 - Of course I have access to the shell.


text:
Q: How to populate a Generic List from a JSON string using C#.NET? I am trying to populate a List in C# but the values are not appearing in the array - though it does not throw an error until I try and set a variable with an array index (because it is out of range of course).
This is the exact return string strJSON I am seeing while debugging.
strJSON "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}"

Why is the List (array) not populating?
This is the code for KeyValue.cs (which to be honest I do not know yet why it needs another class)
namespace LoLSummoner
{
    public class KeyValue
    {
        public int id {get; set;}
        public string name {get; set;}
        public int profileIconId {get; set;}
        public int summonerLevel {get; set;}
        public int revisionDate {get; set;}
    }
}

And this is the code from Summoner.svc.cs
namespace LoLSummoner
{
    public class Summoner : ISummoner
    {

        public int GetSummonerID(string SummonerName)
        {
            int summonerId = 0;

            WebClient client = new WebClient();
            string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");

            JavaScriptSerializer js = new JavaScriptSerializer();

            KeyValue[] arrJSON = js.Deserialize<List<KeyValue>>(strJSON).ToArray();

            summonerId = Convert.ToInt32(arrJSON.GetValue(0));

            return summonerId;
        }
    }
}

A: *

*Your RevisionDate property has to be long, because 1387913628000, and that's the value your trying to deserialize, exceeds int range.

*Your JSON contains information about only one KeyValue object, not an array of there, so you have to deserialize it as KeyValue, no KeyValue[]:
KeyValue item = js.Deserialize<KeyValue>(strJSON);

*Having KeyValue instance you can use standard property syntax to return ID:
return item.id;

I find this code working:
public class KeyValue
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public int summonerLevel { get; set; }
    public long revisionDate { get; set; }
}

static void Main(string[] args)
{
    var input = @"{""id"":34379899,""name"":""Revelation22"",""profileIconId"":547,""summonerLevel"":30,""revisionDate"":1387913628000}";

    JavaScriptSerializer js = new JavaScriptSerializer();

     var item = js.Deserialize<KeyValue>(input);

     var summonerId = item.id;
}

A: As already noted, the revisionDate will cause a runtime binding exception if it is not typed as a long.
public class KeyValue
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public int summonerLevel { get; set; }
    public long revisionDate { get; set; }
}

In addition to that, you may wish to attempt a simple detection in order to deserialize this as either an object or an array of objects (if in the future the name is no longer unique).
public int GetSummonerID(string SummonerName)
{
    int summonerId = 0;

    WebClient client = new WebClient();
    string strJSON = client.DownloadString("http://prod.api.pvp.net/api/lol/na/v1.2/summoner/by-name/" + SummonerName + "?api_key=xxxx");

    JavaScriptSerializer js = new JavaScriptSerializer();

    if(strJSON[0] == '[')
    {
        return js.Deserialize<KeyValue[]>(strJSON)[0].id;
    }
    else
    {
        return js.Deserialize<KeyValue>(strJSON).id;
    }
    return summonerId;
}

A:
I do not know yet why it needs another class

You don't need that class. It think the simplest way would be to deserialize your json directly to Dictionary<string, object>
var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";

var dict = new JavaScriptSerializer()
           .Deserialize<Dictionary<string, object>>(strJSON);

Console.WriteLine(dict["name"]);
Console.WriteLine(ToDateTime((long)dict["revisionDate"]));

DateTime ToDateTime(long l)
{
    return  new DateTime(1970, 1, 1).AddMilliseconds(l);
}

A: One thing to note is that your JSON string contains only a single KeyValue, not a list of them. Another problem is that the revision date is too large to fit in a 32 bit int, so consider using a long instead.
Here's some example code that reads your sample string and prints out some of the values.
public class KeyValue
{
    public int id { get; set; }
    public string name { get; set; }
    public int profileIconId { get; set; }
    public int summonerLevel { get; set; }
    public long revisionDate { get; set; }
}

static void Main(string[] args)
{
    var strJSON = "{\"id\":34379899,\"name\":\"Revelation22\",\"profileIconId\":547,\"summonerLevel\":30,\"revisionDate\":1387913628000}";
    var serializer = new JavaScriptSerializer();

    var keyValue = serializer.Deserialize<KeyValue>(strJSON);
    var id = keyValue.id;
    var name = keyValue.name;
    var level = keyValue.summonerLevel;

    Console.WriteLine("Summoner name:{0}, Id:{1}, Level:{2}", name, id, level);
    Console.Read();
}

A: Your JSON contains a single object, not an array.
Therefore, you can only deserialize it as KeyValue.


text:
Q: Posting Forms Using Sitecore through javascript I am currently using Sitecore and I am trying to create a POST action to post info to a payment site using information gathered by the form. Knowing that Sitecore strips  tags from html makes it a bit of a pain. After some searching I found that I can use javascript to create a dynamic form and send that would be the answer my question, sadly I am a javscript newbie and while I was able to decipher the javacript I can't make it post.
Any input or links to basic info would be much appreciated.
Here is what my form code looks like:
<fieldset id="PayForm" >

<input type="Hidden" name="ps_store_id" value="******" />
<input type="Hidden" name="hpp_key" value="*******" />
<input type="Hidden" name="charge_total" value="40.00" />

<input type="hidden" value="1" name="quantity1" />
<input type="hidden" value="Public Speaking" name="description1" />
<select name="id1">
<option>Select Date...</option>
<option value="Sep22PubSp"> Sept-22
</option>
<option value="Sep29PubSp"> Sept-29
</option>
<option value="Nov19PubSp"> Nov- 19
</option>
</select>

<input type="hidden" value="40" name="price1" />

First Name<input type="text" name="ship_first_name" value="First Name" />  Last Name  <input type="text" name="ship_last_name" value="Last Name" />

Student ID#: <input type="text" name="cust_id" value="Student ID" />

Email<input type="text" name="email" value="Email" />

CCID<input type="text" name="note" value="CCID" />

</fieldset>

And here is what my Javascript looks like

Thank you for your time!

A: Your issue here is not that Sitecore strips form tags. Your issue is that you are working in ASP.Net webforms, which require special considerations for forms. This is because you already have a form tag, with the attribute runat="server" working to display sitecore's components.
That said, your javascript as it is written will never work in sitecore's environment. You simply can't nest an html form inside of an ASP.Net webform.
See this article on the basics of modifying your ASP.net template to support form submission:
http://www.sitepoint.com/net-form-processing-basics/
Alternatively, you could create the form as you expect it to work (again, without javascript) as pure html, and include it in a sitecore component template (.ascx control) in an IFrame.


text:
Q: Find lines that end with a particular letter How to grep for lines that end with a letter a or d followed by xy
I know that using $ you can check for the ending but not sure how to combine this
and use or condition

A: Few commands to match lines ending with axy or dxy:
# pick one
grep   'axy$\|dxy$'
grep -E 'axy$|dxy$'
grep  '\(a\|d\)xy$'
grep -E  '(a|d)xy$'

*

*You are right about $, it matches the end of the line.

*| is "or". You need to escape it (with \) in BRE (basic regular expression); without escaping the character is literal. In ERE (extended regular expression, grep -E) it's the other way around: "or" when not escaped, literal when escaped.

*( and ) indicate a group, here I used them to limit the scope of |. Similarly, you need to escape in BRE, you mustn't escape in ERE.


text:
Q: How do you center equations? I can't seem to center equations without causing some weird formatting problem.  The following results in the R being dropped:
\begin{center}
 E(R_{i,t})=E(\alpha_i)+E(\beta_{i,F_1 } F_{1,t})+E(\beta_{i,F_2 } F_{2,t})+\ldots+E(\beta_{i,F_m } F_{m,t})\linebreak
\bar{R}_{i,t}=a+\hat{\beta}_{i,F_1 } E(F_{1,t})+\hat{\beta}_{i,F_2 } E(F_{2,t})+\ldots+\hat{\beta}_{i,F_m } E(F_{m,t})\linebreak
\bar{R}_{i,t}=a+\gamma_1\hat{\beta}_{i,F_1 } +\gamma_2\hat{\beta}_{i,F_2 } F_{2,t}+\ldots+\gamma_m\hat{\beta}_{i,F_m }
\end{center}

Any ideas?  Is {center} the wrong thing to use?

A: The center environment is for text, not math. What you want here is (this also lines up the equals signs):
\begin{align*}
  E(R_{i,t})    &= E(\alpha_i)+E(\beta_{i,F_1 } F_{1,t})+E(\beta_{i,F_2 } F_{2,t})+\ldots+E(\beta_{i,F_m } F_{m,t}) \\
  \bar{R}_{i,t} &= a+\hat{\beta}_{i,F_1 } E(F_{1,t})+\hat{\beta}_{i,F_2 } E(F_{2,t})+\ldots+\hat{\beta}_{i,F_m } E(F_{m,t}) \\
  \bar{R}_{i,t} &= a+\gamma_1\hat{\beta}_{i,F_1 } +\gamma_2\hat{\beta}_{i,F_2 } F_{2,t}+\ldots+\gamma_m\hat{\beta}_{i,F_m }
\end{align*}

You need the amsmath package for align*, so make sure you have the line \usepackage{amsmath} in your preamble (before \begin{document}).

A: For a series of centered equations use the gather environment of amsmath:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{gather*}
 E(R_{i,t})=E(\alpha_i)+E(\beta_{i,F_1 } F_{1,t})+E(\beta_{i,F_2 } F_{2,t})+
    \ldots+E(\beta_{i,F_m } F_{m,t})\\
\bar{R}_{i,t}=a+\hat{\beta}_{i,F_1 } E(F_{1,t})+\hat{\beta}_{i,F_2 } E(F_{2,t})+
    \ldots+\hat{\beta}_{i,F_m } E(F_{m,t})\\
 \bar{R}_{i,t}=a+\gamma_1\hat{\beta}_{i,F_1 } +\gamma_2\hat{\beta}_{i,F_2 } F_{2,t}+
    \ldots+\gamma_m\hat{\beta}_{i,F_m }
\end{gather*}
\end{document}

Instead of centering you may consider to align all equations at the equal sign and center the whole multiline environment. For this, use the align or align* environment, see the amsmath user's guide (or type texdoc amsldoc at the command prompt).
In any case, use amsmath. That package provides many kinds of multiline diplayed formula environments.


text:
Q: Java: Implementing parallel hierarchy of trees and its nodes In order to practice data structures I'm implementing my own library of Trees. I've begun with BST and in following I'm about to implement AVL Tree, Red-Black Tree and maybe more. AVL & RBT are BST trees as well, so some class hierarchy is rather obvious. The problem I came into is that all those trees have other types of Nodes - AvlNode has balance factor flag, RgbNode has color flag, BstNode doesn't need any additional info (despite of references to parent, children and value which all Nodes need). So I've a hierarchy of Nodes and a hierarchy of Trees. I could give some flag attribute to BstNode and use it in extending classes but it is surely not a good way to do it.
The problem is how to deal with the fact that for example Bst.findNode() will return BstNode but in Avl I need AvlNode despite the findNode() methods will be the same in both (apart of return type).
I need help with planning the hierarchies or if those parallel hierarchies (as a code smell) are in general a bad idea, I need a workaround because I have no clue how to do it in proper way.
BstTree Class:
public class BstTree<T extends Comparable> implements Iterable
{
    private BstNode<T> root;

    public void addValue(T value)
    {
        BstNode node = new BstNode(value);
        addNode(node);
    }

    public void addNode(BstNode<T> node)
    {
        ...
    }

    public boolean removeNode(T value)
    {
       ...
    }

    public BstNode findNode(T value)
    {
        ...
    }
    //other less significant methods
}

BstNode class:
public class BstNode<T extends Comparable>
{
    private static int lastId = 0;
    private int id;
    private T value;
    private BstNode parent = null;
    private BstNode leftChild = null;
    private BstNode rightChild = null;

    public BstNode(T value) {
        this.id = ++lastId;
        this.value = value;
    }

    public boolean isGreaterThan(BstNode n)
    {
        //...
    }

    public boolean hasLeftChild()
    {
        //...
    }

    public boolean hasRightChild()
    {
        //...
    }

    public boolean hasParent()
    {
        //...
    }

    public boolean isLeaf()
    {
        //...
    }

    public boolean hasOnlyOneChild()
    {
        //...
    }

    public BstNode getOnlyChild(BstNode node)
    {
        ...
    }

    public boolean isLeftChildren()
    {
        ...
    }

    public BstNode getConsequentNode()
    {
        ...
    }
}

I can guess that the separation of responsibilities above may not be perfect, if it's wrong then I might get some of the methods from Node to Tree class but this thing is not a big problem.

A: I would do something like this:
public abstract class BstTree<T extends Comparable,N extends BstNode<T,N>> {
    private N root;
...

    public void addValue(T value)
    {
        N node = newNode(value);
        addNode(node);
    }

    public abstract N newNode(T value);

    public void addNode(N node)
    {
        // ...
    }
}

public class BstNode<T extends Comparable,N extends BstNode<T,N>>
{
    private T value;
    private N parent = null;
    private N leftChild = null;
    private N rightChild = null;

    public BstNode(T value) {
        this.value = value;
    }

    public N getOnlyChild(N node)
    {
        // ...
    }
...
}

public class AVLTree<T extends Comparable> extends BstTree<T,AVLNode<T>> {
    ...
    @Override
    public AVLNode<T> newNode(T value) {
        return new AVLNode<>(value);
    }
}

public class AVLNode<T extends Comparable> extends BstNode<T,AVLNode<T>> {
    ...

    public AVLNode(T value) {
        super(value);
    }

    @Override
    public AVLNode<T> getOnlyChild(AVLNode<T> node) {
        return super.getOnlyChild(node);
    }
    ...
}


text:
Q: Lines + Markers not working in Dash Scattergeo Plot I've created a scattergeo plot in Plotly which is rendering fine, including displaying line + markers Plotly screenshot
However when i call this graph through Dash I can't get the lines + markers to work - it will only show markers
Dash screenshot
When I use mode = lines I get lines in Dash, however evening reversing the options won't show markers + lines
My Code:
dict(type='scattergeo',
    locationmode='country names',

    lon = [From_lon,To_lon],
    lat = [From_lat,To_lat],
    mode='lines + markers',
    opacity = max(min(1,float(df.iloc[i]['Volume']/2000)),0.1),
    #opacity = min(1,float(df.iloc[i]['Volume']/1000)),
    name = df.iloc[i]['ALP From'] + "->" + df.iloc[i]['ALP To'] + " " + df.iloc[i]['Volume'].astype(str),
    hoverinfo="name",
    line = dict(color=df.iloc[i]['Marker_col'],
                width = max(2,df.iloc[i]['Volume']/2000)
    )

Thank you

A: You should remove the spaces from "lines + markers" and use mode="lines+markers" instead


text:
Q: IBAction methods in class extensions? Is it good programming practice to define all (IBAction) methods associated with a NSViewController's .xib within a class extension?

A: Everything that's in the class extension is private to your class.
So the real question here is your IBAction here is private to your view controller or not. If that's something used internally, like the press of a button to activate a function inside your view controller, then yes, put it in your class extension.

A: There's no reason to declare the IBAction in the class extension, if the intent is merely to make the IBAction method private. Just add the implementation of the action method in the controller @implementation.


text:
Q: Why can external JavaScript files access other external JavaScript files functions and how to stop it? I am by no means a guru with JavaScript, so my apologies if this questions sounds "beginner". But why is it that if I have 3 JavaScript files in a project, that any of those 3 JavaScript files can call any of the other functions that are in the other JavaScript  files?
The bigger question is how can this be stopped? an example would be if, of these 3 hypothetical JavaScript files, just say they are named as ManagerJS.js, TeamAJS.js and TeamBJS.js, I don't want TeamAJS to be able to access TeamBJS but I want them both to be able to access ManagerJS.

A: All scripts on a page are evaluated in global scope. There is a single shared global scope per page.
You can prevent access by not defining stuff in global scope. You can use an IIFE to create a private scope for each script:
// myScript.js
(function() {

  // everything declared here is *local* to this function
  var localValue = 42;

  // we could expose values by explicitly creating global variables
  // (but there are other, more elaborate ways)
  window.globalValue = 21;

}());

Only expose values that you want other code / scripts to access. There are various ways to do that, one of them is the revealing module pattern.
See also What is the purpose of a self executing function in javascript?

A: It sounds like you want to use some kind of dependency injection system. There are quite a few options out there, including CommonJS, RequireJS, ES6 imports, and probably a lot of others.
Here's an example in CommonJS
// in TeamAJS.js...
// gain reference to Manager script
var Manager = require('./ManagerJS')

// do things with Manager
// note: can't access TeamBJS unless you require it as a dependency

module.exports = {
    // put methods or variables in here that you wish to expose to other modules
}

The RequireJS site has a nice article on modules


text:
Q: how to use $match in $cond else section in mongodb I want to use $match in $cond in Mongo query and my first try is :
Query in MongodbPlayground
but this error accrued:

query failed: (InvalidPipelineOperator) Unrecognized expression '$match'

Do you have any idea of using $match in $cond?
my expected result is :
[
  {
    "_id": "b4",
    "coll_C": "c2",        // the nearest date to "2020-08-01" that has coll_C value is: "2020-07-01" so added the "coll_C:"c2"
    "coll_D": "d1",
    "coll_E": "e2",
    "date": "2020-08-01"
  },
  {
    "_id": "b2",
    "coll_C": "c2",
    "coll_D": "d2",        // the nearest date to "2020-07-01" that has coll_D value is: "2020-06-01" so added the "coll_D:"d2"
    "coll_E": "e1",        // the nearest date to "2020-07-01" that has coll_E value is: "2020-05-01" so added the "coll_E:"e1"
    "date": "2020-07-01"
  },
  {
    "_id": "b1",
    "coll_C": "c1",
    "coll_D": "d2",
    "coll_E": "e1",        // the nearest date to "2020-06-01" that has coll_E value is: "2020-05-01" so added the "coll_E:"e1"
    "date": "2020-06-01"
  },
  {
    "_id": "b3",
    "coll_C": "c3",
    "coll_D": "d3",
    "coll_E": "e1",
    "date": "2020-05-01"
  }
]

*

*if it has each of the coll_C or coll_D or coll_E, show that.

*if it has not each of the coll_C or coll_D or coll_E, get the nearest coll_C or coll_D or coll_E base on date field from other documents.


text:
Q: Key length limit with Java Cryptography Extension I am aware that the keylenght in the Sun/Oracle JVM is limited for judical reasons. However as far as I understood the concept of the JCE (Java Cryptography Extension) is that a user can choose it's own security provider to compensate this limitation.
For this reason I am trying to operate the Bounce Castle as security provider in conjunction with the Orcale JDK 1.7.
In order to figure out the actual allowed keylegths I am using this code:
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.security.GeneralSecurityException;
import java.security.Provider;
import java.security.Security;

public class JCETest {
public static void main( String[] args ) throws GeneralSecurityException
{

    BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
    Security.addProvider(bouncyCastleProvider);

    System.out.println( "\nSecurity-Provider:" );
    for( Provider prov : Security.getProviders() ) {
        System.out.println( "  " + prov + ": " + prov.getInfo() );
    }
    System.out.println( "\nMaxAllowedKeyLength (for '" + Cipher.getInstance("AES").getProvider() + "' using current 'JCE Policy Files'):\n"
            + "  DES        = " + Cipher.getMaxAllowedKeyLength( "DES"        ) + "\n"
            + "  Triple DES = " + Cipher.getMaxAllowedKeyLength( "Triple DES" ) + "\n"
            + "  AES        = " + Cipher.getMaxAllowedKeyLength( "AES"        ) + "\n"
            + "  Blowfish   = " + Cipher.getMaxAllowedKeyLength( "Blowfish"   ) + "\n"
            + "  RSA        = " + Cipher.getMaxAllowedKeyLength( "RSA"        ) + "\n" );
}
}

The output for the Orcale JDK 1.7 and it's build in providers is:
Security-Provider:
  SUN version 1.7: SUN (DSA key/parameter generation; DSA signing; SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore; PKIX CertPathValidator; PKIX CertPathBuilder; LDAP, Collection CertStores, JavaPolicy Policy; JavaLoginConfig Configuration)
  SunRsaSign version 1.7: Sun RSA signature provider
  SunEC version 1.7: Sun Elliptic Curve provider (EC, ECDSA, ECDH)
  SunJSSE version 1.7: Sun JSSE provider(PKCS12, SunX509 key/trust factories, SSLv3, TLSv1)
  SunJCE version 1.7: SunJCE Provider (implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, Diffie-Hellman, HMAC)
  SunJGSS version 1.7: Sun (Kerberos v5, SPNEGO)
  SunSASL version 1.7: Sun SASL provider(implements client mechanisms for: DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM; server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)
  XMLDSig version 1.0: XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory)
  SunPCSC version 1.7: Sun PC/SC provider
  BC version 1.46: BouncyCastle Security Provider v1.46

MaxAllowedKeyLength (for 'SunJCE version 1.7' using current 'JCE Policy Files'):
  DES        = 64
  Triple DES = 128
  AES        = 128
  Blowfish   = 128
  RSA        = 2147483647

But when I apply BC as provider by switching to
Cipher.getInstance("AES", bouncyCastleProvider).getProvider()
It still shows me the limited key length (except for RSA) like this:
MaxAllowedKeyLength (for 'BC version 1.46' using current 'JCE Policy Files'):
  DES        = 64
  Triple DES = 128
  AES        = 128
  Blowfish   = 128
  RSA        = 2147483647

But when I change the JDK to openJDK, I get this output:
MaxAllowedKeyLength (for 'BC version 1.46' using current 'JCE Policy Files'):
  DES        = 2147483647
  Triple DES = 2147483647
  AES        = 2147483647
  Blowfish   = 2147483647
  RSA        = 2147483647

This astonishes me since I was under the impression that not the JDK but the security-provider limiting the key length. But my tests are showing that obviously the JDK is limiting the key length, no matter which provider I choose.
My question is: Did I got something wrong? Is there a way to unleash the keyleght with the Oracle JDK?

A: The key length limits are determined in the JCE, that is in the JRE, not in the provider. JCE checks the limits before it hands over to the provider.
The correct solution to this is to install the unlimited strength policy files. While this is probably the right solution for your development workstation, it quickly becomes a major hassle (if not a roadblock) to have non-technical users install the files on every computer. There is no way to distribute the files with your program; they must be installed in the JRE directory (which may even be read-only due to permissions).
Bouncy Castle does provide its own API though, which is separate from the JCE. This API does not enforce any key length limits. This is not an ideal solution either, as the API is totally different from the JCE and bound to BC, and BC is an extra 1MB library to distribute with your program.
Finally, there is also a reflection workaround described here in more detail.
OpenJDK does not have any key length limits, which is why they are all simply Integer.MAX_VALUE.


text:
Q: Any drawback of building website based on JSON API for Data Access Layer For instance, in ecommerce websites, we generally have two interfaces. One with which customer interacts and places orders and one with which company employees interact to manage orders and customers etc.
If we divide this website into two different websites. That means, two different projects all together, not dependent on each other. Only thing common between both websites will be the database. Both websites will be using the same database. Then what would be a good option for making Data Access Layer

*

*Each website have its own Database access code and entities.

*Link both website with a centralized layer - which exposes Read/Write to database using API based on JSON

In my opinion, second option would be better. As it cancels out dependency of database, any changes made in database need not to be made at two places. And many other benefits.
But my only concern is, how much it could hamper performance of overall system? Because in that case we are serializing and de-serializing objects and also making use of HTTP connections.
Could someone please throw some light over what would be benefits and drawbacks of API backed Data Access Layer in comparison to having own Database access code.

A: People disagree about the best architecture for this sort of thing, but one common and popular architectural guideline suggest that you avoid integrating two products at the database layer at all costs. It is simpler to have two separate apps and databases which can change independently of each other, and if you need to reference data from one in the other you should have some sort of event pipeline between the two configured on the esb.
And, you should probably have more than two back end databases anyway -- unless you have an incredibly simple system with only the two classes of objects you mentioned, you'll probably find that you have more than two bounded domains.
Also, if your performance requirements increase then you'll probably want to look at splitting the read and write sides of your services and databases, connecting the two sides through an eventing system of some sort, (maybe event-sourcing).
Before you decide what to do you should read Implementing Domain Driven Design by Vaughn Vernon. And, the paper on  CQRS by Martin Fowler. And the paper on event sourcing, also from Dr Fowler. For extra points you should also read Fowler on Microservices architecture.
Finally, on JSON -- and I'm a big fan -- but you should only use it at the repository interface if you're either using javascript on the back end (which is a great idea if you're using io.js and Koa) and the front end (backbone & marionette, please), or if you're using a data-source that natively emits json. If you have to parse it then it's only going to slow you down so use some format native to the data-source and its consumers, that way you'll be as fast as possible.

A: An API centric approach makes more sense as the data is standardised and gives you more flexibility by being usable in any language for one or multiple interfaces.
Performance wise this would greatly depend on the quality and implementation of the technology stack behind the API. You could also look at caching certain data on the frontend to improve page load time.
The guys over at moltin have already built a platform like this and I've had great success using it. There's already a backend dashboard and the response times are pretty fast too!


text:
Q: compare an image using ImageMagick and only get result true/false 0/1 We use a git repo for screenshots and always the images are marked changed by git, but with apply fuzz, there are no changes.
I use this script to compare images
do_compare()
{
     compare $color_flag $fuzz_flag $backgroundcolor_flag "$f1" "$f2" png:- | \
        montage -geometry +4+4 $backgroundcolor_flag "$f1" - "$f2" png:- >"$destfile" 2>/dev/null || true
}

but I want only know if there is a change in the image, with respect the fuzz, or not.
Does someone has an idea how to do so ?

A: You can do that in command line ImageMagick on Unix using
compare -metric ae -fuzz XX% image1 image2 null: 2>&1

-metric ae will return the number of pixels that do not match. So if the result is 0, then it matches perfectly within the specified -fuzz value.
For example, testing with fuzz = 0:
XX=0
test=`compare -metric ae -fuzz $XX% lena.png lena.jpg null: 2>&1`
if [ "$test" = "0" ]; then
echo "match"
else
echo "no match"
fi

no match

Testing with fuzz = 10%:
XX=10
test=`compare -metric ae -fuzz $XX% lena.png lena.jpg null: 2>&1`
if [ "$test" = "0" ]; then
echo "match"
else
echo "no match"
fi

match


text:
Q: Эффект появления/затухания в Java fx Не могу разобраться, какой bind нужно прикручивать к элементам Java FX, чтобы получить эффект появления затухания, влияя на него из Task()
При помощи opacity.
Task_for_Opacity task_for_opacity = new Task_for_Opacity();

calendar_main.opacityProperty().bind(task_for_opacity. ??????  );

Thread th2 = new Thread(task_for_opacity);th2.setDaemon(true);th2.start();

Такое вообще возможно ? или есть другие варианты.

A: Можно использовать анимацию
public void start(Stage stage) {
    Text msg = new Text("JavaFX animation is cool!");
    msg.setTextOrigin(VPos.TOP);
    msg.setFont(Font.font(24));
    Pane root = new Pane(msg);
    root.setPrefSize(500, 70);
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setTitle("Opacity");
    stage.show();

    /* Set up a Timeline animation */
    // Create the initial and final key frames
    KeyValue initKeyValue = new KeyValue(msg.opacityProperty(), 0.0);
    KeyFrame initFrame = new KeyFrame(Duration.ZERO, initKeyValue);
    KeyValue endKeyValue = new KeyValue(msg.opacityProperty(), 1.0);
    KeyFrame endFrame = new KeyFrame(Duration.seconds(3), endKeyValue);
    // Create a Timeline object
    Timeline timeline = new Timeline(initFrame, endFrame);
    // Let the animation run forever
    timeline.setCycleCount(Timeline.INDEFINITE);
    // Start the animation
    timeline.play();
}


text:
Q: How to include the GoogleMaps.apk file while extending MapActivity I need a help, In my eclipse, I have extended MapActivity to display google maps. Now if i run my program, there exists an error that

[2011-08-27 18:47:42 - GoogleMaps] Could not find GoogleMaps.apk!

and i dont have any other errors in program.
How to overcome this Bug?

A: Are you using the Android n.n Platform library? I think you need the Android n.n Google APIs library.
It can be downloaded via the Android SDK and AVD Manager.

A: If the app is run on a device that does not come with the Google Maps app, then there is nothing you can do. It is owned by Google, and if the device does not come with it you cannot provide it yourself.


text:
Q: How to configure internet for one 'super' router and four routers underneat In our home we have one Ziggo (dutch cable internet provider) router and we are stuck with one unfortunately.
However, as we have 4 households (appartements) that all should connect to this router, we wish to all have our own router and subnet so we can't access each others devices.
Now I was wondering, how would you configure the subnets and the DHCP on each device?
I was thinking of creating a different DHCP range for each router (as the main router doesn't need to know about the DHCP setup on the household routers)

Would love to hear your opinion :)

A: You can accomplish what you wish to do.
For each sub-router:
Hook up the WAN port to a LAN port on the Main Network.
Make sure the DHCP is enabled in the LAN section of each sub-router (that is normally the default way).
Make an IP Range for each sub-router. The exact IP range does not really matter - it can be different for organizational purposes.
Done this way, users on one sub-router cannot see users on another sub-router.
I have done this both ways in my setups here.

A: This is entirely possible:
By default most routers have DHCP enabled. Just connect each of them from their WAN-Port to one of the LAN-Ports on the Main Router.
The specific DHCP-Range of each of those routers does not matter (exception: see next paragraph) and even having the same range for the 4 routers should not be a problem since those routers are not aware of what is going on behind the other 3 routers (but having multiple ranges might make it easier to distinguish to which of the networks they are connected if some users use more than one of these networks).
I'm not entirely sure if this is necessary but from my understanding the DHCP Range of the Main Router should be different from the DHCP Range of the other 4 routers (even though those 4 can be the same). If this is not the case the "Sub-Routers" might be confused which network is talking to them.

This picture shows a mixture of both having different and the same DHCP Ranges on the sub-routers: Routers #2 and #3 both feature range 192.168.20.0/24 (192.168.20.1 - 192.168.20.255) but they are not shared between both routers. Devices on Router #2 can still not see devices on Router #3 and both routers will asssign the IPs independently.
I use two routers "in series" myself since I need the router supplied by my ISP but need  additional flexibility that my ISPs router doesn't offer.
Additional Information that might add a second option to your situation:
I don't need multiple routers but I have multiple VLANs (Virtual LANs; with different DHCP ranges) that prevent devices from talking from one VLAN to another (one VLAN for my own devices, one for guests etc.). I don't know the specific situation you are in but if the networks are managed by one person only anyway and privacy is not to big of a concern you could also add just one "high end" router and then add multiple VLANs and use a managed switch to split them up for the different households. Buying one good router, a managed switch and four (or potentially less; you might be able to have multiple SSIDs/ Wifi-names per access point) access points could actually turn out cheaper but this depends heavily on your specific situation.


text:
Q: Entity Framework updating many to many I am trying to find the suitable form of updating a many to many relationship but i am find some issues on it.
The application is an asp.net mvc with simple injector(set up per context)
I have an entity People which has an IEnumerable and also i have a entity Team which has an IEnumerable.
The People entity has some other fields like Description, Email, etc and in its View, there are some check boxes so the user can choose the Teams.
I had tried to search on the net for the best approach for updating a many to many relationship and all that i found was deleting everything in the third table that is created and then add the Teams again.
Under is what i am trying to do, but i am getting pk's already exists. I know it is happening because firstly i load the People entity with Find method(to remove the list of Teams inside a foreach) and after i try to Attach(when the error happens) the modified object to set it's State to Modified.
        public override void Modify(People obj)
    {
        var ppl = SearchById(obj.Id);

        if (ppl.Teams.Count > 0)
        {
            foreach (var team in ppl.Teams.ToList())
            {
                ppl.Teams.Remove(team);
            }
        }

        var entry = lpcContext.Entry(obj);

        if (lpcContext.Entry(obj).State == EntityState.Detached)
            dbSet.Attach(obj);

        entry.State = EntityState.Modified;
    }

To air it out some things, i am using the Unit Of Work pattern, so i SaveChanges later.
Are there any other approach or i have to remove the Teams one by one, SaveChanges and after that, update the object and SaveChanges again?

A: Unfortunately, working with detached entities isnt that straight forward in EF (yet). Attach() in EF will work for connected entities only. That means if you load an object from DB, pass it on to a view (or page is asp.net). When you read the object back from that view/page, EF will not be tracking that object anymore. If you now try to use Attach(), you will get an error that the key already exists in the DBContext. To workaround this, you need to find the entry and make changes to the entity using SetValues(). Something like this:
public virtual void Update(T entity)
        {
            DbEntityEntry dbEntityEntry = DbContext.Entry(entity);

            if (dbEntityEntry.State == EntityState.Detached)
            {
                var pkey = _dbset.Create().GetType().GetProperty("Id").GetValue(entity);//assuming Id is the key column
                var set = DbContext.Set<T>();
                T attachedEntity = set.Find(pkey);
                if (attachedEntity != null)
                {
                    var attachedEntry = DbContext.Entry(attachedEntity);
                    attachedEntry.CurrentValues.SetValues(entity);
                }
            }
        }

Please note that this will ignore any nested objects. Hence, you should make DB trip, and compare the object returned from DB to find out if you should invoke Add, Update or Delete on each child object. This is the best workaround I could find when working with disconnected objects in EF. I guess nHibernate doesnt have this bug. Last I read about this, Microsoft was going to work on this after EF 6.x. So, we'll have to wait for this, I guess. Please go through the below article to understand the issue (and possible solutions) in length:
http://blog.maskalik.com/entity-framework/2013/12/23/entity-framework-updating-database-from-detached-objects/
To talk about your specfic scenario, you should make a DB hit and find out if any new teams were selected or some existing team was dropped and call add or delete as appropriate by comparing the Team collection of People object returned by DB vs People object returned from view/page. To update the People object itself, you can use the Update() as given above.


text:
Q: Airport Extreme Name Resolution I have a little issue with my airport extreme. I'm using the device in my corporate network which has two DNS server for resolving intern and external names.
When I do an nslookup "public adresse" (such as www.google.com), everything works fine.
...But, when I try to resolve an internal name, for exemple bardo1, I get:
;;SERVFAIL reply from XXX.XXX.XXX.XXX trying next server
;;connection timed out; no servers could be reached

When I try nslookup internalservername my.internal.dns.server everything works thing.
Where is the problem ??? I don't get it.
Is it because apple uses a different way to resolve names then microsoft ?
How can I fix that on the router ? Not on client side...
My PC Config IP: 10.0.1.3/32 Gateway: 10.0.1.1 DNS: 10.0.1.1

Airport Extreme IP WAN: 172.16.1.117 DNS1: x.x.x.13 DNS2: x.x.x.45 domain: mydomain.local

A: Apple's DNS resolution expects a tiered solution, so you will want to simply point the router and clients to the internal DNS.
That DNS will answer all queries for it's internal responses and refer/forward requests outside it's authority to the outside DNS of your choosing.
In short, you will either need to change your internal DNS or set up a third DNS to know what requests to handle internally and which externally as the AirPort wasn't designed to do that choosing for you.
Here's how you would set up OS X server DNS to do forwarding - it's a simple pane where you place the external addresses.

A: Try swapping the order of the DNS servers on the AirPort Extreme.


text:
Q: percentage symbol to decimal numbers in .net Using .net
To add a $ symbol for numbers I did
Texbox1.Text.Format = "C"
How to add % symbol at the end of each integer to represent a string in textbox.

A: Standard Numeric Format Strings; in particular: the Percent ("P") Format Specifier.

A: double number = 1.2;
lbl.Text = number.ToString("P");

Produces: 120.00%
double number = 0.12;
lbl.Text = number.ToString("P");

Produces: 12.00%
So if you have a percentage already:
double number = 12;
lbl.Text = (number / 100).ToString("P");

Produces: 12.00%


text:
Q: Pyspark UDF column on Dataframe I'm trying to create a new column on a dataframe based on the values of some columns. It's returning null in all cases. Anyone know what's going wrong with this simple example?
df = pd.DataFrame([[0,1,0],[1,0,0],[1,1,1]],columns = ['Foo','Bar','Baz'])

spark_df = spark.createDataFrame(df)

def get_profile():
    if 'Foo'==1:
        return 'Foo'
    elif 'Bar' == 1:
        return 'Bar'
    elif 'Baz' ==1 :
        return 'Baz'

spark_df = spark_df.withColumn('get_profile', lit(get_profile()))
spark_df.show()

   Foo  Bar  Baz get_profile
    0    1    0        None
    1    0    0        None
    1    1    1        None

I would expect that the get_profile column would be filled out for all rows.
I also tried this:
spark_udf = udf(get_profile,StringType())

spark_df = spark_df.withColumn('get_profile', spark_udf())
print(spark_df.toPandas())

to the same effect.

A: The udf has no knowledge of what the column names are. So it checks each of your conditions in your if/elif block and all of them evaluate to False. Thus the function will return None.
You'd have to rewrite your udf to take in the columns you want to check:
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

def get_profile(foo, bar, baz):
    if foo == 1:
        return 'Foo'
    elif bar == 1:
        return 'Bar'
    elif baz == 1 :
        return 'Baz'

spark_udf = udf(get_profile, StringType())
spark_df = spark_df.withColumn('get_profile',spark_udf('Foo', 'Bar', 'Baz'))
spark_df.show()
#+---+---+---+-----------+
#|Foo|Bar|Baz|get_profile|
#+---+---+---+-----------+
#|  0|  1|  0|        Bar|
#|  1|  0|  0|        Foo|
#|  1|  1|  1|        Foo|
#+---+---+---+-----------+

If you have a lot of columns and want to pass them all (in order):
spark_df = spark_df.withColumn('get_profile', spark_udf(*spark_df.columns))

More generally, you can unpack any ordered list of columns:
cols_to_pass_to_udf = ['Foo', 'Bar', 'Baz']
spark_df = spark_df.withColumn('get_profile', spark_udf(*cols_to_pass_to_udf ))

But this particular operation does not require a udf. I would do it this way:
from pyspark.sql.functions import coalesce, when, col, lit

spark_df.withColumn(
    "get_profile",
    coalesce(*[when(col(c)==1, lit(c)) for c in spark_df.columns])
).show()
#+---+---+---+-----------+
#|Foo|Bar|Baz|get_profile|
#+---+---+---+-----------+
#|  0|  1|  0|        Bar|
#|  1|  0|  0|        Foo|
#|  1|  1|  1|        Foo|
#+---+---+---+-----------+

This works because pyspark.sql.functions.when() will return null by default if the condition evaluates to False and no otherwise is specified. Then the list comprehension of pyspark.sql.functions.coalesce will return the first non-null column.
Note this is equivalent to the udf ONLY if the order of the columns is the same as the sequence that's evaluated in the get_profile function. To be more explicit, you should do:
spark_df.withColumn(
    "get_profile",
    coalesce(*[when(col(c)==1, lit(c)) for c in ['Foo', 'Bar', 'Baz'])
).show()


text: Q: autoclose for alerts angular SPA I use this article to create app notifications. I'd like to add autoclose alerts but have no idea how to do it. When I try to add timeout in Alert constructor object it doesn't work. Perhaps some of you know how to check trigger timeouts for each alert object in AlertComponent?


text:
Q: Unable to install cURL 7.54.0 on MacOS Catalina 10.15.7 I'm trying to install a specific version of cURL instead of the latest version (through homebrew). I've extracted Curl 7.54.0 source and executed the following commands
./configure --prefix=$HOME/curl
make
make install

Getting error in second command as follows
connect.c:1086:12: error: 'connectx' is only available on macOS 10.11 or newer
      [-Werror,-Wunguarded-availability]
      rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
           ^~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/usr/include/sys/socket.h:723:5: note:
      'connectx' has been marked as being introduced in macOS 10.11 here, but
      the deployment target is macOS 10.8.0
int connectx(int, const sa_endpoints_t *, sae_associd_t, unsigned int,
    ^
connect.c:1086:12: note: enclose 'connectx' in a __builtin_available check to
      silence this warning
      rc = connectx(sockfd, &endpoints, SAE_ASSOCID_ANY,
           ^~~~~~~~
1 error generated.
make[2]: *** [libcurl_la-connect.lo] Error 1
make[1]: *** [all] Error 2
make: *** [all-recursive] Error 1

Although current MacOS version is higher than 10.11, unable to determine the rootcause of this error.

A: For anyone who brushes upon this issue in the future. The easy solution is to pass in -Wno-error in CFLAGS.
The final command is make CFLAGS=-Wno-error.


text:
Q: Java Class Boolean not accepting null I am working on a react application with a Java 8 backend. I'm trying to export a filtered table to a CSV file. I have been able to successfully export a table that is filtered only by an array of strings or single value strings. I am having trouble incorporating filters that are Booleans, BUT ONLY when those filters are left null. If the user does not need to filter the table by a boolean column, the value for that filter field is equal to undefined.  A value of undefined cannot be passed through the web service request. To deal with this, I have a ternary operator set like this:
Boolean === undefined ? null : BooleanValue
However, I receive null errors
Failed to bind request element: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Boolean'; nested exception is java.lang.IllegalArgumentException: Invalid boolean value [null]
I'm guessing by the reference to java.lang.string that null is getting passed as a string value, however, when I try to account for this in my webservice controller it fails before I can see and debug the value.
NOTE: I am using the class Boolean, not the primitive type boolean (lower case). Its my understanding that the class Boolean should be able to have a value of null but that does not seem to be the case here. Is there a way to do this?
React (Get Values being filtered, if filter not set, change undefined to null):
  webservice.Loans.dashboard.filteredCSV(
  LoanTable.status,
  LoanTable.engineerEmail,
  LoanTable.issues === undefined ? null : LoanTable.issues).then(/*Do Stuff*/)

webservice controller (debugger won't get this far if value = null but will if value = true or false"):
@RequestMapping(value = "/filteredCSV.json")
@ResponseBody
public WebserviceResponse<?>filteredCSV(
    @RequestParam(value="status") ArrayList status,
    @RequestParam(value="engineerEmail") ArrayList engineerEmail,
    @RequestParam(value="issues") Boolean issues){

   if(issues.equals("null")){
        issues = new Boolean(null);
    }

return service.filteredCSV(status, engineerEmail, issues);
}

Is there a way to deal with this?

A: Set required to false then the issues parameter will be nullable.
@RequestMapping(value = "/filteredCSV.json")
@ResponseBody
public WebserviceResponse<?>filteredCSV(
    @RequestParam(value="status") ArrayList status,
    @RequestParam(value="engineerEmail") ArrayList engineerEmail,
    @RequestParam(value="issues", required=false) Boolean issues){

     return service.filteredCSV(status, engineerEmail, issues);
}


text:
Q: Add lang argument in tweeter query I have this code and i want to retrieve tweets about seminars in english.
this is my code. please how can i add parameters to my query ?
i have tried to add parameters with add_argument but it does not work.
import config

class TwitterListener(StreamListener):

    def __init__(self, output_dir, query):
        valid_chars = '-_.%s%s' % (string.ascii_letters, string.digits)
        query_fname = ''.join(c if c in valid_chars else '_' for c in query)
        self.outfile = "%s/stream_%s.json" % (output_dir, query_fname)

    def on_data(self, status):
        try:
            with open(self.outfile, 'a') as f:
                f.write(status)
        except BaseException as e:
            print("Error on_status: %s" % str(e))
            time.sleep(5)

    def on_error(self, status_code):
        if status_code == 420:
            print(status_code)
            return False

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Twitter Scraper")
    parser.add_argument("-q", "--query", dest="query", help="Filter the twitter stream with this query.",
                        default='-')
    parser.add_argument("-d", "--output-dir", dest="output_dir", required=True,
                        help="Path to the directory in which you want to store the tweets.")
    args = parser.parse_args()
    authentication = OAuthHandler(config.consumer_key, config.consumer_secret)
    authentication.set_access_token(config.access_token, config.access_secret)
    api = tweepy.API(authentication)

    twitter_stream = Stream(authentication, TwitterListener(args.output_dir, args.query))
    twitter_stream.filter(track=[args.query])


text:
Q: Integral coordinate change I'm trying to compute
$$\int_0^n\int_0^n\int_0^n\frac{\sin(x-y)\sin(y-z)\sin(x-z)}{(x-y)(x-z)(y-z)}\,dx \,dy \,dz$$
I want to make new coordinates as $a=x-y$, $b= y-z$ (so $x-z=a+b$) and $c=z$. I'm a bit confused about the limits of the integral, can anyone help?


text:
Q: Parse JSON object in SAS macro - Part 2 - using OUTPUT function to handle nested values This question is related to:  prior question link
I have a JSON file that looks like:
    [
      {
        "rxnorm_id": "999999999",
        "drug_name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "plans": [
          {
            "plan_id_type": "xxxxxxxxxxxxx",
            "plan_id": "999999999999999",
            "drug_tier": "xxxxxxxxxxxxxxx",
            "prior_authorization": false,
            "step_therapy": false,
            "quantity_limit": false
           },

I am able to import every line into SAS that has 'rxnorm_id and drug_name using this code:
    >
    filename data url 'http://stg-oh-medicaid.molinahealthcare.com/JSON/Drugs_Molina_Healthcare.json';
    data formularies;
    infile data lrecl = 32000 truncover scanover;
    input   @'"rxnorm_id": "' rxnorm_id $255.
    @'"drug_name": "' drug_name $255.
    @'"plan_id_type": "' plan_id_type $255.
    @'"plan_id": "' plan_id $255.
    @'"drug_tier": "' drug_tier $255.
    @'"prior_authorization": ' prior_authorization $255.
    @'"step_therapy": ' step_therapy $255.
    @'"quantity_limit": ' quantity_limit $255.;
    rxnorm_id = scan(rxnorm_id,1,'",');
    drug_name = scan(drug_name,1,'",');
    plan_id_type = scan(plan_id_type,1,'",');
    plan_id = scan(plan_id,1,'",');
    drug_tier = scan(drug_tier,1,'",');
    prior_authorization = scan(prior_authorization,1,'",');
    step_therapy = scan(step_therapy,1,'",');
    quantity_limit = scan(quantity_limit,1,'",');
    run;

But, I want to pick up all of the values in the 'plans' nest that are in between the rxnorm and drug name values.  Someone suggested using the OUTPUT option in SAS to see the missing rows.  Anyone got a good fix to my code to do this?
Thanks

A: As of 9.4, the best way to parse JSON in SAS is using PROC GROOVY. That is what I recommend. You can also do it with DS2. If you are adventurous, and on 9.4m3, you can also use PROC LUA. That is what I would try, since it allows you to manipulate SAS datasets easily.
That being said, if you can rely on the simple structure of your example, then you can select only the lines that have fields and output them in the format you wanted using regular expressions in data step:
data want;
    infile 'c:/tmp/json_snippet.txt';
    length field $20 data $100;
    keep field data;
    retain re;

    input;
    if _n_ = 1 then do;
        re = prxparse('/"(.*?)": "?(true|false|.*?(?="))/');
    end;

    if prxmatch(re,_infile_); /* grep only matching lines */

    call prxposn(re,1,start,len);
    field = substr(_infile_,start,len);
    call prxposn(re,2,start,len);
    data  = substr(_infile_,start,len);
run;

Caveat emptor: A wise person said that when you solve a problem using regular expressions, now you have two problems :). Among the things that can go wrong:

*

*line breaks

*using ' instead of " for string delimiters

*lengths

*mixed types


text:
Q: Struts 2 Action error I have a problem with struts 2 action error while forwarding from one action to another action .The problem lies as there is a interceptor in between and we are doing a redirect action
Can I some how copy the action error from old action to current action
or save the action error in the session?
It will highly appreciable if some one gives a working peice of code
Thanks

A: Your result type is currently "redirect" or "redirectAction" these reset the value stack use "chain". Although you should generally look for a solution that does not use any of the aforementioned result types...

A: I am also facing same problem for showing successfully saved message. Here's what I got while googling the solution. http://glindholm.wordpress.com/2008/07/02/preserving-messages-across-a-redirect-in-struts-2/
Hope it helps you.


text:
Q: iis7 forms authentication is missing? I do not have the option for form Authentication in IIS Manager under IIS=>Authentication. I do have the following options:
1)Anonymous Authentication
2)ASP.NET Impersonation
3)basic Authentication
according to this, forms Authentication is needed to provide for an application
please help me to fix it.

A: One thing you could try:
Make a backup of 'C:\Windows\System32\inetsrv\config\administration.config'.
In
<moduleProviders>

find the line
<add name="Impersonation" type="Microsoft.Web...

and make a copy of it just below, then replace 'ImpersonationModuleProvider' with 'FormsAuthenticationModuleProvider' in the new line.
further down in the file in the section:
<location path=".">
    <modules>

check whether there is an entry:
<add name="FormsAuthentication" />

and if not, add it.
I don't know whether this will fix your problem or why these entries are missing in the first place. But it is worth a try.
Otherwise I would re-install IIS.


text:
Q: OAuth2 to Sandbox community with `refresh_token` - requested scope not available I am using Salesforce Mobile SDK for iOS which uses OAuth 2.0 User-Agent Flow.
When authenticating against a community, the URL looks like so
https://<Community>/<OptionalPath>/services/oauth2/authorize?client_id=<ClientId>&redirect_uri=https://login.salesforce.com/services/oauth2/success&display=touch&device_id=<iOS VendorId>&response_type=token&scope=full%20refresh_token

The connected app callback uri is set to https://login.salesforce.com/services/oauth2/success
This works fine when connecting to Community in Production.
However, if i connect to community in my sandbox, i get an error

error=invalid_scope&error_description=the%20requested%20scope%20is%20not%20available

If i take out refresh_token scope, the redirect to Login works just fine.
However, the SDK requires a refresh_token to work.
What can i do without changing redirect uri (as this is an app we already shipped to thousands of users) so that the app works with Sandbox community?


text:
Q: TypeError: Cannot read properties of undefined (reading 'firstname') I'm new to react and node (express)
I'm trying to get some date from a database ('firstName' and 'lastName'),concatenate and display them in a select tag.
There is what I do:
The request I sent to the database in my node file:
app.get("/employeesName", (req, res) => {
  db.query("SELECT firstname , lastname FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

The get request in react:
const [employeeList, setEmployeeList] = useState([]);
  useEffect(() => {
    const  getEmployeesNames = () => {
      Axios.get("http://localhost:3001/employeesName").then((response) => {
        setEmployeeList(response.data);
      });
      };
          getEmployeesNames();

  },[])

I tried something like that to diplsay my data in the select tag:
 <select>
        <option value="">{employeeList[0].firstname+" "+employeeList[0].lastname}</option>
        <option value="">{employeeList[1].firstname+" "+employeeList[1].lastname}</option>
 </select>

When I do that in vs code It works,but just when I refresh my page In the browser I get that error (Cannot read properties of undefined),I think that employeeList is empty on first render. Which Is reasonable as my initial state is an empty array (useState([]);),I tried to initialize
my useState with something like that useState([{firstname: 'test', lastname: 'test2'}]); but still get the error
What should be done to avoid this error?

A: useState([{firstname: 'test', lastname: 'test2'}])

This array has one element so employeeList[1] will be falsy

You can just conditionally render the select:
{
    employeeList.length > 0 && (
        <select>
            {
                employeeList.map((emp, index) => <option key={index} value={index}>{emp.firstname + " " + emp.lastname}</option>)
            }
        </select>)
}


text:
Q: Super in Python I have been working in django CBV but i am stuck and cannot reslove it i also googled that thing but nothing much i get it
sometimes in classes we use super
class ArticleCounterRedirectView(RedirectView):
permanent = False
query_string = True
pattern_name = 'article-detail'

def get_redirect_url(self, *args, **kwargs):
    article = get_object_or_404(Article, pk=kwargs['pk'])
    article.update_counter()
    return super().get_redirect_url(*args, **kwargs)

class ArticleCounterRedirectView(RedirectView):
permanent = False
query_string = True
pattern_name = 'article-detail'

def get_redirect_url(self, *args, **kwargs):
    article = get_object_or_404(Article, pk=kwargs['pk'])
    article.update_counter()
    return super(ArticleCounterRedirectView,self).get_redirect_url(*args, **kwargs)

we use super to to call the parent class then in one example we give no arguments and in another we give it two arguements please can someone help me out in this

A: super().get_redirect_url(*args, **kwargs)

And
super(ArticleCounterRedirectView,self).get_redirect_url(*args, **kwargs)

Both do the same thing in this case essentially,
The first one is the new syntax in python 3. If you want to explicitly bypass the MRO then you can use the second method to do that.
Hope you understood.


text:
Q: PHP Error: Cannot use object of type stdClass as array in Laravel Using Laravel 6 Getting error

Cannot use object of type stdClass as array

I converted my query to an array.
$filterQuery = DB::table('view_vi_properties');
$filterQuery->select('id','name','bedrooms','max_guests','min_stay','private_pool','private_pool_text','price','security_deposit','pets_allowed','latitude','longitude','pro_address1','pro_address2','pro_city','country','primary_image','slug','rooms');
$filterQuery->whereNotIn('id', explode(',', $comma_property_id));
$filterQuery->whereNotIn('rooms_id', explode(',', $comma_room_id));
$filterQuery->whereNotIn('block_name', explode(',', $comma_block_name));
$filterQuery->where('status', 1)->groupBy('id');
$filterQuery->orderBy('name', 'asc');
$results = $filterQuery->get()->toArray();
print_r($results);

and I'm getting an array but the error is still showing
Array   (
    [0] => stdClass Object
        (
            [id] => 4
            [name] => Candolim
            [bedrooms] => 5
            [max_guests] => 9
            [min_stay] => 3
            [primary_image] => 1646566320.jpg
            [slug] => candolim
            [rooms] => 7 BR
        )
   )

A: $filterQuery->get() returns you a Collection of StdClass items, and toArray() converts only Collection object, but not items inside of it (not working recursively as you want).
The easiest way is to change DB::table('view_vi_properties'); to corresponding Eloquent model, lets assume you model is ViewViProperties.In this case $filterQuery->get() will return a Collection of ViewViProperties class and toArray() will be able to convert all data to array recursivley.
If you don't want to use Eloquent then you need to convert each item separately or refer to them with object syntax like $results[0]->id.

A: The issue mentioned above is correct because toArray() converted the parent objects to an array, but not child objects. To convert child objects to array also can be achieved through:
$result  = json_decode(json_encode($results), true);


text:
Q: reading file to check for same number of delimiters I have created a method which reads a file line by line and checks if they all contain the same number of delimiters (see below code). The trouble with the solution is that it works on a line per line basis. Given that some of the files I am dealing with are gigabytes in size, this will take a while to process, is there a better solution which will 1) validate whether all lines contain the same number of delimiters 2) not cause any out of memory issues. Thanks in advance.
def isValid(fileName):
    with open(fileName,'rb') as infile:
        for lineNumber,line in enumerate(infile,1):
            count = line.count(',')
            if lineNumber > 1 and prevCount != count:
                # this line does not contain the same number of delimiters
                return False
            prevCount = count
    return True

A: You can use all instead and a generator expression:
with open(file_name) as your_file:
    start = your_file.readline().count(',') # initial count
    print all(i.count(',') == start for i in your_file)

A: I propose a different approach (without code):
1. read the file as binary, and in chunks of, say, 64 KB
2. count the number of end-of-line tokens in the chunk
3. count the number of delimiters in the chunk but only up to the position of the last EOL token
4. if both number do not divide evenly, stop and return False
5. At EOF, return True
As you'd have to handle the 'overlap' between the last EOL token and the end of the chunk the logic is a bit more complicated than the 'brute-force' approach. But in dealing with GBs it might pay off.

A: I just noticed that - if you would want to stick with simple logic - the original code can be deflated a bit:
def isValid(fileName):
with open(fileName,'r') as infile:
    count = infile.readline().count(',')
    for line in infile:
        if line.count(',') != count:
            return False
return True

There is no need to keep the previous line's count as one single difference will decide it. So keep only the delim count of the first line.
Then, the file needs to be opened as a text file ('r'), not as a binary.
Lastly, by prefetching the very first line just before the loop we can discard the call to enumerate.


text:
Q: Differences between SWFAddress and JSInterface... which to choose? What are the differences between SWFObject/SWFAddress and JSInterface?
JSInterface has a lot more functionality but SWFAddress seems to be the standard, so I'm wondering what you choose to use and why, and if you could use both of them.
Can you even do SWFAddress-like things with JSInterface?  I can't seem to find out how to do "back", "forward", and to update/listen-for the url changes...

A: SWFAddress is the standard for deep linking in flash.  Its tried and tested and used in a lot of production quality software.  If all you're looking for is deep linking and using the browser provided buttons and bookmarking, then go with SWFAddress.
If you need more communication between flash and the browser and want a simplified and more robust ExternalInterface go with JSInterface.
Heres a good explination of the main features of JSInterface: http://actualwave.com/lab/pack/JSInterface_presentation_en.swf

A: SWFAddress is only deep-linking library that uses JavaScript only for this.
JSInterface is library that helps you do anything what you can do with JavaScript but inside Flash.
So, if you need only deep-linking - SWFaddress is your choise, but if you need extended JavaScript fearutes, like DOM manipulations, or data exchange with Ajax application, or external resource management(you can load data from many resources at a time), or environment control(window size and placement), SWFAddress can't give you tools to do this.


text:
Q: GDATA and youtube, Get all videos on a playlist Does anyone know how to get all the videos from a playlist ?
E.g from this playlist
https://gdata.youtube.com/feeds/api/playlists/454A0274C1223C90?v=2
it caps at 10 results
I tried &max-results=1000 but that 404'ed

A: try asking for 50 results at a time ( max allowed )
GET /feeds/api/playlists/454A0274C1223C90?v=2&&max-results=100&fields=entry/id,entry/title&key=4{your-key} HTTP/1.1
Host: gdata.youtube.com
Authorization: OAuth ya29.AHES6ZQMwDjrUKh8RLysv-ZzF3DaUmg0XmG0jtVcWdSA0A
HTTP/1.1 400 Bad Request
status: 400
content-length: 246
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
expires: Sat, 28 Apr 2012 16:29:01 GMT
x-google-cache-control: remote-fetch
server: GSE
via: HTTP/1.1 GWA
x-gdata-user-country: US
cache-control: private, max-age=0
date: Sat, 28 Apr 2012 16:29:01 GMT
x-frame-options: SAMEORIGIN
content-type: application/vnd.google.gdata.error+xml
-content-encoding: gzip
<errors xmlns='http://schemas.google.com/g/2005'><error><domain>GData</domain>InvalidRequestUriException<internalReason>Max-results value is too high. Only up to 50 results can be returned per query.

GET /feeds/api/playlists/454A0274C1223C90?v=2&&max-results=50&fields=entry/id,entry/title&key=${key} HTTP/1.1
Host: gdata.youtube.com
Authorization: OAuth ya29.AHES6ZQMwDjrUKh8RLysv-ZzF3DaUmg0XmG0jtVcWdSA0A
HTTP/1.1 200 OK
status: 200
gdata-version: 2.1
content-length: 6703
via: HTTP/1.1 GWA
content-location: https://gdata.youtube.com/feeds/api/playlists/454A0274C1223C90?v=2&&max-results=50&fields=entry/id,entry/title&key=w1Q
x-content-type-options: nosniff
expires: Sat, 28 Apr 2012 16:32:08 GMT
vary: Accept, X-GData-Authorization, GData-Version
x-google-cache-control: remote-fetch
server: GSE
last-modified: Sat, 28 Apr 2012 10:46:07 GMT
x-xss-protection: 1; mode=block
etag: W/"A04CRn47eCp7I2A9WhVWFk0."
cache-control: private, max-age=300, no-transform
date: Sat, 28 Apr 2012 16:32:08 GMT
x-frame-options: SAMEORIGIN
content-type: application/atom+xml; charset=UTF-8; type=feed
-content-encoding: gzip
x-gdata-user-country: US


text:
Q: How to compare date from current year with column from database I'm trying get data from database dependent on  this condition:
 if($now < "'.$current_year . '-09-15")

I have to display data for last study session.
I want to check if current date is less than 15.September current year and if it is to display data from database for study session.
But it's not showing correct result.
My code is:

<?php
 $date = new DateTime("now");
 $now=$date->format('Y-m-d');
 $current_year = $date->format('Y');
 $last_year =  $current_year -1;

 if($now < "'.$current_year . '-09-15") {

      $this->db->where('student_surveys.created_at < "'.$current_year . '-09-15" AND student_surveys.created_at > "'.$last_year . '-09-15"');
 }
 else {

      $this->db->where('student_surveys.created_at > "'.$current_year . '-09-15"');
 }

A: There's an error in the formation of your date in the compare statement. When I tried to run the code, with a "true" printed in the if portion and "false" in the else, it returned false (which was incorrect output).
Try this:
<?php
 $date = new DateTime("now");
 $now=$date->format('Y-m-d');
 $current_year = $date->format('Y');
 $last_year =  $current_year -1;
 $yourdate = $current_year."-09-15";
 if($now < $yourdate) {
      $this->db->where('student_surveys.created_at < "'.$current_year . '-09-15" AND student_surveys.created_at > "'.$last_year . '-09-15"');
 }
 else {
      $this->db->where('student_surveys.created_at > "'.$current_year . '-09-15"');
 }
?>


text:
Q: Font family select is not applying at the same time, its getting updated when I select next font family this is my select option in html

                    <select id="selected_font_id" data-bind="value: getObservable('selected_font'),
                            event:{ change: changeMessageFontStyle}">
                        <option value="" disabled selected hidden>Please select the font</option>
                        <option value="Freestyle Script">Freestyle Script</option>
                        <option value="Arriel">Ariel</option>
                        <option value="Calibri">Calibri</option>
                        <option value="Times New Roman">Times New Roman</option>
                        <option value="French Script MT">French Script MT</option>
                        <option value="Lucida Handwriting">Lucida Handwriting</option>
                        <option value="Sylfaen">Sylfaen</option>
                    </select>

this is my preview to show the font change

To:

        Message:

        From:

this is my JS with JQuery
changeMessageFontStyle: function () {
            this.model.getObservable('selected_font').subscribe(function (value) {
                //alert(value);
                //alert('changeMessageFontStyle');
                $("#selected_font_id").change(function () {
                    //alert($(this).val());
                    $('.gift-message-preview').css("font-family", value);

                });

            });
        },

can anyone help?

A: You seem to have added more complexity to this than is needed.
The simplest way to achieve this will be to use the style binding.
Something like this should do the job:

This will automatically update the font family whenever the selected_font observable changes.
Using jQuery within Knockout isn't advisable as it's easy to run into conflicts/problems like you have here.


text:
Q: Connect device to Windows 7 hostednetwork -> No Internet Access needed I 'm looking for a clean way to communicate between an Android/iOS phone and a Windows 7 laptop. No need for internet connection, just a way for a TCP connection between the phone and the laptop.
I have enabled the hosted network, but there is no connectivity. The laptop has 192.168.173.1 and the phone 192.168.173.3 but ping fails and connections between the two devices fail.

A: Goto Control Panel\Network and Internet\Network and Sharing Center\Advanced sharing settings
Turn on the requested items and specially check Enable file sharing for devices that use 40- or 56- bit encryption


text:
Q: Simpler or shorter way to simplify expression $(16^{2} \times 64^{3})\div1024^{2}$ for a power I am studying about powers for a discipline in college and the teacher asked me to simplify the following expression to transform it into the form of a single power,
$$
(16^{2} \times 64^{3})\div1024^{2}
$$
I can simplify to,
$$
2^{6}
$$
But, take many steps to get this result,
$$
(16^{2} \times 64^{3})\div1024^{2} \\ \implies(16\times16)\times(64\times64\times64)\div(1024\times1024) \\ \implies 256 \times262144\div1048576\\ \implies67108864\div1048576=64\\ 64\implies2^{6} \\ (16^{2} \times 64^{3})\div1024^{2} \implies 2^{6}
$$
However I would like to know if there is a shorter or simpler way to simplify expression $(16^{2} \times 64^{3})\div1024^{2}$ ?

A: \begin{align}
& (16^2 \times 64^3)\div1024^2 \\[10pt]
= {} & (2^4)^2 \times (2^6)^3 \div (2^{10})^2 \\[10pt]
= {} & 2^8 \times 2^{18} \div 2^{20} \\[10pt]
= {} & 2^{8+18-20}.
\end{align}

A: Too complicated. Notice that:

*

*$16 = 2^4$;

*$64 = 2^6$;

*$1024 = 2^{10}$.

Therefore:
$$\begin{array}[rcl]
((16^{2} \times 64^{3})\div 1024^{2} & = & (2^{8} \times 2^{18})\div 2^{20} \\
& = & 2^{26}\div 2^{20} = 2^6 = 64. \\
\end{array}$$

A: By writing these out as powers of primes (namely $2$), we have
$$
\frac{16^{2} \times 64^{3}}{1024^{2}} = \frac{(2^{4})^{2} \times (2^{6})^{3}}{(2^{10})^{2}} = \frac{2^{8}\times2^{18}}{2^{20}} = \frac{2^{26}}{2^{20}} = 2^{6}.
$$

A: Notice that all can be represented in powers of 2
$$16^2=(2^4)^2=2^8$$
$$64^3=(2^6)^3=2^{18}$$
$$1024^2=(2^{10})^2=2^{20}$$
$$\frac{2^8\cdot 2^{18}}{2^{20}}=\frac{2^{26}}{2^{20}}=2^6$$

A: $$(16^{2} \times 64^{3})\div1024^{2}=2^8 \times 2^{18} /2^{20} =2^6=64$$


text:
Q: FilterExpression Does Not Work? Why? ObjectDataSource1.FilterExpression = "userid LIKE '{0}' AND action LIKE '{1}'";
    ObjectDataSource1.FilterParameters.Add("userid", ddlUsers.SelectedValue);
    ObjectDataSource1.FilterParameters.Add("action", ddlAction.SelectedValue);
I wirte like this code.
when I run it grid view is empty. BUT, when I write and run it works good.
ObjectDataSource1.FilterExpression = "userid LIKE '{0}' AND action LIKE '{Login}'";
ObjectDataSource1.FilterParameters.Add("userid", ddlUsers.SelectedValue);
ObjectDataSource1.FilterParameters.Add("action", ddlAction.SelectedValue);

Without parameters (action)
its shows all login of selected ddlUsers.SelectedValue.
Why does not work like this?
ObjectDataSource1.FilterExpression = "userid LIKE '{0}' AND action LIKE '{1}'";
ObjectDataSource1.FilterParameters.Add("userid", ddlUsers.SelectedValue);
ObjectDataSource1.FilterParameters.Add("action", ddlAction.SelectedValue);

A: Yes :) I found the problem.
Before this code, I used ObjectDataSource1.FilterParameters.Add("userid", Name); code
so 3 filterParameters.
So this query is empty. Grid View shows empty information.
I remove all parameters and I add just this two parameters and it's ok. It shows very good.
:)


text:
Q: Convert From Local Coordinates To Global Coordinates I've been writing a Parent/Child Entity system for a small game and I am having a problems when I try to get a child object's location.
As it stands now, the child of an Entity are transformed, rotated, and scaled in the coordinate space of the parent. This means that if our parent is at a location of ( 2, 3, 0 ) and we add a child to that parent at a location of ( 1, 2, 1 ), its world space is ( 3, 5, 1 ).
My problem is that I don't know how to convert from the local space ( 1, 2, 1 ), to the global space ( 3, 5, 1 ).
The obvious place to start is by adding the parent position and the child position. This works for non-rotated objects. Whenever rotation and scale are applied though it gets confusing and this is what I cannot figure out.
I read somewhere to use inverse of matrices but the explanation beyond that was not clear. Any help/mathematical insight/pseudocode would be greatly appreciated, thanks!

A: Just wanted to post this in case it helped anyone cause it caused me quite a bit of confusion.
This is actually very simple to do. All you have to do is multiply the parent entities model matrix by the child's model matrix then recover the coordinates from the bottom row like so.
In the example below we can see how I get the position from the model matrix of an entity with and without a parent. ( I do not actually do this. I store the position of each entity separately. This is just useful for entities that you know have a parent and need the position in the world space. )
Vector3f Entity::GetPosition() const {
    Matrix4f matrix;
    if ( GetParent() != 0 ) {
        matrix = GetParent()->GetModelMatrix() * GetModelMatrix();
    } else {
        matrix = GetModelMatrix();
    }

    float x = matrix[ 3 ][ 0 ];
    float y = matrix[ 3 ][ 1 ];
    float z = matrix[ 3 ][ 2 ];

    return Vector3f( x, y, z );
}

Note: I wrote my own matrix implementation so how you multiply and extract the positions will most likely be different.

A: The underlying concept used here is change in basis of matrix.
Using the axis vectors of the local coordinate system and coordinates with respect to the local coordinate system , the coordinates at global system can be obtained.
a = [a']M

a' - Coordinates wrt local axis
M  - Basis matrix formed using vectors of axis

I found videos which explain the same in great detail .
Links :
1) https://youtu.be/zntNi3-ybfQ
2) https://youtu.be/1j5WnqwMdCk


text:
Q: How to simplify an error callback in react I have a parent component that handles an error callback from its child components however in keeping with do not repeat yourself there seems to be a lot of repitition in my code id like to eliminate.
    function BasicInfo() {
    const {shell, ageAndGender, body} = styles;
    const {dispatch, state: {firstname}} = useSignUpState();
    const [firstnameError, setFirstnameError] = useState(true);
    const [ageError, setAgeError] = useState(true);
    const [genderError, setGenderError] = useState(true);
    const [sexualOrientationError, setSexualOrientationError] = useState(true);
    const [heightError, setHeightError] = useState(true);

    const setUserAgeError = useCallback(val => {
        setAgeError(val);
    }, [setAgeError]);

    const setUserGenderError = useCallback(val => {
        setGenderError(val);
    }, [setGenderError]);

    const setUserSexualOrientationError = useCallback(val => {
        setSexualOrientationError(val);
    }, [setSexualOrientationError]);

    const setUserHeightError = useCallback(val => {
        setHeightError(val);
    }, [setHeightError]);

    const handleError = () => {
        return firstnameError || ageError || sexualOrientationError || genderError || heightError;
    }

    useEffect(() => {
        if (firstname === '') {
            setFirstnameError(true);
        } else setFirstnameError(false);
    }, [firstname])

    return (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
            <View style={shell}>
                <View style={{flex: 10}}>
                    <SignUpHeader title={`Enter a bit about\nyourself`} page={1}/>
                    <View style={body}>
                        <TextInput
                            autoComplete
                            mode="outlined"
                            label="Firstname"
                            value={firstname}
                            onChangeText={firstname => dispatch(setFirstname(firstname))}
                            style={{maxHeight: 64, marginBottom: 32}}
                            activeOutlineColor={"#000"}
                            outlineColor={"#DBDBDB"}
                            theme={{
                                colors: {
                                    text: "#000",
                                    placeholder: "#878787",
                                    background: "#FFF"
                                }
                            }}
                        />
                        <View style={ageAndGender}>
                            <AgeButton setBasicInfoError={setUserAgeError}/>
                            <GenderButton setBasicInfoError={setUserGenderError}/>
                        </View>
                        <SexualOrientationButton setBasicInfoError={setUserSexualOrientationError}/>
                        <HeightButton setBasicInfoError={setUserHeightError}/>
                    </View>
                </View>
                <SignUpFooter
                    buttonTitle="Next"
                    disabled={handleError()}
                    route="BasicInfo"
                    title={`Basic\nInfo`}
                />
            </View>
        </TouchableWithoutFeedback>
    );
}

As you can see in the code above every error is passed down to its child, does something very similar to my firstname useEffect which checks if its not valid and sets a boolean which is then checked by the parent.
Is there a way to maybe create just one callback as say an array and say if length is > 1 set the error? Any help with this would be great to avoid duplication! Thanks

A: This looks like something you need to condense into a single useState. If you only expect one error at a time (even if they can be fairly close together) then you can simply have
[error, useError] = useState("");

And then set the error to "age" or "gender". In UseEffect, you use a switch to handle all possible use cases.
If you want multiple errors handled at a time, it looks pretty similar, but your useState starts out looking more like this
[error, useError] = useState({
age: true, gender: true, sexualOrientation: true, height: true
})

Again, with this method, you can use a single useEffect to monitor it.  To handle changing a single piece, you can use the spread operator
useError({...error, age: false})

which changes age to false, but keeps everything else the same.


text:
Q: Get number of pages in a pdf using a cmd batch file I can see there are a lot of questions for getting the number of pages in a a pdf with C, PHP and others but am wondering with a batch file or cmd is there a simple way of getting the number of pages?

A: Using pdftk:
pdftk my.pdf dump_data | grep NumberOfPages
does the trick.

A: Without any external tools (save the script bellow as .bat) :
@if (@X)==(@Y) @end /* JScript comment
@echo off

cscript //E:JScript //nologo "%~f0"  %*

exit /b 0
@if (@X)==(@Y) @end JScript comment */

   var args=WScript.Arguments;
   var filename=args.Item(0);
   var fSize=0;
   var inTag=false;
   var tempString="";
   var pages="";

   function getChars(fPath) {

        var ado = WScript.CreateObject("ADODB.Stream");
        ado.Type = 2;  // adTypeText = 2
        ado.CharSet = "iso-8859-1";
        ado.Open();
        ado.LoadFromFile(fPath);
        var fs = new ActiveXObject("Scripting.FileSystemObject");
        fSize = (fs.getFile(fPath)).size;

        var fBytes = ado.ReadText(fSize);
        var fChars=fBytes.split('');
        ado.Close();
        return fChars;
   }

   function checkTag(tempString) {

    if (tempString.length == 0 ) {
        return;
    }

    if (tempString.toLowerCase().indexOf("/count") == -1) {
        return;
    }

    if (tempString.toLowerCase().indexOf("/type") == -1) {
        return;
    }

    if (tempString.toLowerCase().indexOf("/pages") == -1) {
        return;
    }

    if (tempString.toLowerCase().indexOf("/parent") > -1) {
        return;
    }

    var elements=tempString.split("/");
    for (i = 0;i < elements.length;i++) {

        if (elements[i].toLowerCase().indexOf("count") > -1) {
            pages=elements[i].split(" ")[1];

        }
    }
   }

   function getPages(fPath) {
        var fChars = getChars(fPath);

        for (i=0;i<fSize-1;i++) {

            if ( fChars[i] == "<" && fChars[i+1] == "<" ) {
                inTag = true;
                continue;
            }

            if (inTag && fChars[i] == "<") {
                continue;
            }

            if ( inTag &&
                 fChars[i] == ">" &&
                 fChars[i+1] == ">" ) {

                inTag = false;
                checkTag(tempString);
                if (pages != "" ) {
                    return;
                }

                tempString="";

            }

            if (inTag) {
                if (fChars[i] != '\n' && fChars[i] != '\r') {
                   tempString += fChars[i];
                }
            }

        }

   }

   getPages(filename);
   if (pages == "") {
     WScript.Echo("1");
   } else {
    WScript.Echo(pages);
   }

It takes the path to the .pdf file and simply prints the number of the pages.Not pretty fast as it reads the pdf symbol by symbol , but could be optimized.

A: Because you asked for a "batch file" I have to assume you only want a Windows-based solution. But, just in case Mac OS X is an option, here something that could be useful.
If you have the PDFs on a Mac, on a drive that has been indexed by Spotlight (the default), the following command will return the number of pages using no external dependencies:
mdls -name kMDItemNumberOfPages POSIX_PATH_OF_PDF_FILE

Source: MacScripter.net - http://macscripter.net/viewtopic.php?id=32381

A: Alternatively you can use the command, which returns only the number:
pdfinfo "${PDFFILE}" | grep Pages | sed 's/[^0-9]*//'
You will need the poppler package:
https://poppler.freedesktop.org/
Which can be installed using either homebrew / linuxbrew:
brew install poppler

or with apt:
sudo apt install poppler-utils

A: QPDF is a lightweight alternative to PDFtk (requiring Java runtime) and pdfinfo (quite a dumb tool).
qpdf --show-npages file.pdf

It prints just the number of pages, needing no post-processing.
Packages for most Linux distributions exist, usually named just qpdf. Pages like Softpedia host binaries for Windows. The source code can be downloaded from SourceForge, or from the official GitHub repository.

The --show-npages option was added in a version after 4.1.0, in commit 91367239fd55f7c4996ed6158405ea10573ae3cb. To be compatible with version 4.1.0 and earlier, you can dump basic information about each page and count the pages. In Linux and OS X:
qpdf --show-pages file.pdf | grep -c ^page

On Windows, you should use findstr and find instead:
qpdf --show-pages file.pdf | findstr ^page | find /c /v ""

A: It might be helpful for new users. In the new version of PDFtk tool (above 2.0), use below command to get the number of pages of a PDF file:
pdftk file.pdf dump_data_annots output outputfile.txt

A new file will created at destination having content similar to below:
NumberOfPages: 6

Now read the file and manipulate the content as you want.

A: I know this is old post, yet still very much relevant, so I believe that there should be an answer which can tell how to get page count using "poppler-0.68.0" utility, in windows.
Navigate to bin folder and run pdfinfo.exe like -
C:\Temp\temp_folder\poppler-0.68.0\bin>pdfinfo.exe "C:\Temp\temp_folder\TT.pdf"

A: A simple way if ImageMagick or GraphicsMagick is installed:
   identify *.pdf | wc -l