text:
Q: Return parent node after string search in XML - PHP I have an XML file like so:
<GenResponse>
  <Detail1></Detail1>
  <Detail2></Detail>
  <DataNodes>
    <DataNode>
      <NodeDetails1>
        <node4>Parrot Musky Truck Moo</node4>
        <node5>Tinker Singer Happy Fool</node5>
        <node6>
          <FurtherDetails>
            <Node>Musky</Node>
            <Node>Lorem Ipsum</Node>
          </FurtherDetails>
      </NodeDetails1>
      <NodeDetails2>ID</NodeDetails2>
    </DataNode>
    <DataNode>
      <NodeDetails1>
        <node4>Sky Star Panet Shoe</node4>
        <node5>Rusky Husky Musky Boo</node5>
      </NodeDetails1>
      <NodeDetails2>ID</NodeDetails2>
    </DataNode>
  </DataNodes>
</GenResponse>

I would like to know how I would inject a search string "Musky" to a PHP function and get back <DataNode>...</DataNode> & <DataNode>...</DataNode> back?
Essentially I would like to search a huge XML file for a string and return all the DataNode's which contain the string back.
If this is possible with SimpleXML it would be great. Else any other solution is also fine.
EDIT: Notice how "Musky" can be in different nodes under <DataNode>

A: use
$xmlStr = file_get_contents('data/your_XML_File.xml');
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with  text
$res = $xml->xpath("node2[contains(., 'Musky')]");
print_r($res);

//For testing purpost just copy paste following code in editor , For testing , I didnt use separate xml file.
<?php
//$xmlStr = file_get_contents('test.xml');
$xmlStr = '<node1>
  <node2>
    <node3>
      <node4>Parrot Singer Truck Moo</node4>
      <node5>Tinker Musky Happy Fool</node5>
    </node3>
    <node7>ID</node7>
  </node2>
  <node2>
    <node3>
      <node4>Sky Star Panet Shoe</node4>
      <node5>Rusky Husky Musky Boo</node5>
    </node3>
    <node7>ID</node7>
  </node2>
</node1>';
$xml = new SimpleXMLElement($xmlStr);
// seach records by tag value:
// find nodes with  text
$res = $xml->xpath("node2[contains(., 'Musky')]");
echo "
";
print_r($res);

?>

It gives proper output , i tried
Array
(
    [0] => SimpleXMLElement Object
        (
            [node3] => SimpleXMLElement Object
                (
                    [node4] => Parrot Singer Truck Moo
                    [node5] => Tinker Musky Happy Fool
                )

            [node7] => ID
        )

    [1] => SimpleXMLElement Object
        (
            [node3] => SimpleXMLElement Object
                (
                    [node4] => Sky Star Panet Shoe
                    [node5] => Rusky Husky Musky Boo
                )

            [node7] => ID
        )

)

A: Use this code and you can find your search word.I have made it a function just pass your keyword and you will get your result,
function findWord($findVar)
{
    $catalog = simplexml_load_file("xmlfile.xml");

    $category = $catalog->node2;

    $found = 0;
    foreach($category as $c)
    {
        foreach($c->node3 as $node3)
        {
            $node4 = (string) ($node3->node4);
            $node5 = (string) ($node3->node5);
            if (stripos(strtolower($node4),strtolower($findVar)))
            {
                echo 'Found!!'.'
';
                $found++;
            }
            if (stripos(strtolower($node5),strtolower($findVar)))
            {
                echo 'Found!!'.'
';
                $found++;
            }
        }

        if (stripos(strtolower((string)$c->node7),strtolower($findVar)))
        {
            echo 'Found!!'.'
';
            $found++;
        }
    }
    if ($found == 0)
    {
        echo "No result";
    }
}

$findVar = 'Musky';
findWord($findVar);


text:
Q: Add route prefix to Flask application running behing Gunicorn tldr; Looking for a way to prefix all routes within an app running behind Gunicorn without a reverse proxy/blueprint/duplicate prefix in @route(PREFIX + '/') etc.

Creating a few Python services, using Flask, running in Docker containers.
Not, currently, using Nginx/Apache for reverse proxying.
Have something like below that works when running flask by itself
 - (eg % python app.py responds with localhost:5000/a/b/some-route)
base_path = "/a/b"
app = DispatcherMiddleware(_root_app, {base_path: self})
run_simple(host, port, app, **options)

Not sure how to achieve the same result when running behind Gunicorn.
(Would really like to do this without making a blueprint for the main app. Also trying to avoid having the same prefix in every @route(PREFIX + ''))
Reason for doing this
Using an extension that adds a few routes, along with a blueprint. Would like to have app routes AND extension/blueprint routes to all be prefixed.

This question asked this specifically for Flask, which I'm able to get working using the DispatcherMiddleware approach.
  My question is how to get this working when running behind Gunicorn (no Nginx or Apache in front, just Gunicorn)

Potential Fix:
Currently using a subclass of Flask (needed to do some customized logging nonsense.)
Overriding the add_url_rule works.
prefixed_rule = self._prefix_rule(rule)
super().add_url_rule(prefixed_rule,
                     endpoint=endpoint,
                     view_func=view_func,
                     **options)

This also works with our extensions too

A: If you are doing app composition, then you can use the DispatcherMiddleware trick you referenced.  However, it sounds like you are trying to have a single service that is subpath mounted, but doesn't serve anything out of the "higher" paths at all.
There are several different ways to do this.

*

*Replace Flask.url_map._rules with a werkzeug.routing.Submount rule factory:
from werkzeug.routing import SubPath

app = Flask(__name__)

# register blueprints and extensions
# load config, etc.

app.url_map._rules = SubPath(app.config['APPLICATION_ROOT'], app.url_map._rules)

*Replace Flask.url_rule_class:
from werkzeug.routing import Rule

app.url_rule_class = lambda path, **options: Rule(PREFIX + path, **options)

*Replace add_url_rule, as you suggest in your question.

A: You can prefix all routes for a specific blueprint
from flask import Blueprint
my_blueprint = Blueprint('my_blueprint_name', __name__, url_prefix='/my_prefix')

then for all your routes for the blue print simply put
@my_blueprint.route('my_route')

before the function definition and its route will be the url_prefix+my_route
You may find this link helpful http://flask.pocoo.org/docs/0.10/patterns/urlprocessors/

A: try this
app = dash.Dash(
    __name__,
    server=server,
    routes_pathname_prefix='/dash/'
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to change spelling suggestion to en-US in latex + vs code? I am using VS code + Latex for writing my research papers. I want my spell check to show suggestions in English-US, but the results I am getting are in English-UK. Is there any possible way to configure the language in VS code?
PS: I am using the LaTex Workshop (James Yu) extension in VS code.

A: There are several VS Code plugins which provide this task. I recommend a couple:

*

*Code Spell Checker, which supports many programming and markup languages;

*LTeX – LanguageTool grammar/spell checking, which supports only a few markup languages.

Both check documents in American English (en-US) by default.


text:
Q: Extra strange segment in a form action URL automatically added by laravel I have this form:
{!!Form::open(['route'=>'fastsearch.show'])!!}

In routes.php I have:
Route::resource('fastsearch','SearchController');

And in SearchController i have a method show() that sends the return to a view called fastsearch (which is fastsearch.blade.php)
If I look into the source of the page where the form is, I see this:
<form method="POST" action="http://localhost:8000/fastsearch/%7Bfastsearch%7D" accept-charset="UTF-8"><input name="_token" type="hidden" value="hLcSkGk2p5XfTkFEv2pwGgcVQB18vHQIGMpOVGpM">

If I put some data in the form and click Submit, I get this error:
MethodNotAllowedHttpException in RouteCollection.php line 201:

My question is why the extra segment in the action URL (this one: /%7Bfastsearch%7D). Is something wrong with the routes ?
(Just to give you all the details, this a general search form that lies on almost every page in order to allow the users to run a quick search from almost every page they might be at that time. So it doesn't matter if you're on Home page or on /Home/Subpage/SubSubPage{wildcard}{wildcard} you can still see the form and use it)

A: You're trying to send a post request to a route expecting a get request.
Change:
{!! Form::open(['route'=>'fastsearch.show']) !!}

To:
{!! Form::open(['route'=>'fastsearch.index']) !!}

Where index is the name of the action you wish to receive the post request.
You're probably better off using specific named routes for this though.
Route::post('fastsearch', [
    'as' => 'fastsearch.search', 'uses' => 'SearchController@search'
]);

Take a look at http://laravel.com/docs/5.1/controllers#restful-resource-controllers for more info on resource controllers and http://laravel.com/docs/5.1/routing#named-routes for more on named routes.
You can also use ./artisan route:list for a list of existing routes.


text:
Q: gmdate 12 hours off I'm trying to get the GMT to send with an API request however my time is off from the actual GMT.
Right now the GMT is 6:40 PM Friday, November 20, 2020.
However when I run
gmdate("Y-m-d\Th:i:s\Z");

I get 2020-11-20T06:47:07Z. Which is 6AM instead of PM.
How do I get the correct GMT?

A: Change h to H to get a 24 hour hour. The small h gives you the hour in 12 hour format.
gmdate("Y-m-d\TH:i:s\Z");


text:
Q: Card matching game.. how to compare cards? So my design is to have 26 picture boxes (code only shows till 10.. you get the idea) to show the user their "hand". Now how do I check those image boxes for doubles, and then remove those doubles to a cleared pile? So let's say if there are 2 Jacks, and 3 fives then 2 Jacks are removed and only 2 fives are removed. I can't figure out how to do this. I have them set up and named in my code below as follows:
Dim faces() As String = {"Ace", "Two", "Three", "Four", "Five",
         "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}

Here is my code, this is really just for player one although there will be a computer player as well.
Deckofcards
Public Class DeckOfCards
   Private Const NUMBER_OF_CARDS As Integer = 52 ' number of cards
   Private deck(NUMBER_OF_CARDS - 1) As Card ' array of Card objects
   Private currentCard As Integer ' index of next Card to be dealt
   Private Shared randomNumbers As New Random() ' random number generator

   ' constructor fills deck of Cards
   Public Sub New()
      Dim faces() As String = {"Ace", "Two", "Three", "Four", "Five",
         "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"}
      Dim suits() As String = {"Hearts", "Diamonds", "Clubs", "Spades"}
        currentCard = 0 ' set currentCard so first Card dealt is deck(0)

      ' populate deck array with Card objects
      For count = 0 To deck.GetUpperBound(0)
         deck(count) = New Card(faces(count Mod 13), suits(count \ 13))
      Next
   End Sub ' New

   ' shuffle deck of Cards with simple one-pass algorithm
   Public Sub Shuffle()
      ' after shuffling, dealing should start at deck(0) again
      currentCard = 0 ' reinitialize currentCard

      ' for each Card, pick another random Card and swap them
      For first = 0 To deck.GetUpperBound(0)
         ' select a random number between 0 and 51
         Dim second As Integer = randomNumbers.Next(NUMBER_OF_CARDS)

         ' swap current Card with randomly selected Card
         Dim temp As Card = deck(first) ' store copy of deck(first)
         deck(first) = deck(second) ' move deck(second) to deck(first)
         deck(second) = temp ' move original deck(first) to deck(second)
      Next
   End Sub ' Shuffle

   ' deal one Card
   Public Function DealCard() As Card
      ' determine whether Cards remain to be dealt
      If currentCard <= deck.GetUpperBound(0) Then
         Dim lastCard As Integer = currentCard ' store current card number
         currentCard += 1 ' increment current card number
         Return deck(lastCard)
      Else
         Return Nothing ' no more cards to deal
        End If

    End Function ' DealCard

End Class

A: I Think you are going about this the wrong way. ie Your design is wrong because you are assigning values as strings which makes comparing them more difficult
I would recommend you have a Card class that looks like this:
Public Class Card

    Public Enum CardValue
        Ace = 1
        Two = 2
        'etc
        Jack = 11
        Queen = 12
        King = 13
    End Enum

    Public Enum CardSuit
        Clubs
        Spades
        Hearts
        Diamonds
    End Enum

    Public Property Value As CardValue
    Public Property Suit as CardSuit

    Public sub New(value as CardValue, suit as CardSuit)
        Me.Value = value
        Me.Suit = suit
    End Sub

End Class

The each play would simple have a List(Of Card) in their hand. To compare which ones are the same is as simple as:
Dim Cards as List(Of Card) 'Players hand

If Cards.Select(Function(x) x.Value).Distinct.Count < Cards.Count Then
    'there are some duplicates in the list
    Dim duplicates = Cards.GroupBy(Function(x) x.Value).Where(Function(g) g.Count > 1).Select(Function(g) g.Key).ToList
    For Each i In duplicates
        Debug.WriteLine("Card value " + i.ToString + " is a match")
    Next
End If

You can create and populate your deck of cards as follows:
Dim deck(51) As Card
Dim cardPosition As Integer = 0

'loop through each suit and each value in that suit setting one of the deck to that
For Each suit As Card.CardSuit In [Enum].GetValues(GetType(Card.CardSuit))
    For Each value As Card.CardValue In [Enum].GetValues(GetType(Card.CardValue))
        deck(cardPosition) = New Card(value, suit)
        cardPosition += 1
    Next
Next


text:
Q: Finding minimum sum of absolute differences between heights of $n$ boys and $m$ girls Given two sets $A$ and $B$, $A$ has heights of $n$ boys and $B$ has heights of $m$ girls, $m \ge n$.
We have to find one solution of pairing up $n$ boys with $n$ (out of $m$) girls so that the sum of the absolute difference between the heights of boy and girl in each pair is minimized.
For example:
$$A = \{10,10,12,13,16\}$$
$$B = \{6,7,9,10,11,12,17\}$$
so ans should be $4$
one possible soln. of pairing is $\{(10,10),(10,9),(12,11),(13,12),(16,17)\}$
Each tuple is $(A,B)$

A: If two boys have heights $b_1 \leq b_2$ and two girls have heights $g_1 \leq g_2$ and if you have a matching where $b_1$ is paired with $g_2$ and $b_2$ is paired with $g_1$, then you can find at least as good of a matching by instead matching $b_1$ with $g_1$ and $b_2$ with $g_2$.  Thus you can safely assume the best matching must have matched girls in sorted order of height when their corresponding boys are put in sorted order of height.  If you want a computer programming approach to solve the problem, this dramatically reduces the complexity of your search, e.g. you can use dynamic programming to find the optimal matching by building up optimal matchings that have the first $j$ boys in sorted height order all paired up somehow among the first $k$ girls in sorted height order (where $j \leq k$), and using the optimal matchings for the values $(j,k-1)$ and $(j-1,k-1)$ to decide the optimal matching for the values $(j,k)$, based on whether you pair up boy $j$ with girl $k$ or not.  This dynamic programming solution has $O(nm)$ time and space complexity if you have $n$ boys and $m$ girls.


text:
Q: How will GPU execute when the number of threads per block is larger than the maximum number of active threads on a Streaming Multiprocessor? Base on my current understanding of CUDA and GPU computing, each thread block has to be run within one Streaming Multiprocessor. Each streaming multiprocessor has a fixed number of cores (which is equal to the maximum number of active threads on a streaming multiprocessor). Then my question is what will happened if we have a thread block with larger number of threads than the number of cores on one streaming multiprocessor.
For example, GeForce GTX 980 has 16 streaming multiprocessor, each of which has 128 cores. So the maximum number of active threads on one streaming multiprocessor would be 128. But when programming in CUDA, we can launch a kernel with <<<1,512>>>, which means one thread block with 512 threads. Then how will the GPU execute this kernel? Will it run all 512 threads on one streaming multiprocessor or will it split it across multiple streaming multiprocessors? If it runs on one streaming multiprocessor, how could this happen? Will it run 128 threads first, then the next 128 threads, then the next...
Please correct me if any of my understanding is not correct. Thanks.


text:
Q: Converting Facebook feed from JSON to typed objects with JSON.NET The problem is, I receive a list of posts from facebook (page feed) which occasionally holds multiple comments in an array inside the post object. Only the first comment of the post gets parsed correctly. Somehow the second and later comments don't get parsed.
This is the JSON I'm going on about:
{
  "data": [ //Root object
  { //Post object
     "id": "153411918116843_304953306296036",
     "from": {
        "category": "Sports/recreation/activities",
        "category_list": [
           {
              "id": "124887510918208",
              "name": "Swimming Pool"
           }
        ],
        "name": "Twentebad",
        "id": "153411918116843"
     },
     "link": "http://dlvr.it/5bBKPx",
     "picture": "irrelevant",
     "message": "Onderzoek renovatie Twentebad! http://dlvr.it/5bBKPx",
     "created_time": "2014-05-07T09:44:18+0000",
     "comments": { // Collective comments object

        // Actual comments objects in array !!!!! ONLY FIRST GETS PARSED !!!!
        "data": [
           { //Comment object
              "id": "304953306296036_304959069628793",
              "from": {
                 "id": "884483928243965",
                 "name": "Selena Suzan Valentino"
              },
              "message": "Twentepalace",
              "can_remove": false,
              "created_time": "2014-05-07T10:32:26+0000",
              "like_count": 0,
              "user_likes": false
           },
           { Unparsed comment object
              "id": "304953306296036_305126702945363",
              "from": {
                 "id": "884483928243965",
                 "name": "Selena Suzan Valentino"
              },
              "message": "Na baantjes trekken vooral heerlijk...",
              "can_remove": false,
              "created_time": "2014-05-08T09:12:43+0000",
              "like_count": 0,
              "user_likes": false
           },
           { //Unparsed comment object
              "id": "304953306296036_305126622945371",
              "from": {
                 "id": "884483928243965",
                 "name": "Selena Suzan Valentino"
              },
              "message": "Wil infrarood sauna weer terug komt...",
              "can_remove": false,
              "created_time": "2014-05-08T09:11:20+0000",
              "like_count": 0,
              "user_likes": false
           }
        ],

        "paging": {
           "cursors": {
              "after": "MQ==",
              "before": "Mw=="
           }
        },
        "summary": {
           "order": "ranked",
           "total_count": 3
        }
     }
  }
  ]
}

I'm using JSON.NET to parse this json to a typed object list like this:
foreach (JToken facebookItem in data["data"])
{
    JToken messageCheck = facebookItem.SelectToken("message", false); //Irrelevante post als er geen inhoud in zit (false = geen error melding indien null)
    if (messageCheck != null)
    {
        itemsToAdd.Add(facebookItem.ToObject<FacebookItem>());
    }
}

The FacebookItem class looks like this:
public class FacebookItem
{
    public string id { get; set; }
    public From from { get; set; }
    public string link { get; set; }
    public string picture { get; set; }
    public string message { get; set; }
    public string created_time { get; set; }
    public Comments comments { get; set; }
    public PostPaging paging { get; set; }

    public class PostCategories
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    public class From
    {
        public string category { get; set; }
        public List<PostCategories> category_list { get; set; }
        public string name { get; set; }
        public string id { get; set; }
    }

    public class CommentCategories
    {
        public string id { get; set; }
        public string name { get; set; }
    }

    //Root of Comments ("data":[ "comments":{ [],{},{} } ])
    public class Comments
    {
        public List<CommentData> data { get; set; } //SHOULD HOLD MORE THAN 1
        public CommentPaging paging { get; set; }
        public Summary summary { get; set; }
    }

    //Data gegevens van comments ("data":[ "comments":{ "data":[],{},{} } ])
    public class CommentData
    {
        public string id { get; set; }
        public CommentFrom from { get; set; }
        public string message { get; set; }
        public bool can_remove { get; set; }
        public string created_time { get; set; }
        public int like_count { get; set; }
        public bool user_likes { get; set; }
    }

    //Data gegevens van ccommenter ("data":[ "comments":{ "data":[ "from":{} ],{},{} } ])
    public class CommentFrom
    {
        public string id { get; set; }
        public string name { get; set; }
        public string category { get; set; }
        public List<CommentCategories> category_list { get; set; }
    }

    //Paging gegevens van comments ("data":[ "comments":{ [],"paging":{},{} } ])
    public class CommentPaging
    {
        public Cursors cursors { get; set; }
    }

    //Summary gegevens van comments ("data":[ "comments":{ [],{},"summary":{} } ])
    public class Summary
    {
        public string order { get; set; }
        public int total_count { get; set; }
    }

    public class Cursors
    {
        public string after { get; set; }
        public string before { get; set; }
    }

    public class PostPaging
    {
        public string previous { get; set; }
        public string next { get; set; }
    }
}

Is there a Json.net expert out there that undertands why only the first comment gets parsed?
This is what the debugger show me:

A: I'll tell you where I live, please come and kill me...
I called the url from localstorage. I changed the url but changes aren't detected so it doesn't get overwritten.
So, why only one comment? I had the comments' limit set to 1 :(
Not as exiting as I hoped this would be.
Hopefully the info provided can help someone in the future.


text: Q: Apple mobile purchase renews itself during the day sometimes when I create a new sandbox account and make a purchase, the revenue cat dashboard shows the number of transactions more than once. My appstore settings seem to be okey. Even though I purchased it once, the package seems to be renewed by itself. I only have this problem in apple, there is no such problem in android


text:
Q: What is the difference between a stability condition and a CFL condition? From what I know, a stability condition depends on the eigenvalues of a matrix and CFL condition involves a time component. Say I have a system $$Au=f$$ but then add in a time component so that I have $$\frac{du}{dt}+Au=f$$
Is the only real difference that I have the consider the adjusted eigenvalues of the second equation? In particular, if I am using forward Euler to approximate the time component, what does my CFL condition look like? Essentially, I am just confused as to how I get the bound for a CFL condition and how it differs from a stability condition.


text:
Q: How do I write a CD/DVD from the shell to save emails etc? Was wondering if there is a simple way to save emails, etc... to a CD/DVD from terminal when the upgrade to ubuntuu 14.04 has delivered an icon and bar-less desktop with a program  error message?  Needless to say, I did not make a backup (not that I know how to).  The information is not that important, but would like to learn how to do a few things in Linux, other than getting stuck in log-in loops.

A: Depending on what email software you are using, for example on my Thunderbird setup I copy the profile and rsync it from time to time to separate folder (with thunderbird is turned off) and then that folder I backup to external media when needed.

A: Burning CD/DVD from terminal
The tool to burn a CD or DVD from the command line is growisofs. The man page shows only part of the options, because some are forwarded to a subcommand, that is used by growisofs: genisoimage
For example, of the command line to burn the home directory to a DVD (assuming it is not too large), growisofs -Z /dev/sr0 -r -J /home/username, the options -Z /dev/sr0 are documented in man growisofs, and -r -J /home/username are described in man genisoimage
See http://community.linuxmint.com/tutorial/view/1089 for some examples.

Backup of email
If you use IMAP to read mail, not POP3, there is a good chance that the mail is stored on the mail server, and you only have a copy. (IMAP keeps the mail on the server normally, but you can also move mail to a local folder)
If you use Thunderbird, your mails are stored in something like ~/.thunderbird/*.default usually, as part of the thunderbird profile.
A backup of this contains account settings too.
If you want to backup independant of the format of thunderbird, there is the thunderbird addon "ImportExportTools" that can be used to export mails to single files, for example, to have a more flexible backup.


text: Q: Orbeon - strange behaviour - radio-buttons I got a strange issue with Orbeon Forms. It might be a problem with styles, but I'm not sure. When I put validation on radio-type control, I got an asterisk icon, what is normal. These asterisks show up signed to every answer.


text:
Q: Eclipse: Converting JAR file into project I have a maven project converted into executable jar which is hosted and running just fine.
How to convert this jar src into a project in eclipse so that i can debug and do modifications to the existing files?
I have tried importing as maven, but it imports the libraries inside the META-INF, and i can't see any class files or pages.
This is the project structure  JD-GUI,

A: Use JD GUI. Open the application, drag and drop your JAR file into it.


text:
Q: Does try catch clause affect performance if used in looping in Java? I want to know if I use one or two try catch in a while loop, does this affect the performance or not?
Example code below:
try {
    // some code
    ....

    try {
        // some code
        ...
    } catch(Exception e) {
        if(e is not catchable) {
            //throw it as MyException(e);
        }
    }

    // some code
    ...

} catch(Exception e) {
    if(e is my Exception) {
        then do somthing
        ...
    } else { // is other Exception
        if(e is not catchable) {
            then stop the loop
        }
        // else catch it and continue
    }
}

What about if else if used instead, then which one will be the good idea?
If someone knows pleas tell me does it affect performance or not, if yes then why.
My question maybe asked by someone else before, but I also want to know about if-else if it is better then try-catch.
Edit:
I know if throws Exception then for catching it needs some time, but how about if the program goes whit no Exception jut like:
// some code
        ....
// some code
        ....
// some code
        ....

Thanks!

A: Try - catch block doesn't affect performance itself, but the code inside catch block wil be executed every time an exception is throwed, and this could affects permformances.


text:
Q: Apply sound effects on a video file I am a little miss guided here and it seems i am totally lost. I am developing an android app and its core idea is to develop a video recorder and video player that applies some sound effects on the voice of the people or any sound that it records. Sound effect means that if i make a video of a person who is giving some speech then there should be no effect on video but his/her voice should appear like voice in talking tom cat app. I hope you understand the idea. Similar app is Helium Booth you can check it here. I am trying to use libraries like libSonic, libpd and tried to use XUGGLE too.
Read somewhere that Xuggle is not really developed for mobile devices so left it. Now what i want is that it should apply this effect on voice on the run time i.e while recording the pitch of the sound should be alterd and saved immediately. And what i am getting with these libraries is that i can apply sound effect after video is recorded. So it means i need to rip the audio from the video and then apply the change in pitch and frequency and again concatenate this audio file with the old video file. And i have no idea how to do it.
Please show me the right approach and tools if possible.
Regards


text:
Q: Restoring a database with just .idb and .frm files I've never attempted something like this before. We had a WAMP installation with WordPress running on my wife's PC, and the Aestan tray menu failed. I figured we need to uninstall and re-install WAMP, which left the data files in .ibd and .frm files along with the core WordPress installation. I'm trying to bring them back to life again to be used. The WAMP people recommended I find a way to restore the database files.
I read a post here (Recover MySQL database from data folder without ibdata1 from ibd files) regarding someone who had the same set of "leftover" files, and was given some advice regarding how to restore using some MySQL utilties. They said, "you can download a MySQL utility that can generate the SQL needed to create the table." I went to Oracle and downloaded the Windows version of their utilities, but there are around 24 .exe files in there! I have no idea which one to use. I was expecting a single app in there, not a collection.
I'm not afraid to try this, but it's not clear which utility(ies) I should use. I'm trusting that the instructions could make sense once I'm actually attempting it. I've been in PHPAdmin a few times so I do know how to make some edits, but doing a restore like this with .ibd and .frm files is new territory for me.
Details: My WAMP installation was using MySQL 5.6.12, and the new WAMP installation uses 5.6.17. The WAMP people said if I restore the database in the 5.6.12 then I'll be able to choose the 5.6.12 setup from the Aestan tray menu. I have made backup copies of the 5.6.12 database files. So I'm ready to attempt this, but would appreciate a little advice from any of you.


text:
Q: How to dismiss a NavigationController in Storyboard? I've looked everywhere for this, so as a last resort I figured I should ask the question.
I'm using Storyboard in XCode and have a navigation controller as my initial view. The root view of this navigation controller is a table view. In this table view, I have a button in the navigation bar that flips the view horizontally via a modal segue to a navigation controller. The root view of this controller is my map view. Now, when I want to dismiss this map view using [self dismissViewControllerAnimated:YES completion:nil] it doesn't work. It does if I take out the navigation controller. So, I'm guessing the dismissViewController is getting passed to the navigation controller, and not doing anything. I know I could implement a class for the navigation controller to handle the call and pass it on, but I don't want to do that unless absolutely necessary.
So to solve this question:

*

*I need a way to switch between table view to map view using the flip horizontally animation and vice versa.

*I need to have a navigation controller in both views, I could either be the same one, or a different one. I can't seem to find a way to use the same one, since any transitions would be pushes which don't do the flip horizontally transition.
Thanks in advance for the help!

A: Who is self when you call [self dismissViewControllerAnimated:YES completion:nil]?
The receiver of this message needs to be the view controller which presented the modal view controller you want to dismiss. If you call it on the presented view controller, or (in the case of container view controllers like UINavigationController, one of the view controllers it manages), UIKit will try to do the right thing but won't always succeed.
Presuming the self you refer to is the view controller containing the map view, you can get the presentingViewController property to get the object you should call dismissViewControllerAnimated:completion: on. (And if you need to get the navigation controller that's in between, use the navigationController property.)


text:
Q: regarding to Computer RAMs So I was reading on word size of a computer, in the book, it says "The main indication of the word size is how much memory the processor can address. A 32-bit processor is limited to 232 memory addresses, each of which usually holds one byte. Hence, 32-bit PCs and Macs are limited to a maximum of 4 gigabytes of electronic memory (RAM and ROM)."
My question would be , does that mean the limited RAM for 64-bit processor is 8 gigabytes??
I remember seen 16 gigabytes of RAM before

A: No 2^32 is 4GB
2^64 is 16 billion gigabytes ... much bigger

A: No, it means that the limited RAM for a 64-bit processor is 4GB x 4GB, which is 16EB (ExaByte).


text:
Q: Python: Error when appending new item to a list in a pandas dataframe I have a pandas dataframe with three columns: user_id (str), list_of_purchases (list) and a binary column named b.
I would like to create a fourth column named final_list that follows the rules below:

*

*When b = 1, then final_list should be the concatenation of list_of_purchases and the item "Success". So for example, if list_of_purchases = ['item_1', 'item_2', 'item_3'] then final_list should be ['item_1', 'item_2', 'item_3','Success']

*When b = 0, then instead of "success", final_list should be ['item_1', 'item_2', 'item_3','Null']

I tried the following code but got the error:
df['final_list'] = np.where(
    df['b'] == 0,
    df['list_of_purchases'] + ['Null'],
    df['list_of_purchases'] + ['Success'])

TypeError: Cannot broadcast np.ndarray with operand of type <class 'list'>

I figured out how to do it using a for loop and checking every row in column b, but it is really ineficient and takes a long time.
Thanks in advance for the help!

A: #create a function:
def lista(df):
    return [df['list_of_purchases'] + ['Null'] if df['b'] == 0 else df['list_of_purchases'] + ['Success']]

#use the function on every row of df:
df['final_list'] = df.apply(lista, axis=1)

from what I understand, pandas dataframes are not designed to store lists as their values, so super efficient solutions are not available

A: Feels like a nice use for a lambda, rather than defining a function, though both approaches work.
import pandas as pd
import numpy as np

data = [[1, [1,2,3]],
        [0, [4,5,6]]]
df = pd.DataFrame(data, columns=["b", "list_of_purchases"])

df["Output"] = df.apply( \
    lambda row : row["list_of_purchases"] + \
    ["Success" if row["b"] else "Null"], axis=1)

print(df)

Produces:
   b list_of_purchases              Output
0  1         [1, 2, 3]  [1, 2, 3, Success]
1  0         [4, 5, 6]     [4, 5, 6, Null]

"Benefits" of using a lambda are (here) basically just that it avoids defining a function which you might not ever reuse.
If the function/logic is to be reused elsewhere then defining a function (and not using a lambda) might be exactly the right approach. If it's only used for this, and not reused, I'd probably go with the lambda.


text:
Q: Speeding up jquery autocomplete with php list Hi I have run into an issue. I have implemented jquerys famous autocomplete and I am creating a list (quite long) from the database to output into the autocomplete feild. But it is taking too long to find the correct value in list. Does anyone know a way I can speed this up??? Here is my jquery:
<script>
    $(function() {function log( message ) {$( "#destId" ).val( message );}
        $( "#destinations" ).autocomplete({
            source: "destinos.php",
            minLength: 2,
            select: function( event, ui ) {
                log( ui.item ?
                    "" + ui.item.id :
                    "" + this.value );}});});
    </script>

And here is destinos.php:
//connect to database
include 'php/dbconn.php';
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT Destination as value, DestinationId as id FROM DestinationId WHERE Destination LIKE '%".$term."%'";
//query the database for entries containing the term
    $result = mysql_query($qstring);
//loop through the retrieved values
    while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
    {
            $row['value']=htmlentities(stripslashes($row['value']));
            $row['id']=htmlentities(stripslashes($row['id']));
            $row_set[] = $row;//build an array
    }
    echo json_encode($row_set);//format the array into json data

Any help would be greatly greatly appreciated!

A: You most likely need to speed up your database query. You'll have to do a couple of things to do that.

*

*Make sure your Destination field has an index on it.

*Unless you absolutely must match from the middle of the string, drop the leading % from your LIKE query to enable the index to be used. MySQL cannot effectively use the index with the leading wildcard.

*If you must leave the leading % then set minLength to 3 in your jQuery. This will allow MySQL to use an optimizing algorithm on the pattern.

Source: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

A: I would start off looking at the DB aspects.
First, you need to make sure you have an index on Destination.
Second, you ought to consider using a LIMIT, say 10 or 20 rows.  In an autocomplete, in most cases you don't need that many results to display at one time. The match count will decrease as the user continues typing fairly quickly.
Third, you should use proper mysql escape on $term variable before querying with it.
The rest looks pretty straightforward.


text:
Q: PHP - float numbers - comma and dot problem I'm having a problem with my PHP server (5.6.40).
The PHP sometimes change the dot to comma, without any kind of warning.
For example:
$runTimes = 20;
$number   = 39.102564102564;

for ($i = 0; $i < $runTimes; $i++) {
    echo "<p>$number</p>";
}

This echo shows '39.102564102564', but sometimes shows '39,102564102564' (with comma). This is awful, because when I insert this number into the DB, it changes to 39 (without decimals).
I tried setlocale(LC_NUMERIC, 'C'), but didn't change anything.
It doesn't happens in my localhost, only on my server
localeconv() print:
Array
(
    [decimal_point] => .
    [thousands_sep] =>
    [int_curr_symbol] =>
    [currency_symbol] =>
    [mon_decimal_point] =>
    [mon_thousands_sep] =>
    [positive_sign] =>
    [negative_sign] =>
    [int_frac_digits] => 127
    [frac_digits] => 127
    [p_cs_precedes] => 127
    [p_sep_by_space] => 127
    [n_cs_precedes] => 127
    [n_sep_by_space] => 127
    [p_sign_posn] => 127
    [n_sign_posn] => 127
    [grouping] => Array
        (
        )

    [mon_grouping] => Array
        (
        )

)

EDIT:
Executing the script directly through the PHP (prompt) it doesn't happen. This problem only happens through a browser (in this case, Firefox)

SOLUTION:
I changed to another concurrency model called the prefork MPM and the problem was solved.

A: Locale is NOT thread-safe in PHP!
https://www.php.net/manual/en/function.setlocale.php

The locale information is maintained per process, not per thread. If
you are running PHP on a multithreaded server API , you may experience
sudden changes in locale settings while a script is running, though
the script itself never called setlocale(). This happens due to other
scripts running in different threads of the same process at the same
time, changing the process-wide locale using setlocale(). On Windows,
locale information is maintained per thread as of PHP 5.6.20 and PHP
7.0.5, respectively.

Regarding the output (changing dot and comma) - this has to do with the number-to-string conversion on C-level (PHP is written in C...). With a little research you'll probably stumble over this site.
https://phpinternals.news/52
The initial problem is: Another script, running in the same process as yours, change the locale while your script is executing... even though this other script may switch the locale back to its original value, and despite the fact that it's probably only a fraction of a fraction of a second being changed, it is still shared amongst all threads of the process.
hth


text:
Q: Analysing an s-domain circuit with multiple sources So I am working on the following circuit:

I have already worked my initial conditions and the next step is to perform analysis of the charged up circuit. My charged circuit is shown below:

The charged circuit now has 4 sources. I am confused as to how I can go about analyzing the charged circuit. For some clarity, the dependent current source is 0.9vd and the dependent voltage source is 2it.


text:
Q: Not able to add Rabbitmq plugin I was following this http://www.rabbitmq.com/plugin-development.html link to build rabbitmq plugin https://github.com/rabbitmq/rabbitmq-web-mqtt
after building i ONLY copied rabbitmq_mqtt.ez to /usr/lib/rabbitmq/lib/rabbitmq_server-3.6.2/plugins
running sudo rabbitmq-plugins enable rabbitmq_web_mqtt
shows :
The following plugins have been enabled:
  cowlib
  cowboy
  rabbitmq_web_mqtt

Applying plugin configuration to rabbit@manish-Lenovo-G510... failed.
Error: {could_not_start,rabbitmq_web_mqtt,
           {undef,
               [{lager_config,get,
                    [{rabbit_log_lager_event,loglevel},{0,[]}],
                    []},
                {rabbit_web_mqtt_app,mqtt_init,0,
                    [{file,"src/rabbit_web_mqtt_app.erl"},{line,69}]},
                {rabbit_web_mqtt_app,start,2,
                    [{file,"src/rabbit_web_mqtt_app.erl"},{line,31}]},
                {application_master,start_it_old,4,
                    [{file,"application_master.erl"},{line,269}]}]}}

Running sudo rabbitmq-plugins list
 Configured: E = explicitly enabled; e = implicitly enabled
 | Status:   * = running on rabbit@manish-Lenovo-G510
 |/
[e*] amqp_client                       3.6.2
[e ] cowboy                            1.0.3
[e ] cowlib                            1.0.1
[e*] mochiweb                          2.13.1
[  ] rabbitmq_amqp1_0                  3.6.2
[  ] rabbitmq_auth_backend_ldap        3.6.2
[  ] rabbitmq_auth_mechanism_ssl       3.6.2
[  ] rabbitmq_consistent_hash_exchange 3.6.2
[  ] rabbitmq_event_exchange           3.6.2
[  ] rabbitmq_federation               3.6.2
[  ] rabbitmq_federation_management    3.6.2
[E*] rabbitmq_management               3.6.2
[e*] rabbitmq_management_agent         3.6.2
[  ] rabbitmq_management_visualiser    3.6.2
[E*] rabbitmq_mqtt                     3.6.2
[  ] rabbitmq_recent_history_exchange  1.2.1
[  ] rabbitmq_sharding                 0.1.0
[  ] rabbitmq_shovel                   3.6.2
[  ] rabbitmq_shovel_management        3.6.2
[  ] rabbitmq_stomp                    3.6.2
[  ] rabbitmq_tracing                  3.6.2
[e*] rabbitmq_web_dispatch             3.6.2
[E ] rabbitmq_web_mqtt
[  ] rabbitmq_web_stomp                3.6.2
[  ] rabbitmq_web_stomp_examples       3.6.2
[  ] sockjs                            0.3.4
[e*] webmachine                        1.10.3

I am not able to connect using paho JS client. So what is causing the issue? I tried port 1888, 8083,8883,15675

A: Applying plugin configuration to rabbit@manish-Lenovo-G510... failed.
Error: {could_not_start,rabbitmq_web_mqtt,
           {undef,
               [{lager_config,get,

Lager is only in the version 3.7.0, most likely you built the master branch.
To build the plugin version 3.6.2 you should:
    git clone https://github.com/rabbitmq/rabbitmq-public-umbrella.git .
    make up BRANCH=rabbitmq_v3_6_2
    cd deps/rabbitmq_web_mqtt
    make dist

EDIT
you have to disable and remove the old .ez file, after copied the new one, you have to enable the plugin.
just tried and it works correctly, see the test:


text:
Q: Can i create a XmlNamespaceManager object from the xml file i am about to read? I have some c# code running on sharepoint that i use to check inside the xml of an infopath document to see if i should checking the document or discard the document.
The code is working fine for a couple of different form templates i have created but is failing on my latested one.
I have discovered that the XmlNamespaceManager i am creating contains the wrong diffinition for the "MY" namepsace.
I'll try to explain
I have this code to decalre my XmlNamespaceManager
NameTable nt = new NameTable();
NamespaceManager = new XmlNamespaceManager(nt);

// Add prefix/namespace pairs to the XmlNamespaceManager.
NamespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
NamespaceManager.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");
NamespaceManager.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");
NamespaceManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-14T13:45:59");
NamespaceManager.AddNamespace("xd", "http://schemas.microsoft.com/office/infopath/2003");`

I can then use the following line of code to search for the xml i am after
XPathNavigator nav = xml.CreateNavigator().SelectSingleNode("//my:HasSaved", NamespaceManager);

nav.Value then gets be the data i want.
This all works fine on a couple of my form templates. I ahve a new form template and have discovered that i need to use thi line instead
NamespaceManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-11-30T17:39:37");

The date is different.
My problem is that i cannot add this twice as only 1 set of forms will work.
So my question is. Is there a way i can generate the NamespaceManager object from the XML file as this is all contained in the header?
I have not been able to find a simple way round this.

A: I found a way of doing this. Instead of adding the "my" namespace it can be pulled from the XmlDocument object. This might just be a bit of luck that it works this way but i'm happy with it.
NamespaceManager.AddNamespace("my", formXml.DocumentElement.NamespaceURI

formXML is an XmlDocument created from the infopath XML

A: One option would be to try to load the xml node using the first namespace, if that doesn't give any results, call PushScope(), override the first namespace definition, select, etc...
var doc = new XmlDocument();

doc.LoadXml(@"<?xml version=""1.0""?>
      <root xmlns:my=""http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-11-30T17:39:37"" value=""1"">
           <my:item>test</my:item>
      </root>");

var nameTable = new NameTable();

var namespaceManager = new XmlNamespaceManager(nameTable);

namespaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

namespaceManager.AddNamespace("xhtml", "http://www.w3.org/1999/xhtml");

namespaceManager.AddNamespace("dfs", "http://schemas.microsoft.com/office/infopath/2003/dataFormSolution");

namespaceManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-07-14T13:45:59");

namespaceManager.AddNamespace("xd", "http://schemas.microsoft.com/office/infopath/2003");

// n will be null since the namespace url doesn't match

var n = doc.SelectSingleNode("descendant::my:item", namespaceManager);

namespaceManager.PushScope();

namespaceManager.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2010-11-30T17:39:37");

// will work

n = doc.SelectSingleNode("descendant::my:item", namespaceManager);

namespaceManager.PopScope();

Another option is to parse the attributes in the header and look for any contained namespaces
foreach(XmlAttribute attribute in doc.DocumentElement.Attributes)
{
    var url = namespaceManager.LookupNamespace(attribute.LocalName);

    if(url != null && url != attribute.Value)
    {
        namespaceManager.RemoveNamespace(attribute.LocalName, url);
        namespaceManager.AddNamespace(attribute.LocalName, attribute.Value);
    }
}

A: You don't need to do anything like this. Just use "my2" or something for the second namespace. You then need the new namespace prefix for any nodes that use the new namespace, and use the old "my" namespace prefix for all the nodes that still use the old namespace.


text:
Q: Is there a way to remove the header and footer that Facebook adds when I save a page as a PDF (from Chrome on a Mac)? Is there a way to remove the header and footer that FB adds when I save a page as a PDF (from Chrome on a Mac)?
When I ask Facebook to give me an archive of some of my previous posts, I gives me results that link to an archive page, something like this:
https://www.facebook.com/[magicnumber_redacted]/allactivity/?category_key=YOURTIMELINEPOSTS&entry_point=ayi_hub&year=2021&month=4

which shows thumbnails and 2- to 3-line snippets of all my timeline posts for April 2021. That's really pretty useful for searching. But unfortunately, that page is not searchable. On a Mac, using Cmd+F will only search the framework of the page that has the date text, the displayed snippets of the post contents are not searchable. Cmd+A, Cmd+V will copy the framework text, but not the snippets. If I save it as HTML and reload the saved file, same problem is there. I'm not enough of an HTML guru to figure out how to automate restructuring of the pages.
However, I can save the page a PDF and then the full displayed text is searchable. That's what  I want. Yay! BUT there is a glitch. FB adds headers and footers to every PDF page that cover over part of the text of the first and last snippet on each. The text is there, hidden. If I search the PDF for text that I know is hidden, Acrobat highlights the area where the text should be, underneath the large colored header or footer bar.
So is there a way to get FB to not insert page headers and footers when the web page is saved as PDF? I can save PDFs of other web pages without this kind of problem.
Thanks.

A: I had erroneously thought that it was Facebook that put the header on every page, and wrote my question that way. That's mistaken.
After much experimenting, it seems that when Facebook serves a page, it provides fixed header information and scrolling page data. Then it is up to the browser to put those together, for display or when you ask the browser to print the page, including save it to PDF.
So the answer to the question is:
It's not Facebook adding the header to the printed page or PDF, it's the browser, and the solution is to use Safari instead of Chrome for these kinds of pages.
Chrome appears to have the design decision that it will print the header on every page. On Facebook, that includes both the menu at the left and the links at the top of the page. But Chrome does not allow room for that on each printed page, with the result that some of the scrolled page data is masked or eclipsed. The same is true for Chrome-like browsers like Opera.
But Safari made a different design decision, they only print the header on one page. It turns out that it's not always the first page, it's the page you are looking at. If you have scrolled to the bottom of a long Facebook page in Safari and then print it, or save it to PDF, Safari will put the header info on the last or next-to-last page, depending on how the pages break. But it won't allow room for the header there, so there will be data that is eclipsed or masked.
But Safari does allow room for the header on the first page, so if you scroll to the top before printing, the header will be on the first page only, and there will be room allowed, and the print or PDF will be reasonably formatted with no data eclipsed or masked.

A: If there are no print css styles in the web page or a special 'print' or
'print version' or 'offline reading' button then it will always be not
easy to print a web page.
Then you will have to find workarounds:

*

*delete html nodes

*change css styles
...

Delete html nodes:
You can delete nodes from the html DOM.
Open the developer tools.
(Shortcut on a Mac: Open Developer Tools    ⌘ + Option + i)
Then go to the 'Elements' - Tab, there you can see the DOM.
Moving the mouse over the html elements in the elements window
will higlight the corresponding parts of the html page.
If you move the mouse over some part of the html page and
click with the right mouse button and select 'Inspect' will select
a html element in the 'Elements' window.
If you have selected a node with 'Inspect' then move the mouse
(without clicking) in the elements windows upwards.
You will see that the
selection in the html page will extend.
Then go further upwards until the whole part of the html page
you want to be deleted will be selected.
If you are on the outmost html element that corresponds to the parts
to be deleted then click the right mouse button
(in the 'Elements' window) and select 'delete element'.
Most of the time this will be a  element
or a  element.
But it will not always work. It depends on how dynamic the web page is
and how the page is composed (html, css js etc.).
Sometimes it goes wrong and the remaining parts of the page
will be moved or collapsed or you did delete too much.
Then you can refresh the page and start again.
Sometimes e.g. you want to delete a whole sidebar or a footer.
You might find  html elements or css style classes called alike.
Changing styles:
You find the styles in the 'Styles' tab.
Sometimes the text content part is in a column that is too narrow.
Try to select the whole column.
Then look a the styles. Maybe you find a size or a percentage.
Click on the value and increase it.
Sometimes a page is build with bootstrap.
If you delete left and right columns to have only the content in the middle,
that part might still not extend to the right.
Then it could be that the bootstrap class restricts the width e.g. to 4 or 6
columns of the whole page layout (maybe a 12 column layout).
The bootstrap class might be 'col-md-6'.
Then you could change this class to e.g. 'col-md-10'
so that the whole div can fill a 10 columns space.
Good luck !


text:
Q: Is it possible to push a index.html to heroku? I develop a pure front-end app with an index-file called index.html. Everytime I push to heroku, i need to rename it index.php, in order to tell heroku to use php. Is there another way to declare what type of server I want? So that I get to keep my file as an html-file?

A: You can also just drop an empty composer.json into your project to make Heroku treat your project as a PHP project.
The preference of index.php over index.html comes from the default DirectoryIndex directive that Apache uses on Heroku; it has nothing to do with your browser. To change it, you could drop a .htaccess with DirectoryIndex index.html into your application.
If you just want raw performance for your static site, it's also probably a good idea to use Nginx. The default configuration should be reasonable for your purposes so add a Procfile with web: vendor/bin/heroku-php-nginx to your project along with an empty composer.json (and no index.php) and you're good to go.
Also see https://devcenter.heroku.com/articles/php-support and https://devcenter.heroku.com/articles/custom-php-settings for more details.

A: You can do that simple node.js app with ExpressJS;
Let say your project folder has a sub folder called public,
var express = require('express');
var app = express();
app.use('/', express.static(__dirname + '/public'));
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
    console.log('Your files will be served through this web server')
});

Save this code in app.js, put your static files under public folder, and prepare your Procfile
Final folder structure will be;
yourproject
--public/
----your staticfiles
--app.js
--Procfile

Procfile will be;
web: node app.js

And deploy your project. When you request your static files like; .../index.html, index.html will be served under public folder

A: Add a empty file called index.php, this will be used by heroku, though, index.html will be prioritised by browsers.


text:
Q: no suitable constructor exists to convert from "v8::Array *" to "v8::Local" I am trying to cast the arguments passed to my C++ addon into arrays but I am running into the error in the title. This is my code:
#include "node.h"
#include "node_buffer.h"
#include "v8.h"

using namespace v8;
using namespace std;

namespace water{
    using v8::FunctionCallbackInfo;
    using v8::Isolate;
    using v8::Local;
    using v8::Object;
    using v8::String;
    using v8::Number;
    using v8::Value;
    using v8::Array;

    void water(const FunctionCallbackInfo<Value> &args)
    {
        if(args[0]->IsArray())
        {
           Local<Array> a = Array::Cast(*args[0]);
           Local<Array> b = Array::Cast(*args[1]);
        }
        args.GetReturnValue().Set(20);
    }
    }

This is my error no suitable constructor exists to convert from "v8::Array *" to "v8::Local<v8::Array>"
In other words, I am looking to pass in arrays to my method from a NodeJs program using node-gyp but I can't seem to do so.

A: Reading the documentation, I think it should be
Local<Array> a = args[0].As<Array>();


text:
Q: Create new list if Say that I have a while loop that runs 'n' times. And I would like to create a new table every time 'n' is divisble by 7. Now I don't know what 'n' is so how can I make the program create a list and call it some random name like list1, list2, list3.. etc...
I've been wondering about this for a long time. Thanks.
Edit: Say 'n' is 1234 or 999900000. Hope you understand what I mean. 'n' is unknown.

A: Yes, but you should not create dynamic variable names.  A better option is to store the names as keys in a dict and the "created table" as the corresponding value
n = 50
myd = {}
list_num = 1
for i in range(1, n):
    if i % 7 == 0:
        myd['list{}'.format(list_num)] = 'i = {}'.format(i)
        list_num += 1

print(myd)

Now all you have to do is replace 'i = {}'.format(i) with a call to your method that creates your table(s)!
And to access a specific table you simply reference myd['list#']
(e.g. 'list1', 'list2', et cetera),
where list1 is the first match to if i % 7 == 0:, which in your case is 7,
and list2 would be the second match (i.e. 14).

A: def yourFunction(n):
    i = 0
    while i < n:
        if n % 7 == 0:
            create_new_table()  # or whatever your new table code is

Although I don't know what you mean by creating list1, list2, list3, etc. Perhaps you want to create a list that itself contains lists? Or create a dictionary with keys such as "list1", "list2", etc. and values of lists?

A: Not really clear what you mean with the list1, list2, list3 part, but I guess this gives an idea of how to solve this: modulo is your friend.
>>> n = 53;
>>> for i in range(0, n):
...   if i % 7 == 0:
...     list.append(i)
...
>>> list
[0, 7, 14, 21, 28, 35, 42, 49]


text:
Q: Why is this just rotating and not moving to the right? I have the following web page:

var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise

function draw_box() {
  var c = document.getElementById("area");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, 500, 500);
  ctx.rotate(box_direction * Math.PI / 180);
  ctx.fillRect(box_x, box_y, 100, 50);
  box_x += 2;
}

setInterval(draw_box, 1000);

Welcome

<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>

Why is the box not just moving to the right?

A: ctx.rotate rotates the entire canvas from the top left corner, so you should first use ctx.translate to move the top left corner to the pivot (which is the box's
top left corner) and then do the same but in reverse so you reset the rotation and translation of the canvas

var box_x = 30;
var box_y = 30;
var box_width = 30;
var box_height = 30;
var box_direction = 20; // Degrees clockwise

function draw_box() {
  var c = document.getElementById("area");
  var ctx = c.getContext("2d");
  ctx.clearRect(0, 0, 500, 500);

  ctx.translate(box_x, box_y);
  ctx.rotate(box_direction * Math.PI / 180);
  ctx.fillRect(0, 0, 100, 50);
  ctx.rotate(-box_direction * Math.PI / 180);
  ctx.translate(-box_x, -box_y);

  box_x += 2;
}

setInterval(draw_box, 1000);

Welcome

<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa" />
</canvas>

A: Because you have ctx.rotate(box_direction * Math.PI / 180);. This is rotating with the box.

    <title>Rectangles wandering around aminlessly</title>

  <body

Welcome

<canvas id="area" width="500px" height="500px" style="border: 1px solid #0000aa"/>
</canvas>


text:
Q: Wordpress file upload media_handle_upload fatal error I wrote a PHP script to process files sent to it via POST.
On the frontend js script, I create a Formdata object, and append images to it...like:
formdata.append('image0', image0);
formdata.append('image1', image1);

etc
This is my PHP code, the code is in the wordpress root directory
<?php
header("Access-Control-Allow-Origin: *");

require_once('wp-admin/includes/image.php' );
require_once('wp-admin/includes/file.php' );
require_once('wp-admin/includes/media.php' );

$id_array = array();

$c = 0;

foreach ($_FILES as $file) {

$id_array[] = media_handle_upload('image' . $c, 0);
$c++;
}

echo implode(',', $id_array);

However when I run this code, I get the following error:
Fatal error:  Call to undefined function __() in /home/website/public_html/wp-admin/includes/file.php on line 16
Am i missing to include additional files in the script? I used the documentation on wordpress and it said:
These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );

I would appreciate any help!

A: In order to use the native Wordpress functions, such as __() wp-config.php needs to be included additionally.
Adding wp-config.php solved the issue

A: I'm also facing same issue.
Adding this in functions.php will fix the error.
Some time it will show as "http error"
add_filter( 'wp_image_editors', 'raj_change_graphic_library' );
function raj_change_graphic_library($array) {
 return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}


text:
Q: Binding treeview to object Bit new to WPF, so i'm just trying to get my head around some bindings in the context of treeviews. First, some code.
In my main window i add my namespace;
xmlns:WPFFM="clr-namespace:WPFFM"

My class i'm trying to bind through type;
namespace WPFFM
{
    public class Asset
    {
        public string ID;
        public string name;
        public string room;
        public string description;

        public Asset(string AssetID, string AssetName, string AssetRoom, string AssetDescription)
        {
            ID = AssetID;
            name = AssetName;
            room = AssetRoom;
            description = AssetDescription;
        }
    }
}

My main class which has my List and it's population;
namespace WPFFM
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        DBConnector dbConnector;
        public static List<Asset> assetList;

        public MainWindow()
        {
            InitializeComponent();
            Populate();
        }

        public void Populate()
        {
            assetList = new List<Asset>();
            dbConnector = new DBConnector();
            DataTable assetDatatable = new DataTable();

            assetDatatable = dbConnector.GetAssets();

            foreach (DataRow row in assetDatatable.Rows)
            {
                Asset assetToAdd = new Asset(row["assetID"].ToString(), row["assetName"].ToString(), row["assetRoomID"].ToString(), row["assetDescription"].ToString());
                assetList.Add(assetToAdd);
            }

            //assetTreeView.ItemsSource = assetList;

        }

    }
}

and finally my treeview XAML;
TreeView x:Name="assetTreeView"   ItemsSource="{Binding assetList}">
                                    <TreeView.ItemTemplate>
                                        <HierarchicalDataTemplate  DataType="{x:Type WPFFM:Asset}" ItemsSource="{Binding assetList}">

                                            <Grid Background="LightSkyBlue"  Margin="2" Width="100" Height="24">

                                                <TextBlock Margin="2" Text="{Binding name}" VerticalAlignment="Center" FontWeight="Bold" />
                                            </Grid>

                                        </HierarchicalDataTemplate>
                                    </TreeView.ItemTemplate>
                                </TreeView>

I've tried numerous ways to bind, but i'm not having any luck. From what i've gathered i'm binding the treeview to the list of Asset(my class), and my datatype to that of Asset. Then i'm trying to display the "name" property exposed from my Asset class. I'm not really sure where i'm going wrong. Am i missing something stupidly simple?
edit: ignore the fact that some functions might need to be moved from the mainwindow.xaml.cs and whatnot, i'm not going for structure at this point.

A: Everything WPF binds to must be a property, not a field.
Another thing missing here is DataContext initialization. Without it, binding won't work.


text:
Q: Routing Issue: Load Balancer with multiple external NICs Single Unix-based load balancer (LB) is configured with multiple network interfaces - 2x external and 1x internal. The LB sits in front of a DNS resolver. The issue I'm trying to solve is that all DNS responses come back to External Interface #1 even when the request comes through Interface #2. If the request came through Int #2, I need the response to come back through the same interface.
Update: Using iptables, but happy to consider alternatives.
Network Diagram


text:
Q: How to use function do.call() efficiently? I have many dataframe (a,b,c,d,e,f,g,....) in a list which have the same structure. When using do.call() to union all of them, it's very slow. Is there any method to combine them more efficiently? Thanks!
mylist<-list(a,b,c,d,e,f,g,....)
do.call(rbind, mylist)

A: library(data.table)

rbindlist(mylist)


text:
Q: Use pdp package to get probability scale partial dependence plots for all classes I have been following the example here to create partial dependence plots but I would like to combine the approach used to get plots for all levels in a multiclass with the one to get predictions on the probability scale (see pages 430-431).
This is my approach but it doesn't work because pred.fun is not allowed to have a third arguement
library(e1071)

iris.svm <- svm(Species ~ ., data = iris, kernel = "radial", gamma = 0.75,
                cost = 0.25, probability = TRUE)

pred.prob <- function(object, newdata,i) { # see ?predict.svm
  pred <- predict(object, newdata, probability = TRUE)
  prob.class <- attr(pred, which = "probabilities")[, i]
  mean(prob.class)
}

pred.prob(iris.svm,iris,"setosa")

pd <- NULL

for (i in 1:3) {
  tmp <- partial(iris.svm, pred.var = c("Petal.Width", "Petal.Length"),
                 pred.fun = pred.prob,
                 which.class = i, grid.resolution = 101, progress = "text")
  pd <- rbind(pd, cbind(tmp, Species = levels(iris$Species)[i]))
}

Any recommendations for how to get around this requirement or a different approach?

A: It looks like the package has actually been updated since the article I referred to was published. Now all you need to do is set the prob argument to TRUE and it will predict on the probability scale.
pd <- NULL
for (i in 1:3) {
  tmp <- partial(iris.svm, pred.var = c("Petal.Width", "Petal.Length"),
                 prob = T,
                 which.class = i, grid.resolution = 101, progress = "text")
  pd <- rbind(pd, cbind(tmp, Species = levels(iris$Species)[i]))
}

I hope this helps someone else to avoid wasting an afternoon!


text:
Q: Atomic operation involving separate processes I have two .NET applications I'm building which need to share a counter resource locally.  I'm looking for a way to atomically increment or decrement the counter from each application.
If I were doing this within a single, multi-threaded application, I would simply use one of the System.Threading.Interlocked.Increment and System.Threading.Interlocked.Decrement overloads with a shared counter variable.
My applications will not have access to a database, so I can't use DBMS locking mechanisms.  Ideally, I'd like to use a registry REG_DWORD value, but I can't figure out a way to increment or decrement it atomically.  I've also considered having a file system folder where "incrementing" is putting a uniquely named file in the folder and "decrementing" is deleting a single file, but that seems a bit bulky or cumbersome of an approach.
Does anyone know of a good approach to this?

A: You can use a shared Mutex to synchronize between multiple processes.
This allows you to "lock" and provide a guard around the code which accesses the registry, if that is the shared storage mechanism you choose to use.


text:
Q: Azure apim developer portal - mimic depreciated portal feature Previously in the azure deprecated developer portal there was an "admin functionality", we need to bring it back to the new self hosted developer portal

to view all the Clientapp releated to an api

to view all the clientapp in the developer portal

to have the "allow tracing" on subscription to get api inspector log

A: Thank you azaslonov and ErikMogensen. Posting your suggestion as an answer to help other community members.

we have migrated this but on the new portal we don t find the admin functionality to see 'Allow tracing' in the api operation details page. This was visible in old depreciated portal

*

*We removed the Trace tab from the developer portal altogether. It was a legacy feature available only to the administrators. We recommend using the test console in the Azure portal instead.

*But if your backend service requires an OAuth token you cannot test it from the Azure Portal. When trying this from the developer portal I can as a workaround add a header with Ocp-Apim-Trace: True and use a subscription which allows tracing
You can refer to Unable to view API-M Trace in new Developer Portal and Debug your APIs using request tracing


text:
Q: How can I pass content to an element in clients html page? I'm currently using Node.js to serve a webpage that takes in user inputs which are stored on a mongodb server. The web page also displays specified or all user inputs entered. I'm trying to figure how to pass the user inputs from node.js to the
 element.
In my node.js file I am responding with the user data as a string like so:
response.writeHead(200, {"Content-Type": "text/plain"});
response.write(stringifyMongoDBCollection(user_data_collection));
response.end();

When I do this, this re-directs the client to display the content as text/plain which I expected. The next step is to update just the content of
. How can I do this? I thought about re-serving the entire html content with the new populated
 but that would make all current user inputs disappear...
The user data would be a mongodb collection array and look like this:
 [ { _id: 5dda17065f7e9b64282e7291,
    date: 'Sat Nov 23 2019 21:37:10 GMT-0800 (Pacific Standard Time)',
    field: '127' },
  { _id: 5dda18ecf330d521a035c444,
    date: 'Sat Nov 23 2019 21:45:16 GMT-0800 (Pacific Standard Time)',
    field: 125},
  { _id: 5dda1951f330d521a035c445,
    date: 'Sat Nov 23 2019 21:46:57 GMT-0800 (Pacific Standard Time)',
    field: '111' } ]

A: You could do something like this.
In Node section
res.status(200).send(stringifyMongoDBCollection(user_data_collection));

Client side

function getContent() {
  $.ajax({
    url: "https://jsonplaceholder.typicode.com/todos",
    success: function (res) {
      if (res) {
        res = res.slice(0, 5); // limiting data to 5
        var val = '';
        res.forEach(todo => {
          val += '
Title:' + todo.title + '  Completed: ' + todo.completed + '
';
        });
      }
      $("#content").html(val);
    },
    error: function () {
      var val = '
Error in loading content
'
      $("#content").html(val);
    }
  });
}

<button onclick="getContent()">Get Content</button>

Todo

References
jQuery ajax() Method
Node.js - Response Object
AJAX Introduction


text:
Q: adding new dropdown lists in asp without reloading the page I would like to have a page that would contain:
hyperlik "Add new country".
After clicking this link by user, dropdown list with names of countries should appear. However this hyperlink should stay on this page. When user click this hyperlink once again, second dropdown list with exactly the same names should appear. This should be repeat as long as user clicks hyperlink.
It is important that this page shouldn't be reloaded.
Does anyone has any idea how can it be made?

A: The typical way to achieve this is to have your Add new country link trigger an ajax call out to a page you create which will provide the data for your list.
The preferred method these days seems to be having that page you call build up a JSON response, then your callback on the ajax method where you called it can populate that data into a drop down.
The page you call from AJAX could be something simple like this:
protected override void  Render(HtmlTextWriter writer)
{
    Dictionary<string, int> myStuff = new Dictionary<string, int>();
    myStuff.Add("country1", 1);
    myStuff.Add("country1", 2);

    JavaScriptSerializer jss = new JavaScriptSerializer();
    Response.Write(jss.Serialize(myStuff.ToList()));
    Response.ContentType = "application/json";
}

Use this jQuery on your main page:

Tested and working. (in a simplified example) I did have to convert from Dictionary to List for the json serializer to make it an array as desired. See the updated Serialize call. There is also some validation, e.g. did the ajax call return real data?, that would need added to a real life implementation.

A: It looks like you are doing it a least approximately right.
in the HTML if you have some tag that surrounds the area you want the drop down box to then it is simple.
for example:
in HTML:
Add new country

in javascript:
function addDD(){
document.dropdownarea.innerHTML += "HTML code for the drop down that you want";
}


text:
Q: how to write Mongoose find filter with 2 values I am trying to write a mongoose Find() filter where it should return the result of users whos  name are either "Ram" or "Shyam"
find({ name: "Ram" or "Shyam"});
How do I write it in a way that it pull all the users that has name set as Ram or Shyam

A: Here the query you're looking for:
Collection.find({
  $or: [
    {
      name: "Ram"
    },
    {
      name: "Shyam"
    }
  ]
})

Reference: https://docs.mongodb.com/manual/reference/operator/query/or/


text:
Q: ImportHTML find ALL tables and lists In Google sheets there is a function called IMPORTHTML which allows you to return tables and lists from HTML pages. However I have no idea how to find out the indexes of the tables or lists I am looking at. Is there a way to figure out ALL of the tables and lists quickly and there respective indexes? I have tried looking at the source on some of the web pages in Chrome and it is unreadable due to how they load the page but somehow the google function knows how to get the 17th table for example. This is a generic question and doesn't apply to any one website but rather ANY website I might want to extract some unknown table number. Right now I am just brute forcing through a bunch of indices which doesn't seem right.

A: This won't find the exact table you want, but it will give you a list of the tables.
From google developers console enter below to find table numbers
var i = 1; [].forEach.call(document.getElementsByTagName("table"), function(x) { console.log(i++, x); });


text:
Q: javax.persistence.PersistenceException: [PersistenceUnit: sapo] class or package not found I know there are other questions about this topic in StackOverflow, I read them but I can't get rid off this error.
I'm deploying my web app in JBoss-as-7.1.1 Final. It's a Maven proyect.
When I go to sapo-ear, rigth click, run as, maven install, it says "build succesfull". Then I try to full publish it in JBoss and then it says:
23:59:26,009 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-1) MSC00001: Failed to start service jboss.persistenceunit."SAPo-ear.ear/SAPo-ejb.jar#sapo": org.jboss.msc.service.StartException in service jboss.persistenceunit."SAPo-ear.ear/SAPo-ejb.jar#sapo": Failed to start service
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1767) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80-ea]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80-ea]
at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80-ea]
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: sapo] class or package not found
at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1400)
at org.hibernate.ejb.Ejb3Configuration.addClassesToSessionFactory(Ejb3Configuration.java:1183)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:1047)
at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:692)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:72)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.createContainerEntityManagerFactory(PersistenceUnitServiceImpl.java:162)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl.start(PersistenceUnitServiceImpl.java:85)
at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
... 3 more
Caused by: java.lang.ClassNotFoundException: uy.edu.fing.tsi2.sapo.entities.Administrador from [Module "org.hibernate:main" from local module loader @beaed3 (roots: C:\Program Files\jboss-as-7.1.1.Final\modules)]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:190)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:468)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:456)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:120)
at java.lang.Class.forName0(Native Method) [rt.jar:1.7.0_80-ea]
at java.lang.Class.forName(Class.java:278) [rt.jar:1.7.0_80-ea]
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:170)
at org.hibernate.ejb.Ejb3Configuration.classForName(Ejb3Configuration.java:1317)
at org.hibernate.ejb.Ejb3Configuration.addNamedAnnotatedClasses(Ejb3Configuration.java:1389)
... 11 more

As far as I know, this could be caused by an inconsistence between persistence.xml and Adminstrador class.
Here is my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
    http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="sapo">
    <jta-data-source>java:jboss/datasources/sapo</jta-data-source>
    <class>sapo.entities.Administrador</class>
    <class>sapo.entities.Almacen</class>
    <class>sapo.entities.AtributoValor</class>
    <class>sapo.entities.Comentario</class>
    <class>sapo.entities.Estandar</class>
    <class>sapo.entities.Mensaje</class>
    <class>sapo.entities.Producto</class>
    <class>sapo.entities.RolEnAlmacen</class>
    <class>sapo.entities.CatCompleja</class>
    <class>sapo.entities.ProductoGenerico</class>
    <class>sapo.entities.TransaccionInterna</class>
    <class>sapo.entities.TransaccionExterna</class>

    <properties>
        <!-- Properties for Hibernate -->
        <property name="hibernate.hbm2ddl.auto" value="update" />
        <property name="hibernate.show_sql" value="false" />
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
    </properties>
</persistence-unit>

And this is my Administrador class
@Entity
public class Administrador extends Usuario {

public Administrador(){
}

public Administrador(String nick, String password, String nombre,
        String mail, String direccion, Date fechaNacimiento,
        String linkImagen) {
    super(nick, password, nombre, mail, direccion, fechaNacimiento, linkImagen);
    // TODO Auto-generated constructor stub
}

}

Usuario is an abstrac class
@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Usuario {
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    @Basic(optional = false)
    private Long id;
    //attribs, Getters setters and other methods
}

The most strange is this line from jboss stack trace
java.lang.ClassNotFoundException: uy.edu.fing.tsi2.sapo.entities.Administrador

This directory was all changed to just sapo.entities.Administrador, the long path was from an old version. I deleted this old project and cloned it again from git, I also deleted all files from C:\Program Files\jboss-as-7.1.1.Final\standalone\deployments but stack trace keep throwing this old path.
My team mates are using the same configuration, cloned from the same git repository without any problem while I'm stacked with this.

A: Finally I solved it, it was a problem in maven project configuration in one of the pom.xml, we had some problems with group ids from artefact and parents.
I don't have the exact answer because my team mate was who solved it, I'll ask her and update this answer with more detail later.

A: If you have entries in your xml file as well as annotation for the corresponding class then sometime it cause problems. Try to remove one of both either annotation or xml entry for the corresponding class and then run again. Hope this helps.


text:
Q: Removing IP from IIS Site Binding Guys I am trying to remove a specific IP from IIS site bindings through C# (Microsoft Web Administration).
Basically what I want to do is, is to check all site's binding in IIS and if any binding IP matches user-provided IP, it should remove it and if the particular site doesn't have any other bindings with different IP then it should stop the site.
However, I can't seem to remove the IP in a loop as I am getting "Collection was modified; enumeration operation may not execute." error.
This is my code :
static void Main(string[] args)
{
    ServerManager mgr = new ServerManager();

    foreach (Site s in mgr.Sites)
    {
        Console.WriteLine("Site {0}", s.Name);

        foreach (Application app in s.Applications)
        {
            Console.WriteLine("\tApplication: {0}", app.Path);

            foreach (VirtualDirectory virtDir in app.VirtualDirectories)
            {
                Console.WriteLine("\t\tVirtual Dir: {0}", virtDir.Path);
            }
        }

        BindingCollection bindingCollection = s.Bindings;
        foreach (Binding b in  bindingCollection)
        {
            Console.WriteLine("\n Bindings: {0}",b.EndPoint);
            if (b.EndPoint != null)
            {
                //Hard Coded IP for testing purpose
                if (b.EndPoint.ToString() == "1.1.1.1:86")
                {
                    Console.WriteLine("Removing this ip : {0}",b.EndPoint.ToString());
                    bindingCollection.Remove(b);
                }
            }
        }
      mgr.CommitChanges();
    }
    Console.ReadLine();
}

What should I do to remove the binding ? I need to remove it in a loop because a site may have more than 1 binding which uses the same IP.

A: The enumerator is versioned for most collections that are part of the BCL, meaning that you cannot modify a collection while you are looping over it. You can copy the collection like so:
var bindingCollection = new List<Binding>(s.Bindings);

So now your loop looks like this:
var bindings = s.Bindings;
var bindingCollection = new List<Binding>(bindings);
foreach (Binding b in bindingCollection)
{
    Console.WriteLine("\n Bindings: {0}", b.EndPoint);
    if (b.EndPoint != null)
    {
        //Hard Coded IP for testing purpose
        if (b.EndPoint.ToString() == "1.1.1.1:86")
        {
            Console.WriteLine("Removing this ip : {0}", b.EndPoint.ToString());
            bindings.Remove(b);
        }
    }
}

However, this does not actually remove the binding like you expect it to. You need to call b.Delete() to actually delete the binding. When you use Remove, all you are doing is removing it from the collection that was built from existing bindings. So add b.Delete() before you remove it from the collection.


text:
Q: Jmeter Regex http response I am trying to "catch" a  value from a json response using regex.
The response:
{"Result":0,"ResponseStatus":{"ErrorCode":null,"Message":null,"StackTrace":null,"Errors":null},"SessionId":"5a004b3b-f610-4a4e-9a0c-9953cee9bd47","ResponseHeader":{"Succeeded":true,"Errors":[]}}

I have created a HTTP request and added a child "JSON PATH EXTRACTOR" with the following data:
Destination Variable Name: SessionId_Regex
JsonPath Expression: "SessionId":"(.{8}-.{4}-.{4}-.{4}-.{12})"
The question is: how do i use the variable of the regex in a 2nd HTTP request
Thanks :)

A: JSON Path has nothing in common with Regular Expressions, you won't extract the value using above expression.
Change it to: $..SessionId[0]
You can refer extracted value directly as ${SessionId_Regex} or using __V() function like ${__V(SessionId_Regex)}  where required
References:

*

*JSONPath - XPath for JSON

*Using the XPath Extractor in JMeter (scroll down to Parsing JSON)


text:
Q: How to scale down UIElement in WPF and see what's originaly outside the window? I got an UIElement who's bigger than the place it need to take. But when i scale down it using a renderTransform, the part of the element originaly hide , stay hide.
<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <Rectangle Fill="Orange" Stroke="Black" StrokeThickness="5" Width="600" Height="500" Margin="20" HorizontalAlignment="Left">
        <Rectangle.RenderTransform>
            <ScaleTransform ScaleX="0.5" ScaleY="0.5"/>
        </Rectangle.RenderTransform>
    </Rectangle>
</Grid>

How can I achieve the scale and gets all the UIElement ?

A: An example to illustrate the solution you recieved in comment would be :
If you have a coloured rectangle with a text inside and you do a 90° rotation:

*

*With LayoutTransform, you would get the rectangle rotated and the text inside would look normal, since the transformation is applied before calculating the content

*With RenderTransform, you would get the rectangle rotated and the text inside rotated as well, since the rectangle AND the text would be generated before doing the rotation.

For your example it gives:

*

*With LayoutTransform, you scale the area, and then calculate its possible content

*With RenderTransform, you calculate the content, and then scale both area AND its content.


text:
Q: nestjs borrar archivos xlsx de capeta upload tengo un servidor en nestjs donde tengo una carpeta llamada /upload/, en esta es donde guardo los archivos que necesito mostrar y descargar, por ejemplo imágenes y archivos de Excel para descargar, las imágenes las almaceno en esa ubicación y deben quedar hay , pero los archivos de Excel que se almacenan hay quiero borrarlos porque después que se descargan no lo necesito, pienso en crear un cron para correr ese servicio los domingos, pero no se como hacer para decirle al node que me borre solo los archivos con esa extensión.
agradezco cualquier ayuda,


text:
Q: ParametricPlot and Piecewise function I want to create a ParametricPlot with multiple Piecewise functions in it. I have tried the following code but it doesn't work
ParametricPlot[Piecewise[{{Cos[x] + x/2, 1 > x > 16}, {Sin[x], 16 > x > 20}}], {x, 0, 21}, Axes -> True]

Basically I want my graph to show a loop but only for a certain interval, as shown in this image:

I used the following command for it:
ParametricPlot[{Cos[x] + x/2, Sin[x]}, {x, 1, 16}]

A: For example:
ParametricPlot[{Cos[x] + x/2, Sin[x]}, {x, 0, 21}, Axes -> True,
               RegionFunction -> (0 < #1 < 4 || 6 < #1 < 8 &)]


text:
Q: select partially matching filenames I have two lists of files with slightly different naming conventions
files1 = {"DTideal_circ_def=000um_astX=000um_astY=410um.png","DTideal_circ_def=050um_defX=000um_defY=010um.png"}

files2={"DT120_blur7_Defoc=000um_AstigX=000um_AstigY=410um.png",
"DT120_blur7_Defoc=000um_AstigX=460um_AstigY=310um.png",
"DT120_blur7_Defoc=000um_AstigX=460um_AstigY=360um.png",
"DT120_blur7_Defoc=000um_AstigX=460um_AstigY=410um.png",
"DT120_blur7_Defoc=000um_AstigX=460um_AstigY=460um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=010um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=060um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=110um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=160um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=210um.png",
"DT120_blur7_Defoc=050um_AstigX=000um_AstigY=260um.png"}

I need to create pairs of files the paremeters of which are matching, i.e. to get
{{"DTideal_circ_def=000um_astX=000um_astY=410um.png","DT120_blur7_Defoc=000um_AstigX=000um_AstigY=410um.png"},
{"DTideal_circ_def=050um_defX=000um_defY=010um.png","DT120_blur7_Defoc=050um_AstigX=000um_AstigY=010um.png"}}

A: First, join the two groups:
Join[files1, files2]

Then gather them by their last 3 numbers like:
StringCases["DT120_blur7_Defoc=050um_AstigX=000um_AstigY=260um.png", DigitCharacter ..]

(*Out: {"120", "7", "050", "000", "260"} *)

StringCases["DT120_blur7_Defoc=050um_AstigX=000um_AstigY=260um.png", DigitCharacter ..][[-3;;]]

(*Out: {"050", "000", "260"} *)

GatherBy[Join[files1, files2], StringCases[#, DigitCharacter ..][[-3 ;;]] &]

Then select groups that have two elements:
Select[GatherBy[Join[files1, files2], StringCases[#, DigitCharacter ..][[-3 ;;]] &], Length[#] == 2 &]

(*Out: {{"DTideal_circ_def=000um_astX=000um_astY=410um.png",
         "DT120_blur7_Defoc=000um_AstigX=000um_AstigY=410um.png"},
        {"DTideal_circ_def=050um_defX=000um_defY=010um.png",
         "DT120_blur7_Defoc=050um_AstigX=000um_AstigY=010um.png"}} *)


text:
Q: ListView add image button with CommandName, Visible, CommandArgument dynamically by calling Eval() Attached desire output (Record(s)))
right now i can add multiple links to Records column but cannot add muliple image button  with command name and command arguments

I tried to create image button dynamically by calling GetRecordLinks(Eval("Records"))` from code behind, below is my code
<asp:ListView ID="Student" runat="server" OnItemCommand="Student_ItemCommand" OnItemDeleting="Student_ItemDeleting" OnItemDataBound="Student_OnItemDataBound">
        <LayoutTemplate>

                    Name
                    Class(s)
                    Sex
                    Recordss
                     Status
                    Activate/Delete

                <asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>

        </LayoutTemplate>
        <ItemTemplate>

                    <%# Eval("StudentLastName") %>, <%# Eval("StudentFirstName") %> <%# Eval("StudentMiddleName") %>

                    <%# JoinStringList(Eval("class")) %>

                 <%# Eval("sex") %>

                    <%# GetRecordLinks(Eval("Records")) %>

                    <%# Eval("StatusID").ToString()=="0"?"Inactive":"Active" %>

                   <asp:ImageButton ImageUrl="img/Refresh.png" ID="StudentActive"  runat="server" CommandName="Active" Visible='<%#Eval("StatusID").ToString()=="0"?true:false%>' CommandArgument='<%# Eval("StudentGUID") %>' />
                    <asp:ImageButton ImageUrl="img/delete.png" ID="StudentDelete" runat="server" CommandName="Delete" Visible='<%#Eval("StatusID").ToString()=="0"?false:true%>' CommandArgument='<%# Eval("StudentGUID") %>' />

        </ItemTemplate>
    </asp:ListView>

GetRecordLinks method below
I want to append asp:ImageButton with CommandName ,Visible,CommandArgument for each record of student.
for eaxmple if student A have 5 records each five record in a cell, should have 5 imagebutton with iteamcommand so that i can delete or activate the record depend on use wish.
public string GetRecordLinks(object obj)
    {
        if (obj != null)
        {
            List<AppointmentDoc> docs = (List<AppointmentDoc>)obj;
            StringBuilder sb = new StringBuilder();
            foreach (AppointmentDoc rec in docs)
            {
                sb.Append("" + rec.Name.Replace("student", "").Trim() + " (" + rec.SignedBy + ")" + (rec.staffSigned ? "*" : "") + "
");
            }
            return sb.ToString();
        }
        return "";
 }

hope understand my question
let me know if any queries
thanks

A: You could use a PlaceHolder and add your ImageButtons to it. First, replace:

    <%# GetRecordLinks(Eval("Records")) %>

with:

    <asp:PlaceHolder ID="phRecords" runat="server" />

Then in code-behind:
void Student_OnItemDataBound(object sender, ListViewItemEventArgs e)
{
    ...
    PlaceHolder phRecords = e.Item.FindControl("phRecords") as PlaceHolder;
    ImageButton imgButton = new ImageButton();
    // Set the ImageButton properties here
    ph.Controls.Add(imgButton);
}

That would add a single button. You can put the ImageButton creation code in a loop to add several of them in the same cell.
You would also have to recreate those ImageButtons on every postback, so you may need to bind your data in the Page_Load method.


text:
Q: How to hide checkboxes in a QTableView using python? I'm quite new to python as well as to Qt. I would like to use the QTableView without checkboxes appearing in the tableview's cells, but as it seems they just appear there by default. As I've found out so far, you just have to deactivate the Qt.ItemIsUserCheckable flag. But how am I supposed to do this? I tried to use the flags - function of the QAbstractItemModell inside a QAbstractTableModel derived model class this way:
def flags(self,index):
        return(QtCore.Qt.ItemIsEnabled| QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable)

So, what I did is: just not returning the Qt.ItemIsUserCheckable flag. This works fine e.g. for the Qt.ItemIsEditable flag making a cell editable or not (when it is not returned) but doing this with the ItemIsUserCheckable flag has no effect on the checkboxes. So my question is: how can I get rid of the checkboxes using python? Please help!

A: Well, I think I could sort this out on my own. The secret of the QTableView's checkboxes doesn't lie in the flag method but goes with the return value of the data-method instead. The description of the data method of QAbstractItemModel explains that you should return an invalid QVariant for those cases you donn't want to handle. In PyQt4.11 this means that you have to return python's None value, because None is interpretated as invalid QVariant. So all I had to do was to make sure that the data method returns None when I don't want to handle a role:
# works for python 3.4 and PyQt4.11
def data(self,index,role):
    if not index.isValid():
        return(None)
    # for all roles you're not interested in, do nothing: i.e. return python's None which is interpreted as an invalid QVariant value
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else:
        return(self.data[index.row()][index.column()])

Notice, that the code returns None for Qt.CheckStateRoleas this role is one of no interest to the code and that no checkboxes are displayed in the GUI.
Now, if you change the data method like this:
def data(self,index,role):
    if not index.isValid():
        return(None)
    elif role == QtCore.Qt.CheckStateRole:
        return("")
    elif role != QtCore.Qt.DisplayRole:
        return(None)
    else:
        return(self.data[index.row()][index.column()])

a string ("") is returned for the Qt.CheckStateRole which of course is not an invalid QVariant. And -surprise, surprise - checkboxes are displayed inside the TableView.
Another point is that all this works without to implement the flags method I mentioned above.

A: This catch occurs with PyQt5 as well: a QAbstractTableModel's data method must return None unless it's addressing a specific role.
So when you instantiate a model table view, each and every possible role that you might employ to give each cell attributes (such as a checkbox, a font, alignment and so on) calls the view's data method. It uses that call to determine whether it is required to help create the cell. If upon querying the method, it is told None, it does nothing.
This shouldn't be a problem, since Python methods return None if you let them run off the end.
So, with a model view designed to simply show data in each cell addressed by (row, column), it is sufficient to simply cater to that specific display role when writing the data method.
def data( self, index, role ):
    if role == Qt.DisplayRole:
        return self.mymodeldata[ index.row() ][ index.column() ]

The many other possible roles each also call the data method and get None in return. Thankfully, you don't have to address None to each of them specifically.
Beware though, that you do return None to all roles but those you do address in the data method, and do not instead return, say, False, as you would with some neat and clumsy logic like:
def data( self, index, role ):
    return role == Qt.DisplayRole and self.mymodelData[ index.row() ][ index.column() ]

In that case, every other role gets told False. When CheckStateRole comes knocking, and gets told False, it duly shows empty checkboxes.
This would address all cases without such error:
def data( self, index, role ):
    return role == Qt.DisplayRole and self.mymodelData[ index.row() ][ index.column() ] or None