text:
Q: .htaccess rewrite works fine with number but not letters? When I write www.example.com/foo/1 it works fine but when i write www.example.com/foo/count or any letter it says
Not Found
The requested URL foo/count was not found on this server.
but everthing works fine when I try foo/12 or any number is passed? whats wrong or what am I missing here?
RewriteEngine On
RewriteBase /
RewriteRule ^([^/]+)/(\d+)/? $1.php?key=$1

A: Try this :
RewriteEngine On
RewriteBase /
RewriteRule ^([^/]+)/([^/]+)/? $1.php?key=$1 [NC,L]

The pattern [^/]+ matchs any characters 1 or more times except the "/".


text:
Q: Regex expression for extracting numbers followed by 'KGS' I would like to identify and extract numeric values followed by 'KGS' (no space between number and 'KGS'. The strings might contain other numbers NOT followed by 'KGS' that should be ignored. Example:
This is a 123 sample (500KGS) string.

500 should be extracted.

A: I suggest using a less strict pattern here since you are not validating, but extracting values. Right now, your regex will only extract 56, 578.56 or 52,456 like values, and values like 2,400.56 won't get matched.
Use
/\d[\d.,]*(?=\s*KGS)/i

See the regex demo. Or, with capturing:
/(\d[\d.,]*)\s*KGS/i

The result is in Group 1. See another demo.
The \d[\d.,]* will match a digit, and then zero or more digits, . or ,.
The /i modifier will make the regex case-insensitive. Depending on the regex flavor, you may even use an inline version of this modifier, (?i) - just put it at the pattern start.

A: Here's the answer:
(\d+(?:[.,]\d+)?)\s?(KGS)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting a List of Base type to a List of Inherited Type I would be certain that this question addresses something that would have been brought up in a previous question, but I was unable to find it.
There is a method in a C# class that takes as a parameter a generic List of a Base Class.  I need to pass a list of an inherited class and do not know exactly how to do this.  I am getting an error in my attempts.  Below is sample code to illustrated this:
public class A
{
   public static void MethodC(List<A>)
   {
       // Do Something here with the list
    }
}
public Class B : A
{
   // B inherits from A, A is the Base Class
}

// Code utilizing the above method
List<B> listOfB = new List<B>();
A.MethodC( (List<A>) listOfB );  // Error: this does not work
A.MethodC( listOfB.ToList<typeof(A)>() ); // Error: this does not work
A.MethodC( listOfB.ConvertAll<A>(typeof(A)) ); // Error: this does not work
// how can I accomplish this?  It should be possible I would think

Note:  Here is my final working  Method as a reference.  I got an even better solution to my problem, but technically it wasn't an answer to the question, since my question was phrased impropertly.
 public static DataTable
    ObjectCollectionToDataTable<GLIST>
      (List<GLIST> ObjectCollection) where GLIST
              : BaseBusinessObject
        {
            DataTable ret = null;

            if (ObjectCollection != null)
            {
                foreach ( var b in ObjectCollection)
                {

                    DataTable dt = b.ToDataTable();
                    if (ret == null)
                        ret = dt.Clone();
                    if (dt.Rows.Count > 0)
                        ret.Rows.Add(dt.Rows[0].ItemArray);
                }
            }

            return ret;
        }

A: You cannot do that. To understand why it is not allowed, imagine what would happen if Add was called on a List<Derived> after it had been cast to a List<Base>.
Also, the answers implying that C# 4.0 will be different are wrong. List will never be modified to allow you to do this. Only IEnumerable will - because it does not allow items to be added to the collection.
Update: The reason it works in the solution you've gone for is because you're no longer passing the same list. You're creating a whole new list which is a copy of the original. This is why I asked about modifying the list; if MethodC makes changes to the number of items on the list, those changes would be made to a copy, not the original list.
I think the ideal solution for you is as follows:
public abstract class A
{
    public void MethodC<TItem>(List<TItem> list) where TItem : A
    {
        foreach (var item in list)
            item.CanBeCalled();
    }

    public abstract void CanBeCalled();
}

public class B : A
{
    public override void CanBeCalled()
    {
        Console.WriteLine("Calling into B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<B> listOfB = new List<B>();

        A a = new B();

        a.MethodC(listOfB);
    }
}

Notice how, with this solution, you can pass a List<B> directly to MethodC without needing to do that weird conversion on it first. So no unnecessary copying.
The reason this works is because we've told MethodC to accept a list of anything that is derived from A, instead of insisting that it must be a list of A.

A: You are addressing the lack of covariance in the current C# version.  Here is one way of doing it:
listOfB.Cast<A>();

A: If you have linq available you can do
var ListOfA = ListOfB.Cast<A>().ToList();

A: Here is an answer that will exclude any objects in your list of the wrong type. This is a much safer way in my opinion:
List<A> ListOfA  = ListOfB.OfType<A>().ToList();

The OfType method will exclude items of the wrong derived class where as the Cast will throw an error.


text:
Q: Tantalum capacitor selection in LT3652 Buck Converter
In this circuit, a buck solar single cell Li-Ion battery charger, I need to select C3 and C4 tantalum capacitors. \$V_{BAT(FLT)}\$ is going to be 4.2 V, hence I selected:
\$C3_{VMAX}=10\text{ V}\$
\$C4_{VMAX}=10\text{ V}\$
Datasheet suggests low ESR tantalum capacitors but the supplier has capacitors ranging from \$1\text{ }\Omega\text{ to }80\text{ }\text{m}\Omega\$.

*

*Are the \$C3_{VMAX}\$ and \$C4_{VMAX}\$ values I picked, correct for this application?

*What ESR values should I pick for the tantalum capacitors for this application, and why?


text:
Q: INDEX MATCH with Two Criteria - Error w/ Cell Autofill I am working on a hiring trends report and have an Excel table with multiple entries per ID/individual (as several individuals have left and been rehired over years). The table looks something like this:
WORKSHEET: SHEET1
A       B           C              D
ID      Name        Location       Hire Date
1122    Karen       Chicago        01/01/2018
1038    Tom         Chicago        05/22/2016
2845    Angel       Pittsburgh     11/15/2016
1122    Karen       New York       10/08/2013
4992    Mallory     Seattle        09/14/2015
2845    Angel       Pittsburgh     07/21/2011
1122    Karen       Pittsburgh     08/22/2011

I have created a new table with only one entry per person and their most recent hire date. The next step is to populate the table with location data based on the person's ID and specified hire date.
My approach was to use an INDEX-MATCH expression with two match statements (one for ID and one for hire date):
=INDEX('SHEET1'!$C$2:$C$2000,
MATCH('SHEET2'!A2,'SHEET1'!$A$2:$A$2000,0),
MATCH('SHEET2'!D2,'SHEET1'!$D$2:$D$2000,0))

The first row where I enter the expression retrieves the correct location data. However, when I attempt to populate the remaining rows in that column, I get a #REF! error, as illustrated below.
WORKSHEET: SHEET2
A       B           C              D
ID      Name        Location       Hire Date
1122    Karen       Chicago        01/01/2018
1038    Tom         #REF!          05/22/2016
2845    Angel       #REF!          11/15/2016
4992    Mallory     #REF!          09/14/2015

I've tested each INDEX-MATCH expression separately (first testing for a match only on ID and then testing for a match only on hire date). Each one works separately, and as shown above, it does work for the first row--it just will not autofill for other rows. I've also checked SHEET1 and each individual definitely has the correct matching criteria on SHEET2 for referencing.
Can anyone help with either suggesting a way to fix my expression or an alternative way to retrieve the location data based on two criteria? Thanks in advance!

A: The third argument to INDEX is the column number, which is why you get a #REF error. You can use LOOKUP instead:
=LOOKUP(2,1/('SHEET2'!A2='SHEET1'!$A$2:$A$2000)/('SHEET2'!D2='SHEET1'!$D$2:$D$2000),'SHEET1'!$C$2:$C$2000)

A: you can use this formula :
=INDEX(Sheet1!C1:C2000;MATCH(1;INDEX((Sheet1!A1:A2000=Sheet2!A1)*(Sheet1!D1:D2000=Sheet2!D1);0;1);0))
so you can use more than one criteria in secend index like this:
=INDEX((criteria1)*(criteria2)*(criteria3);)


text:
Q: Parse JSON with PHP and assign to variable I have the following JSON file that I need to extract a value and assign it to a PHP variable. The value I need is "icn".
{
  "apiVersion": "1.0",
  "data": {
    "updated": 20160331141332,
    "totalItems": 1,
    "currentItemCount": 1,
    "items": [
      {
        "birthDate": "20171101",
        "fullName": "DOE,JOHN D",
        "icn": "889081784V888383",
        "pid": "55R1;60004"
      }
    ]
  }
}

I have tried the following but get no results.
$myjson = file_get_contents('http://testurl.org/info.json');
print_r(json_decode($myjson->data->items[0]->icn,true));

echo "
LAST-Error:"; echo json_last_error();
echo "
LAST-Error-Msg:"; echo json_last_error_msg();

Results are
LAST-Error:0
LAST-Error-Msg:No error

A: I figured out where I went wrong.
$myjson = file_get_contents('http://testurl.org/info.json');
$dec = (Array)json_decode($myjson,true);
$ICN = $dec["data"]["items"][0]["icn"];

A: $myjson is a string, you treat it as object:
$myjson->data->items[0]->icn

You have to first decode JSON string, then you can retrieve JSON elements.
Simply move closing parenthesis and remove True option:

print_r( json_decode( $myjson->data->items[0]->icn, true ) );
#                             ┌──────────────────────────┘
print_r( json_decode( $myjson )->data->items[0]->icn );


text:
Q: How to make a button move? I'm going to make 8 buttons move down to the bottom of screen one by one but I have a problem
here is my code :
var i = 0;
var j = 0;
while(i < 7){
   i++;
   interval[i] = setInterval(interval(), 10);
   function interval(){
      y[j]++;
      if (parseInt(y[j]) >= window.innerHeight) {
        if(j == y.length - 1){
            debugger;
            return clearInterval(interval[j]);
        }
        j++;
        return interval();
      }
      button[j].style.top = y[j] + "px";
   }
   console.log(i);
}

var body = document.getElementById("body");
var button = [];
body.style.position = "relative";
var y = [];
for (var i = 0; i < 8; i++) {
    y[i] = 0;
    button[i] = document.createElement("button");
    button[i].onclick = clickme();
    button[i].innerHTML = "بازی";
    button[i].style.fontFamily = "b nazanin";
    button[i].style.fontSize = "32pt";
    button[i].style.position = "absolute";
    body.appendChild(button[i]);
}
var i = 0;
var j = 0;
var Interval = setInterval(interval(), 10);
function interval(){
    y[j]++;
    if (parseInt(y[j]) >= window.innerHeight) {
        if(j == y.length - 1){
            debugger;
            return clearInterval(Interval[j]);
        }
        j++;
        return interval();
    }
    button[j].style.top = y[j] + "px";
}
/*

var button2 = document.createElement("button");
button2.onclick = clickme();
button2.innerHTML = "بازی";
button2.style.fontFamily = "b nazanin";
button2.style.fontSize = "32pt";
body.appendChild(button);
body.appendChild(button2);
body.style.position = "relative";
button2.style.position = "absolute";
button.style.position = "absolute";
*/
function clickme() {

}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>
<body id="body">

</body>
<script src="index.js"></script>
</html>

Code explained :
button is my buttons element array.
y is my button's Tops array.
My problem is that the first button will move 7 times(Number of Is) and anything stop.I don't know what to do.
Please help me.

A: Ok, I did it with just 2 buttons and it worked :

var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var startNext = false;
var y1 = 0;
var y2 = 0;
var interval1 = setInterval(function(){
    y1++;
    button1.style.top = y1 + "px";
    if(y1>= window.innerHeight){
        startNext = true;
        return clearInterval(interval1);
    }
},10);
var interval2 = setInterval(function(){
    if(startNext){
        y2++;
        button2.style.top = y2 + "px";
        if(y2 >= window.innerHeight){
            return clearInterval(interval2);
        }
    }
},10);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="index.css">
</head>
<body id="body" style="position: relative;">
    <button id="button1" style="position: absolute;">graege</button>
    <button id="button2" style="position: absolute;">ges</button>
</body>
<script src="index.js"></script>
</html>


text:
Q: Cordova localStorage data recovery I have an Ionic app that was side-loaded onto an Android device that kept data in localStorage. The usual mechanism for syncing the data back to our server has failed, and cannot be manually triggered from within the app. Recovering this data is important to a client. Is there any way to access this data? Can it be accessed through a different app that shares an ID with the original? Can the JS in the original be modified in place so that it posts out the data to a rest endpoint? Does Android keep localStorage on the filesystem in a way that is accessible? I have physical access to the device in question.
Thanks


text:
Q: extracting FILE* from C++ istream Object I'm fairly new to C++ programming and facing an issue.
I have an istream object and i need to link it to a C library which requires FILE* pointer.
Is there a way to extract a FILE* from istream object, if not what is the best way to solve this problem?


text:
Q: Changing A ComboBox to a TextBox inside a UserForm Question in title. Seems like something which should be really simple, but i just cannot find it. I am in Design Mode. See picture below, but it's nothing out of the ordinary, really. Really grateful for any suggestions.

In case it matters: This is Excel 2010.

A: Why would you do it?
I don't think you can change type of components. You could place textbox in the same place as combobox and hide/unhide them (change Visible property to true or false) separately.


text:
Q: Copy Presentation Details to new PlaceHolder programmatically Sitecore 7.2 currently I am working on a page that generates a print view of a specific item. So this means I dont need all the stuff from my MainLayout like Navigation etc.
For this reason I have created a new Layout that only has a placeholder.
Lets call this PrintLayout.aspx:
<sc:placeholder ID="PlPrint" runat="server" key="phPrintOutput"></sc:placeholder>

In the code behind I have a method that fetches the renderings from the item, but I am stuck at the point where I want to copy them to my phPrintOutput Placeholder on the fly:
public void AddPresentationDetailsToPlaceHolder(Item item)
{
  List<RenderingReference> renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, false).ToList();
  foreach(RenderingReference r in renderings)
  {
    // How can I apply the renderings on the fly to my phPrintOutput Placeholder??
  }
}

Of course it is very important that every sublayout keeps it current datasource.
Any help would be appreciated, thank you all

A: You only require to add the control to the placeholder. To do so, please see the code below:
public void AddPresentationDetailsToPlaceHolder(Item item)
{
  List<RenderingReference> renderings = item.Visualization.GetRenderings(Sitecore.Context.Device, false).ToList();
  foreach(RenderingReference r in renderings)
  {
      if(r.RenderingID == new ID("Rendering Id you want to be displayed on layout"))
      {
          this.PlPrint.Controls.Add(r.GetControl());
      }
  }
}

This will automatically add the rendering to the layout.


text:
Q: Using predicate logic to verify the theorems of Euclid's elements? I wanted to make a "logical" march through the entirety of Euclid's elements by proving and verifying, step by step, each theorem using Hilbert's axioms as a basis. Of course, I would want to do this all in the symbolic language of predicate logic using a natural deduction format. Has anyone out there done anything like this yet? What would Hilbert's axioms look like when translated into predicate logic? Any tips or pointers would be welcome. Thank you!

A: We (the GeoCoq team) are currently formalizing some propositions of Euclid's Elements using the Coq proof assistant.
Our formalization is based on either Tarski's axioms or Hilbert's axiom as we have shown formally that the first three groups of Hilbert's axiom are bi-interpretable with the corresponding Tarski's axioms (excluding continuity) (https://hal.inria.fr/hal-01332044/file/hilbert_to_tarski.pdf).
You can find a formalization in predicate logic of Hilbert's axioms and a discussion about the formalization and related works in the above paper. It is not completely trivial, because Hilbert's axioms are stated in natural language, and one need to find what is the right interpretation. For example, the concept of a point being inside an angle is not defined by Hilbert. Our formal proofs, shows that our interpretation is enough to reconstruct an ordered field and also prove Tarski's axiom.
You can find Hilbert's axioms formalized in Coq here:
http://geocoq.github.io/GeoCoq/html/GeoCoq.Axioms.hilbert_axioms.html
Most of the propositions of the first book of Euclid can be found in the GeoCoq library (http://geocoq.github.io/GeoCoq/).

A: See :

*

*Sara Negri & Jan von Plato, Proof Analysis : A Contribution to Hilbert's Last Problem (2011) : Part III. Proof systems for geometric theories, page 131-on.


text:
Q: Update the attributes of a java object from a thread? The value of the variable var is always 0. IT is almost as if the method was never called. I would like to be able to change the value of val from inside the thread and if I call getVal() I would like to be able to have access to the new value.
public class Test1 {
    private int val;

    public Test1() {
        val=0;
    }

    public void changeVal() {

        new Thread(new Runnable() {
            public void run() {
                val=1;
            }
        }).start();
    }

    public int getVal() {
        return this.val;
    }

    public static void main(String[]args) {
        Test1 x=new Test1();
        x.changeVal();
        System.out.println("VAl: "+x.getVal() );
    }
}

A: The value is changed, however getVal() is (most of the time) executed before var=1 in method 'run'. The order of execution is controled by thread scheduler, but as told by Johnny Mopp, adding .join() will fix it.
  public void changeVal() throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                val = 1;

            }

        });
        t.start();
        t.join();

    }

    public static void main(String[] args) throws InterruptedException {
        Test1 x = new Test1();
        x.changeVal();

        System.out.println("VAl: " + x.getVal());
    }

A: You have set up a race condition between your statement
  x.changeVal();

and
 System.out.println("VAL: "+x.getVal() );

Try putting the following code between the above two statements.
    try {
        Thread.sleep(100);
    }
    catch (Exception e) {
        System.out.println("Exception: " + e);
    }

This gives your new thread a chance to be established before you reach the println statement.

A: you need to change your main method like below:
public static void main(String[]args)
 {
    Test1 x=new Test1();
    x.changeVal();
   try {
        Thread.sleep(100);//sometime here
    }
    catch (Exception e) {
        System.out.println("Exception: " + e);
    }
    System.out.println("VAl: "+x.getVal() );

 }

Or
You can use Thread.join(); to join Main thread with child thread in changeVal() method.

A: One soultion could be use of ReentrantLock
Define this as class member variable
Lock lock = new ReentrantLock();

Use this lock in changeVal
public void changeVal() throws InterruptedException {
    if (lock.tryLock()) {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    val = val + 1;
                }
            }).start();

        } finally {
            lock.unlock();
        }
    }

}

A: You need to make the variable volatile, and you need to arrange some synchronization or locking if you want the variable to be changed before you print it in the main method. Which makes the thread completely pointless.
Hard to see the point of any of it really.


text:
Q: Element disappears again immediately after fadeIn () http://robinj.be/unity-2d-config-util/
In the source code there's this:

    <?php include ('pages/home.php'); ?>

    <?php include ('pages/screenshots.php'); ?>

But when opening the page, Firebug only shows the div.cash.page#home part.
When you click the camera icon at the bottom of the page, what should happen is this:

*

*The current page disappears.

*A page with screenshots fades in.

But what happens is this:

*

*The current page disappears.

*The page with screenshots fades in.

*The page with screenshots disappears.

What could be the problem in this situation?
--Edit--
For the Recent revisions block, I download a page from Launchpad, which I then filter by using a Regular Expression. Apparently, though, my regex takes a bit too much HTML with it :/

A: On my Chrome they are loaded behind your background. When adding position: relative; to the wrapper div (dash page) they appear on top.

A: This may not apply to the specific scenario here, but I came upon this page when encountering a similar issue with HTML/jQuery and realized later that the issue stemmed from forgetting to add event.preventDefault(); to the event handler, in case that is helpful to those troubleshooting this issue in the future.


text:
Q: MySQL INSERTing rows into a database with datetime sanity checks I am making a meeting room booking system in which there should be no times within the start and end dates so in theory the validation should check for no dates/times within one start and end date time frame.
I have two tables, I can insert into it fine with both start and end dates so the only columns i am interested in at the moment are these
meetingrooms
|------------------------------------||- bookingtime -|-bookingend-|
I understand the principle behind the sanity check and the check i can do in psudocode. Here is the code i have got so far -
>
p4a_db::singleton()->query("INSERT INTO meetingrooms(location_id, bookingtime, bookingend, merono_id)
                WHERE bookingtime < " . $date . " AND bookingend > " . $date . "
                OR
                bookingdate < " . $date . " AND bookingend > " . $dateend . "
                VALUES(?,?,?,?)",
                array($location, $date, $dateend, $merono));

I don't want to insert data directly into the statement but until i understand how to do this i am stuck, so the question,
How do i perform a sanity check before the data is inserted so that i don't get dates within booked times.
any help would be greatly appreciated.

A: Edit:
I've been overthinking my answer and I realized that the old solution will not work in your case since you need the time span, comparing the start and end date is useless.
My way of processing this would be:

*

*Save the dates as int, use 24h system (7:40am is 740, 9:50pm is 2150)

*Check for stored dates where: (Start<NewStart<End)

*Check for stored dates where: (Start<NewEnd<End)

*When processing several rooms, just store room number + time as int. That way you can    still use the method from 2 and 3.

2 and 3 can be done in a sql query, check out this link.
Old answer (checking for duplicates)
This is an example of how to check for duplicates (in this case email) before inserting the text:
    $emailexist = $mysqli->prepare("select email from users where email = ?");
    $emailexist->bind_param('s', $email);
    $emailexist->execute();
    $emailexist->store_result();
    if ($emailexist->num_rows > 0) {
        $emailexist->close();
        $mysqli->close();
        return true;
    }
    else {
        $emailexist->close();
        $mysqli->close();
        return false;
    }

It checks if there are rows which contain the string. If so (if number of rows higher than 0) it returns true (which means, the date already exists).
You can just adapt this to you code.
However, you could also just set the columns to UNIQUE. Then you get an error when trying to insert it. It is easier and you won't have problems with concurrent connections.

A: after a long and intensive search, I have now got a working example of this method, along with a method of protecting against sql injection, here's the code;
if ($this->BookingValue == 1)
    {
        $sql = "SELECT COUNT(*) as num FROM meeting_room_bookings
                WHERE
                (
                (? < start_at AND ? > start_at)
                OR
                (? > start_at AND ? < end_at)
                )
                AND
                meeting_room_id = ?";

        $result = p4a_db::singleton()->fetchRow($sql, array($date, $date, $date, $dateend, $merono));

        if ( 0 == $result["num"] )
        {

         p4a_db::singleton()->query("INSERT INTO meeting_room_bookings (start_at, end_at, meeting_room_id)
                    VALUES
                    (?,?,?)", array($date, $dateend, $merono));

            return true;
        }
        else
        {
         return false;

There isn't much to explain about this code, but in term of differences, (excluding the change in column names with the table) the query is now prepared before the value is set, then it is possible to use it in an if statement, thus allowing the validation to take place to filter results between different dates.
along with this i have added validation to stop dates from other meeting rooms being included within the statement via the AND statement where the meeting room id is limeted to a single value.
Although now, which will lead on to a separate question is another thrown error that comes from this statement, i know the insert is sound but something from this prepared statement causes the error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
File: Pdo.php, Line: 234
Although now i am looking into a error that is thrown from the prepared statement and will update this answer when there is a fix, thanks for the help.


text:
Q: Asterisk directmedia and NAT I have an Asterisk box with a public IP address and two SIP clients behind the same NAT device; I also have SIP clients behind different NATs. I want to know is it possible for Asterisk to detect if both clients are behind the same NAT and use direct media between them and use other options for clients that are behind different NATs?
PS:I assumed each NAT box has a single external IP address, and this assumption is good for me.

A: Asterisk 11.6 has this feature take a look at sip.conf.example and look for directmedia section.

A: No, not posible.
Reason: most of modern routers have network 192.168.1.0/24, as result it will think almost ALL client in same net.
BUT you can force nat=never directmedia=yes for some clients. With that settings it will work directly, but will not work with server.
Optionaly you can put vpn(openvpn?) tunnel to your networks, add that to localnet= list and use direct routing without NAT.

A: You can try set it to directmedia=nonat.  That way it will only do that if the clients are not behind NAT.  However I don't think it will work for your situation because you would also need the PBX behind the same NAT as the 2 clients which is useless.

A: I have the same setup and it's working.
The configuration needed in Asterisk 1.8 is in sip.conf (or any other included file). I put in the [general] section:
[general]
directmediapermit=192.168.0.0/24 (local_network/netmask)
directmediadeny=0.0.0.0/0
...

And in the SIP devices definition, in this case, SIP phones:
[phones]
nat=no
directmedia=nonat
...


text:
Q: Inserting custom element, attribute gets stripped I made a tinymce fiddle about this problem: http://fiddle.tinymce.com/O0gaab
I add a custom element "custom-block" and a custom plugin to insert that element.
tinymce.PluginManager.add('custom', function(editor, url) {
    editor.addButton('custom', {
      text: 'CUSTOM',
      onclick: function() {
        // Open window
        editor.windowManager.open({
          title: 'Custom plugin',
          body: [
            {type: 'textbox', name: 'src', label: 'SRC'},
            {type: 'label', name: 'title', text: 'Insert content bellow:'},
            {type: 'textbox', name: 'content', multiline: true, style: 'width:500px;height:100px;'}
          ],
          onsubmit: function(e) {
            console.log(e.data);
            editor.insertContent('<custom-block src="' + e.data.src + '">' + e.data.content + '</custom-block>');
          }
        });
      }
    });
});
tinymce.init({
    selector: "textarea",
    plugins: [
        "advlist autolink lists link image charmap print preview anchor",
        "searchreplace visualblocks code fullscreen",
        "insertdatetime media table contextmenu paste custom"
    ],
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | custom",
    //valid_elements: "+*[*]", //when using this option trying to allow everything get an error "Cannot read property 'src' of undefined"
    extend_valid_elements: "custom-block[src]",
    custom_elements: "custom-block"
});

The element, get inserted correctly but without the src attribute.
From the documentation I though that extend_valid_elements: "custom-block[src]" would allow src attribute on a custom-block but it gets stripped everytime.
I also tried to set valid_elements to everything(+*[*]) just in case, but then gets worse because at inserting, I get an error: "Cannot read property 'src' of undefined".
I am making any mistake or what is the problem?

A: The name of the configuration option is extended_valid_elements so you simply named it wrong in your configuration.  It should be:
extended_valid_elements: "custom-block[src]"

I have updated your fiddle (http://fiddle.tinymce.com/O0gaab/1) and things appear to work.


text:
Q: Value of variable is changing without actually changing it in C In the binary search code below value of key is changing automatically after calling the function binarySearch(). Despite the fact key is passed as reference in function binarySearch(). Please let me know what is happening in background which is changing the value of Key.
#include <stdio.h>
int binarySearch(int arr[], int key, int low, int high, int *middle){
    if(arr[*middle] == key)
        return *middle+1;
    else if(arr[*middle] > key && arr[*middle] > 0){
        high = *middle--;
        *middle = (low + high)/2;
        return binarySearch(arr, key, low, high, middle);
    }
    else if(arr[*middle] < key && key < arr[high]){
        low = *middle++;
        *middle = (low + high)/2;
        return binarySearch(arr, key, low, high, middle);
    }
 return -1;
}
main(){
    int arr[] = {1, 2, 3, 4, 5, 6, 7};
    int size = sizeof(arr)/sizeof(arr[0]);
    int key;
    int low = 0;
    int high = size - 1;
    int middle = (low + middle)/2;
    printf("Enter the key to be Searched: ");
    scanf("%d", &key);
    printf("%d", key);
    int result = binarySearch(arr, key, low, high, &middle);
    printf("%d", key);
}


text:
Q: "Shops cannot create Listings in languages other than the Shop's primary language. (fr)" Etsy Request Error I'm using the Etsy2 module on Python to automatically create a listing using the createListing() API request, but unfortunately I always get the following error:
ValueError: Could not decode response from Etsy as JSON: status_code: 400, text: "Shops cannot create Listings in languages other than the Shop's primary language. (fr)", url 'https://openapi.etsy.com/v2/listings'

Is it possible to create a listing in my shop's language instead of English? The language=fr parameter is not supported for this request...
Thank you!


text:
Q: Use Index Match to Return Value Using Lookup Value from Multiple Columns I'm trying to return a value from one column using values from a range of 3 columns. When I enter an electrical, plumbing or gas permit number into a report (D14) I want the corresponding building permit number to be entered into another cell as the file reference. The report is one worksheet and the list of permit numbers is another worksheet in the same workbook. It's one permit one report so I don't think I need anything complicated. VLOOKUP didn't work because I need to search right to left.
This is the Index Match formula I've used but I can only use 1 column as the lookup value and I have a column for each type of permit.
=INDEX(Building!$A2:$A25000,MATCH(D14,Building!$D2:$D25000,0))

A: Wrap your MATCH function(s) in IFERROR function(s) so that the lookup is passed to the next column if it is not found.
=INDEX(Building!$A:$A, IFERROR(MATCH(D14, Building!$D:$D, 0),
                       IFERROR(MATCH(D14, Building!$E:$E, 0),
                       IFERROR(MATCH(D14, Building!$F:$F, 0), "nowhere"))))


text:
Q: C# - SocketIoClientDotNet - Connection is never upgraded to WebSocket I have a simple code that I am testing against a socket.io server (chat.socket.io)
    IO.Options testOptions = new IO.Options();
    string url = "http://chat.socket.io";
    testOptions.ForceNew = true;
    testOptions.AutoConnect = true;
    testOptions.Upgrade = true;

    Socket _socket = IO.Socket(url, testOptions);

    _socket.On("data", (data) =>
    {
        Console.WriteLine(data.ToString());
    });

When I look at the connection through fiddler I see the transport is only polling
I have no Idea why
Also about every 2 minutes the client disconnects and reconnects


text:
Q: cocoa - App architecture I've a app that lives of making HTTP GET calls, and parsing the JSON responses. I've about 5/6 different views, where that are waiting for that responses to present the information. The contents are much like text and images.
Problems:
- If I make the requests only when the user enters on the view, he have to wait to much, and that's not a good user experience.
- If I make all the requests on the first viewcontroller, the app becomes more slow, and sometimes it takes to long to respond to the user taps.
Questions:
- What is the best way to implement the app, so I've a good user experience and a good performance?

A: I think it depends on the amount of data you ae downloading. If a view needs a lot of data it might be best to download it only when this view is about to be shown, so your app doesn't unnecessarily use bandwidth.
If you do want to load the data up front it might be best to do so in a separate thread so the UI thread isn't blocked.
You could also cache the data and use this cache while the newest data is downloading in the background. This creates a seamless user experience.


text: Q: Could you please suggest physics textbooks that discuss object velocity and image velocity pertaining to spherical and plane mirrors? I have seen texts such as Zemansky's University Physics or Halliday Resnick's Physics (fundamentals and the older edition) etc. do not contain discussions on object velocity, image velocity (and their relation) in geometrical optics unit. So, I request for the books that discuss these topics along with problems (solved and exercises).


text:
Q: Signalr Hubs Not found (403) Right, so I've seen loads of questions about this, but none of the suggested fixes have worked for me.
I have a MVC4 project running in Visual Studio 2012/IIS Express, using SignalR to do some feedback to users. When I run the project I get a 403 error in Chrome like such:
Failed to load resource: the server responded with a status of 403 (Forbidden) http://{website}/Hubs/

Uncaught Error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. .

Obviously I've changed the actual domain on my machine to {website}
Now, originally I had it in a folder called signalr in the root of my web project with a subfolder of hubs, but then I read on the SignalR GitHub that you shouldn't do that, so i changed it to just 'Hubs'. Still didnt fix it.
I've also seen the fix regarding putting your RouteTable.Routes.MapHubs(); in the right order. Mine looks like this:
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RouteTable.Routes.MapHubs();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

I've also seen some people suggesting passing in your route as a parameter into the MapHubs() method, but that takes a string and a HubConfiguration object as a parameter so that's not working either.
My view code looks like this:
@using(Html.BeginForm("Report", "Home", FormMethod.Post, new { enctype="multipart/form-data" }))
{
    @Html.ValidationSummary(true);

        @(InputExtensions.Hidden(Html, "submittingUserId", ViewBag.CurrentUser))
        @(InputExtensions.Hidden(Html, "signalConnectionId"))

        @Html.EditorFor(model => model.UploadedFile)
        @Html.ValidationMessageFor(model => model.UploadedFile)

        <input id="subButton" type="submit" value="UploadFile" title="Upload File" />

}

@section Scripts {
    @Scripts.Render("~/Scripts/jquery.signalR-1.1.1.min.js")
    @Scripts.Render("~/Hubs")

}

I've also added these elements to the web.config:
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
    </modules>
</system.webServer>

It's been driving me absolutely insane, I've tried absolutely every suggestion I could find on here, github, and anywhere else for that matter :(
Any help would be greatly appreciated!
Thanks
ANSWER
So it turns out, I assumed that the script reference to /signalr/hubs was to the PHYSICAL folder containing the hubs. Which it isn't; it is a reference to a virtual directory, which is why if you ALSO have a physical folder called SignalR it gets confused. I moved my hubs folder to my business project, and set the script reference back to "/signalr/hubs" and it all started working.
Sorry about the stupid question and thanks for your answers.

A: RouteTable.Routes.MapHubs(); maps your hubs to http://{website}/signalr/hubs
Why are you trying to get the hubs from http://{website}/Hubs?
Simply access both paths from your browsers, you need to get a http response containing a lot of javascript code. If that does not work, then it means your application is not configured right.
Follow this tutorial, you can see the order of RouteTable.Routes.MapHubs() is different than what your have

A: Following the inspiration above I updated my webconfig to look like this:

script src='<%: ResolveClientUrl("~/signalr/hubs") %>'

instead of

script src='<%: ResolveClientUrl("~/hubs") %>' type="text/javascript"

Not sure why, as the folder structure is just ~/Hubs relative to the page, but it works so... ZANG!!!!


text:
Q: Infopath Print preview from javascript The InfoPath Ribbon has a 'Print Preview' button. When this button is clicked InfoPath pops up the print view for the current page that is selected from the print settings. Is there a way to add a button (either JavaScript or InfoPath ribbon button) to print the 'print view' that was set for the page without having to click on print preview?

A: You can use the reference
http://arcemise.wordpress.com/2011/02/04/sharepoint-2010-infopath-print-button/#more-179
The similar question has been asked here:
Need to print a "print view" in an Infopath 2010 task form


text:
Q: Broadcast receiver for PACKAGE_ADDED not working from Android 3.1 onwards I am not able to launch my Broadcast receiver which is part of a STOPPED Application,
I had registered for PACKAGE_ADDED event in the broadcast receiver, The application works properly till 3.0 but above 3.1 I am facing this issue. I used the below lines to send the intent.
    Intent intent = new Intent(MY_INTENT_ACTION);
    intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    sendBroadcast(intent);

Please let me know if I need to do anything more.

Adding More Info:
My Intention is i wanted to listen for PACKAGE_ADDED Broadcast event and Perfrom some processing in my OnReceive, Please let me know if there is any possiblity to listen for this event with out launching application. A sample code to achive this would be helpful. Thanks

A: The docs for PACKAGE_ADDED state:

This is a protected intent that can only be sent by the system.

You can't modify it, or try to add flags to it. From the release notes for 3.1:

Note that the system adds FLAG_EXCLUDE_STOPPED_PACKAGES to all broadcast intents.

and from the docs for FLAG_EXCLUDE_STOPPED_PACKAGES

If set, this intent will not match any components in packages that are currently stopped. If this is not set, then the default behavior is to include such applications in the result.

All this means that your app won't work the same way as it used to. You'll have to make sure your app is started in order to receive PACKAGE_ADDED.


text:
Q: Load Balancing on Servers I am looking around to find a PHP Script that can do load balancing. Such as: do.example.com directs to one of eight other servers: d1,d2 and so on. I need a script that can deal with this.

A: Load balancing can be achieved in a number of different ways.  Doing it in PHP is not usually one of them.

*

*Apache can be used as a load balancer.

*Nginx can be used as a load balancer.

*All of the big cloud providers off a DNS based load balancer.

Most of these often include extra features like 'health checks' that can tell when a server is not usable.  Where are your servers hosted?  What kind of environment?  This info would help the community offer better suggestions for balancing your application and make it more fault tolerant.


text:
Q: How to setup a PrologScript I setup the following rules to find if there is a relationship between two elements:
directReference(A,B) :- projectReferences(A,B).
transitiveReference(A,C) :- directReference(A,B),directReference(B,C).
transitiveReferenceD1(A,D) :- transitiveReference(A,C),directReference(C,D).
transitiveReferenceD2(A,E) :- transitiveReferenceD1(A,D),directReference(D,E).

Can I write a PrologScript that will check all these queries for a fact?  Although I plan to use Ruby&Rake, someone is trying to do a non-interactive call from PHP here and it has not worked.  I also saw this answer and tried Kaarel's answer.  I just added a new opts_spec:
opts_spec(
    [ [opt(day), type(atom),
        shortflags([d]), longflags(['term', 'day']),
        help('name of day')]

    , [opt(goal),
        shortflags([g]), longflags([goal]),
        help('goal to be called')]

    , [opt(projectReferences), type(atom),
        shortflags([pr]), longflags(['term', 'projectReferences']),
        help('Project Reference lookup')]
    ]
).

I then compiled with:
.\swipl.exe -o day.exe -g main -c "D:\DevProjects\AskJoe\Output\Sample.pro"
And ran it with:
./day.exe -g "day(Sunday)"
And got error:

ERROR: Prolog initialisation failed: ERROR: validate_opts_spec/1:
  Domain error: unique_atom' expected, foundterm' (ambiguous flag)

My goal is to have this work:
./day.exe -g "transitiveReference('a','b')"
I don't like compiling a "day.exe" to run a script (according to the docs this often is not necessary), but I have found no other way to pass arguments to rules.
I saw a basic intro on swi-pl.org that has not helped much.  It does not explain how to make the leap from the script.sh file example to the execution of ./eval 1+2.  In fact, the example is a comment so I'm totally lost

A: Here is a very crude example of a PrologScript program that will read its arguments as a single goal (which may be compound), call it, and then terminate. It should work on *nix systems, and has been tested on OS X. It is just a slight variation of the example program given for using PrologScript in the SWI docs:
#!/usr/bin/env swipl

:- initialization main.

query :-
        current_prolog_flag(argv, Argv),
        concat_atom(Argv, ' ', Atom),
        read_term_from_atom(Atom, Term, []),
        call(Term).

main :-
        catch(query, E, (print_message(error, E), fail)),
        halt.
main :-
        halt(1).

projectReferences(valueA, valueB) :- writeln('I was called!').
directReference(A,B) :- projectReferences(A,B).
transitiveReference(A,C) :- directReference(A,B),directReference(B,C).
transitiveReferenceD1(A,D) :- transitiveReference(A,C),directReference(C,D).
transitiveReferenceD2(A,E) :- transitiveReferenceD1(A,D),directReference(D,E).

After saving this file as, e.g., cli_test.pl, you'll need to change the permissions on the file so that the operating system will recognize it as an executable:
chmod -x scratchboard.pl

After that, you should be able to call the file as as a normal executable from the command line:
$ path/to/the/file/scratchboard.pl 'transitiveReferenceD1(A,D).'
I was called!

Note:

*

*The goal to be evaluated is simply passed as a single argument. query/0 will then retrieve this argument using current_prolog_flag/2, read it as a Prolog term, and call it.

*Since the program is not running in interactive mode, the only output will result from explicit imperatives to write out, such as occur if catch/3 (in the body of main/0) is triggered by an error or if projectReferences/2 is called successfully.

Using library(optparse) seems advisable for more complicated cli interface, but is not necessary for your stated aim of merely querying goals in a file.
I understand that getting the PrologScript approach to work on Windows is somewhat different. A bit of information can be fond here: http://www.swi-prolog.org/FAQ/PrologScript.html

A: So I got this all working and then after a few runs everything just stopped.  I started getting 'permission denied bad interpreter' errors. All I can say is that it has something to do with the hashBang.  The workaround for me was to create a shell script around the call to swipl:
shellscript.sh
#!/bin/bash
swipl -s script4.pl 'projectReferences(A,D).'

Then I continued using aBathologist's example, but just took off the hashBang:
:- initialization main.

query :-
        current_prolog_flag(argv, Argv),
        concat_atom(Argv, ' ', Atom),
        read_term_from_atom(Atom, Term, []),
        call(Term).

main :-
        catch(query, E, (print_message(error, E), fail)),
        halt.
main :-
        halt(1).

projectReferences(valueA, valueB) :- writeln('I was called!').
directReference(A,B) :- projectReferences(A,B).
transitiveReference(A,C) :- directReference(A,B),directReference(B,C).
transitiveReferenceD1(A,D) :- transitiveReference(A,C),directReference(C,D).
transitiveReferenceD2(A,E) :- transitiveReferenceD1(A,D),directReference(D,E).


text:
Q: How to set ajax data value in data-percent progress bar in php? code:

<select name="source" id="source" class="form-control">
    <option>Select Source</option>
    <?php
        $sql = "select name from source";
        $res = mysqli_query($con,$sql);
        while($rows = mysqli_fetch_array($res))
        {
            echo "<option value='".$rows['name']."'>".$rows['name']."</option>";
        }
    ?>
</select>
<select name="tech" id="tech" class="form-control">
    <option>Select Technology</option>
    <?php
        $sql = "select name from course";
        $res = mysqli_query($con,$sql);
        while($rows = mysqli_fetch_array($res))
        {
            echo "<option value='".$rows['name']."'>".$rows['name']."</option>";
        }
    ?>
</select>

In this code I have created percent progress bar. Now in my ajax file i.e. get-source.php and get-tech.php I have calculated percentage through query which working fine and also show in progress bar but the problem is when I change any value from dropdown it shows percentage but I am unable to pass a dynamic value to data-percent through ajax. So, How can I do this? Please help me.
Thank You

A: In your ajax code, you have to set the data-percent value dynamically.Right now it's only pass the $("#progress2").attr('data-percent', 5); every time.
It's should be like this,
$("#tech").change(function(){
        tech = $(this).val();
        $.ajax({
            type:"POST",
            data:{"tech":tech},
            url:"get-tech.php",
            success:function(data){

                show = JSON.parse(data);
                $("#per_tech").html(show.per_tech);
                $("#techno").html(show.techno);
                $("#progress2").attr('data-percent', show.per_tech);//here you can pass the value

            }
        })


text:
Q: OnAnimationEnd does not work , and yes ive researched Im reading a book "Pragmatics: Hello Android"
and copy the code word for word and syntax is all correct because i get no errors but it does not do what i tell it to do on the onAnimationEnd.. it suppose to take me to my next activity but since that was not working i changed it to something simple like txtView.setText("ggag")
just to see if it was even executing... and i noticed the way the book goes about it is slightly different..
    Animation fadein = AnimationUtils.loadAnimation(this, R.anim.fade_in);
    fadein.setAnimationListener(new AnimationListener() { /*im thinking the problem is
     that it does all the work from within the setAnimationLIstener instead of like i
     have seen around where the methods onAnimationEnd , onAnimationRepeat are all
     done seprately outside of the
      setAnimationListener(new AnimationListener() {..all work is done here??... } */
     @Override
     public void onAnimationEnd(Animation animation) {
      //startActivity(new Intent(splahActivity.this,menuActivity.class));
      //the above line of code was not working so i added the line below
      //neither executes

                    TextView topLogo = (TextView)findViewById(R.id.lblTop);
      topLogo.setText("dfsgsdfg");

     }

    @Override
    public void onAnimationRepeat(Animation animation) {
      // TODO Auto-generated method stub

    }

    @Override
    public void onAnimationStart(Animation animation) {
     // TODO Auto-generated method stub

    }

    });

so yeah my onAnimationEnd code is never executed :(

A: Did you call fadein.start()?
Does code (ex. log a message) in onAnimationStart() run?

A: I have the same problem,
mine solved by adding activities tag in manifest.xml
hope it works for you...
my manifest.xml file now is :
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbook.triviaquiz7"
    android:versionCode="1"
    android:versionName="1.0">
    <application
        android:label="@string/app_name"
        android:debuggable="true"
        android:icon="@drawable/quizicon">
        <activity
            android:name=".QuizSplashActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action
                    android:name="android.intent.action.MAIN" />
                <category
                    android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".QuizGameActivity"></activity>
        <activity
            android:name=".QuizSettingsActivity"></activity>
        <activity
            android:name=".QuizScoresActivity"></activity>
        <activity
            android:name=".QuizHelpActivity"></activity>
        <activity
            android:name=".QuizMenuActivity"></activity>
    </application>
    <uses-sdk
        android:minSdkVersion="7" />
</manifest>

I also put dot in the beginning of each activity name, that eliminate all errors


text:
Q: Incorrect hex representations of characters with char but correct with unsigned char I was writing a function that prints the "hexdump" of a given file. The function is as stated below:
bool printhexdump (FILE *fp) {
    long unsigned int filesize = 0;
    char c;

    if (fp == NULL) {
        return false;
    }

    while (! feof (fp)) {
        c = fgetc (fp);
        if (filesize % 16 == 0) {
            if (filesize >= 16) {
                printf ("\n");
            }
            printf ("%08lx  ", filesize);
        }
        printf ("%02hx ", c);
        filesize++;
    }

    printf ("\n");
    return true;
}

However, on certain files, certain invalid integer representations seem to be get printed, for example:
00000000  4d 5a ff90 00 03 00 00 00 04 00 00 00 ffff ffff 00 00
00000010  ffb8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000030  00 00 00 00 00 00 00 00 00 00 00 00 ff80 00 00 00
00000040  ffff

Except for the last ffff caused due to the EOF character, the ff90, ffff, ffb8 etc. are wrong. However, if I change char to unsigned char, I get the correct representation:
00000000  4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00
00000010  b8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00
00000020  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00000030  00 00 00 00 00 00 00 00 00 00 00 00 80 00 00 00
00000040  ff

Why would the above behaviour happen?
Edit: the treatment of c by printf() should be the same since the format specifiers don't change. So I'm not sure how char would get sign extended while unsigned char won't?

A: Q: the treatment of c by printf() should be the same since the format specifiers don't change.
A: OP is correct, the treatment of c by printf() did not change.  What changed was what was passed to printf().  As char or unsigned char, c goes through the usual integer promotions typically to int.  char, if signed, gets a sign extension.  A char value like 0xFF is -1.  An unsigned char value like 0xFF remains 255.
Q: So I'm not sure how char would get sign extended while unsigned char won't?
A:  They both got a sign extension.  char  may be negative, so its sign extension may be 0 or 1 bits.  unsigned char is always positive, so its sign extension is 0 bits.

Solution
char c;
printf ("%02x ", (unsigned char) c);
// or
printf ("%02hhx ", c);

// or
unsigned char c;
printf ("%02x ", c);
// or
printf ("%02hhx ", c);

A: char can be a signed type, and in that case values 0x80 to 0xff get sign-extended before being passed to printf.
(char)0x80 is sign-extended to -128, which in unsigned short is 0xff80.
[edit] To be clearer about promotion; the value stored in a char is eight bits, and in that eight-bit representation a value like 0x90 will represent either -112 or 114, depending on whether the char is signed or unsigned.  This is because the most significant bit is taken as the sign bit for signed types, and a magnitude bit for unsigned types.  If that bit is set, it either makes the value negative (by subtracting 128) or it makes it larger (by adding 128) depending on the whether or not it's a signed type.
The promotion from char to int will always happen, but if char is signed then converting it to int requires that the sign bit be unrolled up to the sign bit of the int so that the int represents the same value as the char did.
Then printf gets ahold of it, but that doesn't know whether the original type was signed or unsigned, and it doesn't know that it used to be a char.  What it does know is that the format specifier is for an unsigned hexadecimal short, so it prints that number as if it were unsigned short.  The bit pattern for -112 in a 16-bit int is 1111111110010000, formatted as hex, that's ff90.
If your char is unsigned then 0x90 does not represent a negative value, and when you convert it to an int nothing needs to be changed in the int to make it represent the same value.  The rest of the bit pattern is all zeroes and printf doesn't need those to display the number correctly.

A: Because in unsigned char the most significant bit has a different meaning than that of signed char.
For example, 0x90 in binary is 10010000 which is 144 decimal, unsigned, but signed it is -16 decimal.

A: Whether or not char is signed is platform-dependant. This means that the sign bit may or may not be extended depending on your machine, and thus you can get different results.
However, using unsigned char ensures that there is no sign extension (because there is no sign bit anymore).

A: The problem is simply caused by the format. %h02x takes an int. When you take a character below 128, all is fine it is positive and will not change when converted to an int.
Now, let's take a char above 128, say 0x90. As an unsigned char, its value is 144, it will be converted to an int value of 144, and be printed at 90. But as a signed char, its value is -112 (still 0x90) it will be converted to an int of value -112 (0xff90 for a 16 bits int) and be printed as ff90.


text:
Q: Fade Transitions I have a bit of code that i use to transition between views.
if (CGRectIntersectsRect(mainSprite.frame, backTopPathImg.frame)) {
    levelOneViewController * levelOne2 = [[levelOneViewController alloc]initWithNibName:nil bundle:nil];
    [self presentModalViewController:levelOne2 animated:NO];
    [levelOne2 changeSpriteLocationTopPath];

}

This makes a regular transition where it just cuts to the other view. My question is how could i make this a fade transition? As in a long fade through black. Keep in mind i am not using a navigation controller, just #importing the view controller then using the above code. Thanks :)

A: See modalTransitionStyle property of UIViewController.
Try the following
if (CGRectIntersectsRect(mainSprite.frame, backTopPathImg.frame))
{
    levelOneViewController * levelOne2 = [[levelOneViewController alloc]initWithNibName:nil bundle:nil];
    levelOne2.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:levelOne2 animated:YES];
    [levelOne2 changeSpriteLocationTopPath];

}

A: I would suggest having a UIView with a black background laid over top of your levelOne2 and over time change the opacity of it from 1.0 to 0.0.
Here is a similar question: http://www.iphonedevsdk.com/forum/iphone-sdk-development/12998-how-fade-between-views-transitioning-through-black.html


text:
Q: IE background image not showing Having a small problem where the background image is not showing in any of the IE versions (except IE 9 I believe), not sure what is going wrong, any helps/thoughts/things I could try out?
Kind regards
http://www.trucknetuk.com/phpBB/viewforum.php?f=46  It is the Michelin banner(not the small sponsor) just above the new topic button
background: url("./styles/Owner_Fleet_Operator_MS/theme/images/michelinback.gif") repeat-x scroll center 0 transparent;

A: Change this:
background: url('./styles/Owner_Fleet_Operator_MS/theme/images/michelinback.gif')repeat-x scroll center 0 transparent;

To this:
background: url('./styles/Owner_Fleet_Operator_MS/theme/images/michelinback.gif') repeat-x scroll center 0 transparent;

The difference is a space after the closing bracket and before the "repeat-x". IE is much pickier than other browsers regarding syntax.

A: Your background shorthand is wrong, transparent needs to come first
#page-body {
    background: transparent url("./styles/Owner_Fleet_Operator_MS/theme/images/michelinback.gif") repeat-x center 0;
    clear: both;
    padding: 4px 5px;
}

proper shorthand is : body {background:#ffffff url('img_tree.png') no-repeat right top;}
Not sure what you are trying to do with the scroll declaration

A: .button{
      background: transparent url('../images/backrgound.jpg') no-repeat top center;
}

CSS Standard
background : color URL repeat-section and position
JPEG Images
Check whether images are of JPEG2000, if yes, then open any image editor and save it again with proper jpeg extension


text:
Q: Creating overlapping boarder colours with xlsxwriter and pandas Given the following data:
import pandas as pd
import numpy as np
# sample data
np.random.seed(1)
np.random.seed(1)
df = pd.DataFrame(
    np.random.randint(low=0, high=1000, size=(6, 5)),
    columns=["X", "a", "b", "c", "d"],
    index=["a", "b", "X", "d", "e", "X"],
)

I can create a xlsx file with formatted boarders using the following:
with pd.ExcelWriter("testing.xlsx") as writer:
    #  need to create xlsx output for this example
    sheet_name = "Sheet1"
    df.to_excel(writer, sheet_name=sheet_name)
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]

    # create horizontal line
    row_range = (3, 3)
    col_range = (1, 8)
    worksheet.conditional_format(
        row_range[0],
        col_range[0],
        row_range[1],
        col_range[1],
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "top": 2,
                    "border_color": "red",
                }
            ),
        },
    )
    # create vertical line
    row_range = (1, 9)
    col_range = (4, 4)
    worksheet.conditional_format(
        row_range[0],
        col_range[0],
        row_range[1],
        col_range[1],
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "left": 2,
                    "border_color": "red",
                }
            ),
        },
    )

However the formatting is incorrect (or, not as desired), and looks as:

The part which is incorrect is:

It seems that I am unable to format a cell twice? Which is an issue here.
This question might generalise from creating an overlapping boarder to creating overlapping conditional formatting, I'm not familiar enough with xlsxwriter to say.

A: I find out the workaround cause it seems like a bug and I'm not an author of the module.
The idea is to not let the cells to overlap. I split the 2 ranges into 5 ranges. The cell which lies at the crossroad has coloured 2 borders.
import pandas as pd
import numpy as np
# sample data
np.random.seed(1)
np.random.seed(1)
df = pd.DataFrame(
    np.random.randint(low=0, high=1000, size=(6, 5)),
    columns=["X", "a", "b", "c", "d"],
    index=["a", "b", "X", "d", "e", "X"],
)

with pd.ExcelWriter("C:\\Users\\kemot\\Desktop\\programy Python\\testing.xlsx") as writer:
    #  need to create xlsx output for this example
    sheet_name = "Sheet1"
    df.to_excel(writer, sheet_name=sheet_name)
    workbook = writer.book
    worksheet = writer.sheets[sheet_name]

   # create horizontal line
    worksheet.conditional_format(
        'A4:B4',
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "bottom": 2,
                    "border_color": "red",
                }
            ),
        },
    )

    worksheet.conditional_format(
        'C4',
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "right": 2,
                    "bottom": 2,
                    "border_color": "red",
                }
            ),
        },
    )

    worksheet.conditional_format(
        'D4:F4',
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "bottom": 2,
                    "border_color": "red",
                }
            ),
        },
    )
    # create vertical line

    worksheet.conditional_format(
        'D1:D3',
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "left": 2,
                    "border_color": "red",
                }
            ),
        },
    )

    worksheet.conditional_format(
        'D5:D10',
        {
            "type": "no_errors",
            "format": workbook.add_format(
                {
                    "left": 2,
                    "border_color": "red",
                }
            ),
        },
    )


text:
Q: Turtle distribution How to create a set of turtles with the rising distribution of their location from the edge of the environment to the middle?

A: You can use something like this in setup
let center-x (max-pxcor + min-pxcor) / 2
let center-y (max-pycor + min-pycor) / 2
let std-dev 5  ; change this to vary how clumped the turtles are

crt 100
[
  set xcor random-normal center-x std-dev
  set ycor random-normal center-y std-dev
]

That will work if you have world-wrapping on. If world-wrapping is off, you would have to add some code to check that the values of xcor and ycor from random-normal are within the world (e.g., the turtle's new xcor is between min-pxcor and max-pxcor) -- otherwise, the code will sometimes try to put the new turtle outside the space, which is an error.
You could also use a triangular distribution that varies the density of turtles linearly from a peak at the center of the space to zero at the edge.
let center-x (max-pxcor + min-pxcor) / 2
let center-y (max-pycor + min-pycor) / 2

crt 100
[
  set xcor random-triangular min-pxcor center-x max-pxcor
  set ycor random-triangular min-pycor center-y max-pycor
]

NetLogo does not have this triangular distribution built-in, so you need to add this procedure to your code:
to-report random-triangular [a-min a-mode a-max]
  ; Return a random value from a triangular distribution
  ; Method from https://en.wikipedia.org/wiki/Triangular_distribution#Generating_Triangular-distributed_random_variates
  ; Obtained 2015-11-27

  if (a-min > a-mode) or (a-mode > a-max) or (a-min >= a-max)
   [ error (word "Random-triangular received illegal parameters (min, mode, max): " a-min " " a-mode " " a-max) ]

  let a-rand random-float 1.0
  let F (a-mode - a-min) / (a-max - a-min)

  ifelse a-rand < F
  [ report a-min + sqrt (a-rand * (a-max - a-min) * (a-mode - a-min)) ]
  [ report a-max - sqrt ((1 - a-rand) * (a-max - a-min) * (a-max - a-mode)) ]

end


text:
Q: Turn off Hystrix functionality I am integrating Hystrix in an application. That application is already in production and we will be testing out hystrix integration work in sandbox before we will push it to production.
My question is that is there any way to turn on/off hystrix functionality using some configuration setting?

A: As ahus1 said, there is no single way to disable Hystrix entirely. To disable it in our application, we decided it was cleanest and safest to put a HystrixCommand in a wrapper class, and that wrapper class only exposed the parts of the HystrixCommand that we used (in our case, the execute() method). When constructing the wrapper class, we pass it a Callable that contains the code we want executed, and if Hystrix is disabled (according to our own config value), we simply call that Callable without ever creating a HystrixCommand. This avoids executing any Hystrix code whatsoever and makes it easier to say that Hystrix isn't affecting our application at all when it's disabled.

A: There is no single setting for this. You'll need to set multiple parameters to disable Hystrix.
See https://github.com/Netflix/Hystrix/wiki/Configuration for the configuration options:
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests=100000 # basically 'unlimited'
hystrix.command.default.execution.timeout.enabled=false
hystrix.command.default.circuitBreaker.enabled=false
hystrix.command.default.fallback.enabled=false

Please double check your version of Hystrix for the available parameters.

A: This is all what you need:
# Disable Circuit Breaker (Hystrix)

spring:
  cloud:
    circuit:
      breaker:
        enabled: false

hystrix:
  command:
    default:
      circuitBreaker:
        enabled: false

A: There are a couple of  ways to achieve this-

*

*Doing this for your every group including default. Although this will not disable hystrix(it will only keep the circuit closed all the time) but you will achieve the same result-
hystrix.command.{group-key}.circuitBreaker.forceClosed=false

*If you are using java, you can create an around advice over @HystrixCommand annotation and bypass hystrix execution based upon a flag.

Java Code for #2-
@Pointcut("@annotation(com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand)")
public void hystrixCommandAnnotationPointcut() {
}

@Around("hystrixCommandAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {
Object result = null;
Method method = AopUtils.getMethodFromTarget(joinPoint);
if ((System.getProperty(enable.hystrix).equals("true")) {
    result = joinPoint.proceed();
} else {
    result = method.invoke(joinPoint.getTarget(), joinPoint.getArgs());
}
    return result;
}

A: If your Project is spring Managed you can comment the bean definition of hystrixAspect in applicationContext.xml
Comment the following line

bean id="hystrixAspect"class="com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect"/>

This will remove Hystrix from your project.

A: I ran into this situation where I wanted to completely turnoff Hystrix using a single property (We use IBM uDeploy to manage dynamic properties). We are using javanica library built on top of Hystrix

*

*Create a Configuration class which creates the HystrixCommandAspect

@Configuration
        public class HystrixConfiguration{

@Bean(name = "hystrixCommandAspect")
@Conditional(HystrixEnableCondition.class)
public HystrixCommandAspect hystrixCommandAspect(){
      return new HystrixCommandAspect()}
}

2. And the conditional class would be enabled based on a system property.

 public class HystrixEnableCondition implements Condition{

  @Override
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata){
    return
       "YES".equalsIgnoreCase(
           context.getEnvironment().getProperty("circuitBreaker.enabled")) ||

       "YES".equalsIgnoreCase(
           System.getProperty("circuitBreaker.enabled"));
  }

 }

A: setting
hystrix.command.default.execution.isolation.strategy=SEMAPHORE
is enough.
Additionally  you may or should disable also the timeout threads
with hystrix.command.default.execution.timeout.enabled=false


text:
Q: Finding Lebesgue Integral of $\frac{1}{\sqrt{x}}$ over $(0,1]$ How do I rigorously discover what
$$
\int_{(0,1]} \frac{1}{x^{1/2}} = \underset{0 \le \phi \le \frac{1}{\sqrt{x}}}{\sup} \int_{(0,1]} \phi
$$
(for $\phi$ a simple function) is?  Note that I have already shown in another exercise that such an integral exists and that it is finite.

A: Here is a brute force approach using the dominated convergence theorem (DCT). The idea is to create a sequence of simple functions $s_n$ such that $s_n(x) \leq \frac{1}{\sqrt{x}}$, and $s_n(x) \to \frac{1}{\sqrt{x}}$. The DCT shows that $\int s_n \to \int \frac{1}{\sqrt{x}}$.
Let $s_n = \sum_{k=n}^{n^2-1} \frac{k}{n} 1_{[(\frac{n}{k+1})^2, (\frac{n}{k})^2)}$. Then $s_n(x) \leq \frac{1}{\sqrt{x}}$,  $s_n(x) \to \frac{1}{\sqrt{x}}$, and $s_n$ is supported in $[\frac{1}{n^2},1)$.
Then
\begin{eqnarray}
\int s_n & = &  \sum_{k=n}^{n^2-1} \frac kn\left(\left(\frac{n}{k}\right)^2 - \left(\frac{n}{k+1}\right)^2\right) \\
& = & n \sum_{k=n}^{n^2-1}\left(\frac{1}{k} - \frac{k}{(k+1)^2}\right) \\
& = & n \sum_{k=n}^{n^2-1}\left(\frac{1}{k} - \frac{1}{k+1} +\frac{1}{(k+1)^2}\right) \\
& = & n\left(\frac{1}{n}-\frac{1}{n^2}\right) + n \sum_{k=n}^{n^2-1} \frac{1}{(k+1)^2}.
\end{eqnarray}
Noting that $\int_{k+1}^{k+2} \frac{dx}{x^2} \leq \frac{1}{(k+1)^2} \leq \int_k^{k+1} \frac{dx}{x^2}$, we obtain the bounds $\frac{1}{n+1}-\frac{1}{n^2+1} \leq \sum_{k=n}^{n^2-1} \frac{1}{(k+1)^2} \leq \frac{1}{n}-\frac{1}{n^2}$. It follows that $\lim_{n \to \infty} \int s_n = 2$, which coincides with the value obtained from the improper Riemann integral.
In terms of the original question, we note that if $s$ is simple, and $s(x) \leq \frac{1}{\sqrt{x}}$, then $\int s \leq \int \frac{1}{\sqrt{x}}$, and so the above shows that $\int \frac{1}{\sqrt{x}} = \sup_{s \, \mathbb{simple}, s(x) \leq \frac{1}{\sqrt{x}}} \int s = 2$.


text:
Q: A non-empty PSR-4 prefix must end with a namespace separator I'm trying to setup PSR-4 with Composer but I'm just getting A non-empty PSR-4 prefix must end with a namespace separator.
My autoload in my composer.json looks like this:
"autoload": {
    "psr-4": {
        "Acme\\models" : "app/models"
    }
},

app/models is empty.
What am I doing wrong? How can I fix this?

A: Someone made a comment but removed it. He mentioned I was missing \\ at the end of Acme\\models. Acme\\models\\ will get rid of the message and work as it should.

A: As others said PSR-4 requires the trailing slash
Though I had to convert / to \\ in Windows (should work fine on Linux):
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },

A: A non-empty PSR-4 prefix must end with a namespace separator.
namespace separator means \\

*

*Method-1

Incorrect ⬇⬇⬇
"autoload": {
    "psr-4": {
        "Acme\\models" : "app/models"
    }
},

Correct ⬇⬇⬇
"autoload": {
    "psr-4": {
        "Acme\\models" : "app/models/"
    }
},

*

*Method-2: If this doesn't work try deleting vendor + composer.lock and reinstall dependencies

*Method-3: Delete the autoload_psr4.php file in the libraries folder - it probably was created before the update and it had issues before.

Know more about PSR-4: Autoloader


text:
Q: MySQL Multiple Table Joins incorrect summation I'm trying to join and sum three tables together (MySQL), grouped by a 'tracking number' and an 'order_ID':
invoice_data_dhl
master_track_nums
payments

Problem: When they are multiple payments rows for an order_ID, it is multiplying the DHL_COST total by the number of results in the payments table for the order_ID.
SELECT
invoice_data_dhl.Waybill_Number,
sum(invoice_data_dhl.AWB_Original_Amount) AS DHL_COST,
master_track_nums.order_ID,
sum(payments.revenue) AS REVENUE
FROM invoice_data_dhl
LEFT JOIN master_track_nums
ON invoice_data_dhl.Waybill_Number = master_track_nums.track
LEFT JOIN payments
ON master_track_nums.order_ID = payments.order_ID
GROUP BY invoice_data_dhl.Waybill_Number

Can this be written so that I can get the results with a single query that outputs the results like the below?
Waybill_Number  DHL_COST    order_ID    REVENUE
7022193792       182.52       110632      234
4536137201      3311.96       107637     4074
3927382187       248.95       110384      636
7812896712        74.85       106998      247

Thanks for any help in advance!

A: UNTESTED: but something like this:  Updated: didn't remove sum on revenue in inline query.
SELECT A.waybill_number, A.DHL_COST, A.Order_ID, Sum(payments.Revenue)
FROM
  (SELECT invoice_data_dhl.Waybill_Number,
     sum(invoice_data_dhl.AWB_Original_Amount) AS DHL_COST,
     master_track_nums.order_ID
   FROM invoice_data_dhl
   LEFT JOIN master_track_nums
       ON invoice_data_dhl.Waybill_Number = master_track_nums.track
   GROUP BY master_track_nums.Order_ID, invoice_data_dhl.Waybill_Number) A
LEFT JOIN payments
  ON A.order_ID = payments.order_ID
GROUP BY A.waybill_number, A.DHL_COST, A.Order_ID


text:
Q: How do I generate a client from OpenApi documentation made by OpenApi Generator? I am looking at these API docs https://developers.arcgis.com/workflow-manager/api-reference/rest/ which appear to be made by OpenApi Generator (some links at the bottom).
I want to generate a C# client using the openapi-generator-cli which requires a YAML file as input. How do I get that YAML file out of those docs?

A: I ended up asking Esri: https://community.esri.com/t5/arcgis-workflow-manager-questions/is-there-a-spec-for-wm-server-api/m-p/1240965#M1763
https://<server>/<webadaptor>/workflow/doc/swagger.json


text:
Q: question about the cosh function I am having a hard time finding the following sum:
$$\sum_{n=0}^{\infty} \frac{5^n}{(2n)!}$$
I know it has something to do with cosine since it also has $(2n)!$ in the denominator and it might also be connected with $e^x$ since the terms look very similar.
I have tried playing with algebraic manipulations but again it did not help.
Any help with starting would be appreciated

A: $$\cosh(x) = \sum_{k=0}^\infty \frac{x^{2k}}{(2k)!}$$
Therefore,
$$\sum_{k=0}^\infty \frac{5^k}{(2k)!} = \sum_{k=0}^\infty \frac{\sqrt5^{2k}}{(2k)!} = \cosh(\sqrt5) = \frac{e^\sqrt5+e^{-\sqrt5}}{2}$$
EDIT- Let
$$f(x) = \sum_{k=0}^\infty \frac{x^{2k}}{(2k)!}$$
$$g(x) = \sum_{k=0}^\infty \frac{x^{2k+1}}{(2k+1)!}$$
Then $f$ is even, $g$ is odd, and $f(x)+g(x)=e^x$. Note that $f$ and $g$ are defined on all of $\mathbb{R}$. Then
$$e^x+e^{-x} = (f(x)+g(x))+(f(x)-g(x)) = 2f(x)$$
Therefore,
$$f(x) = \frac{e^x+e^{-x}}{2}$$

A: HINT:
As $e^y=\sum_{r=0}^\infty\dfrac{y^r}{r!}$
$$e^{-y}+e^y=?$$
Can you recognize $y$ here?

A: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\sum_{n = 0}^{\infty}{5^{n} \over \pars{2n}!} & =
\sum_{n = 0}^{\infty}{\pars{\root{5}}^{2n} \over \pars{2n}!} =
\sum_{n = 0}^{\infty}{\pars{\root{5}}^{n} \over n!}\,{1 + \pars{-1}^{n} \over 2} \\[5mm] & =
{\sum_{n = 0}^{\infty}\pars{\root{5}}^{n}/n! +
\sum_{n = 0}^{\infty}\pars{-\root{5}}^{n}/n!\over 2} =
{\expo{\root{5}} + \expo{-\root{5}} \over 2} =
\bbx{\cosh\pars{\root{5}}}
\end{align}


text:
Q: how to initiate a convex set in matrix given its limit points? Suppose I have a n-d matrix representing the space and elements set is representing the limit points of a convex set. How to set all elements in this convex set (i.e. pt as convex combination of elements set already) efficiently?
My current approach is to first find the smallest ball includes all limit points. Then find convex hull of current set and remove points that is not the desired limit point. Repeat above step until the convex hull of all set points is the given limit points. However, I think this method is too slow for a large set.


text:
Q: How to handle spaces in a jdbc outbound query parameter? I don't know if this is integration related, but in my context I try to reference a payload value by a key that contains spaces:
<int-jdbc:outbound-channel-adapter
    query="INSERT INTO table (serial, dealer_code) VALUES (:payload[SERIES], :payload[DEALER CODE])"
    data-source="dbDataSource">

</int-jdbc:outbound-channel-adapter>

While the :payload[SERIES] parameter works, as long as I add the second one neither of:

*

*:payload[DEALER CODE]

*:payload['DEALER CODE']

*:payload["DEALER CODE"]
Work, moreover the last two break with a:
org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'payload[': Invalid property 'payload[' of bean class [org.springframework.messaging.support.GenericMessage]: Bean property 'payload[' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

While elsewhere, in another enpoint configuration I do use quotes:
<int-http:inbound-channel-adapter id="/api/requests"
    ...
    status-code-expression="T(org.springframework.web.context.request.RequestContextHolder).requestAttributes.request.method.equals('POST') ? 201 : 200">

</int-http:inbound-channel-adapter>

I've worked around this adding an ExpressionEvaluatingSqlParameterSourceFactory (as explained in Inbound Channel Adapter):
<int-jdbc:outbound-channel-adapter
    query="INSERT INTO table (serial, dealer_code) VALUES (:serial, :dealerCode)"
    sql-parameter-source-factory="spelSource"
    data-source="dbDataSource">

</int-jdbc:outbound-channel-adapter>

<bean id="spelSource"
  class="org.springframework.integration.jdbc.ExpressionEvaluatingSqlParameterSourceFactory">
    <property name="parameterExpressions">
        <map>
            <entry key="serial" value="payload['SERIES']"/>
            <entry key="dealerCode" value="payload['DEALER CODE']"/>
        </map>
    </property>
</bean>

</int-jdbc:outbound-channel-adapter>

But since payload fields are just read, this seems too much.
Am I using the wrong syntax here?

A: Try to use ExpressionEvaluatingSqlParameterSourceFactory for the sql-parameter-source-factory attribute of the <int-jdbc:outbound-channel-adapter >. And yes, indeed, that expression must be like this: :payload['DEALER CODE'].


text:
Q: Search on multiple values with jquery autocomplete Hi I'm trying to get the jQuery UI autocomplete widget to work so that it searches for matches from multiple attributes of my array but something does not work in my code.
For the moment
The idea it is if I type "coupe", response will be "Porsche, Audi, Mercedes". In the same way I will able to type '911' and receive as response "Porsche". Thanks for your help.
$(function() {

var cars =
[
    {   "constructor" : "BMW",
        "model": "Z3",
        "type": "cabrio" },

    {   "constructor" : "Porsche",
        "model": "911",
        "type": "coupe" },

    {   "constructor" : "Audi",
        "model": "A3",
        "type": "coupe" },

    {   "constructor" : "Mercedes",
        "model": "SL500",
        "type": "coupe" }
];

    $("#quickFind").autocomplete({
        source: function(request, response){
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( cars, function( value ) {
            return matcher.test(value.constructor) || matcher.test(value.model) || matcher.test(value.type);
        }));
        }
    });

  });

A: On each object of your cars array is missing the "label" and "value" options, take a look:
http://jsfiddle.net/DLLVw/77/
$(function() {

var cars =
[
    {
        "label" : "BMW - Z3 - cabrio",
        "value" : "BMWZ3",
        "constructor" : "BMW",
        "model": "Z3",
        "type": "cabrio" },

    {
         "label" : "Porsche - 911 - coupe",
        "value" : "Porsche911",
        "constructor" : "Porsche",
        "model": "911",
        "type": "coupe" },

    {   "label" : "Audi - A3 - coupe",
        "value" : "AudiA3",

         "constructor" : "Audi",
        "model": "A3",
        "type": "coupe" },

    {
        "label" : "Mercedes - SL500 - coupe",
        "value" : "mercedessl500",
        "constructor" : "Mercedes",
        "model": "SL500",
        "type": "coupe" }
];

    $("#quickFind").autocomplete({
        source: function(request, response){
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
            response( $.grep( cars, function( value ) {
            return matcher.test(value['constructor']) || matcher.test(value.model) || matcher.test(value.type);
        }));
        }
    });

  });


text:
Q: Producing tree diagrams of formulae and expressions. (software request) By "tree," let us mean a tree that is finite, ordered and rooted; but not necessarily binary (that is, every node can have an arbitrary number of children).
Under the definition, most mathematical formulae and expressions can be described as trees whose nodes are labelled by strings. For instance, the sentence $$\forall xy(\mathrm{equality}(\mathrm{sum}(x,y),\mathrm{sum}(y,x))$$ can be viewed as a tree whose root is labelled $\forall xy,$ with a single child that is labelled $\mathrm{equality},$ with two children both of which are labelled $\mathrm{sum},$ etc.
Is there a good free software package for producing such labelled trees?
I use Ubuntu Linux and Microsoft Windows.
There's at least three few features that I want.

*

*Support for symbols like $\forall$, which I believe are standard HTML symbols.

*More than one possible appearance for edges, e.g. dashed edges.
Motivation. To depict $\mathrm{OR}(\neg A,B)$ I'd rather draw $\mathrm{OR}(A,B)$ but with a dashed edge going to $A.$

*Not only can nodes be labelled by strings, but so too can edges.
Motivation. To depict $\mathrm{prod}(x,y^n)$ I'd rather draw the tree $\mathrm{prod}(x,y)$ but with an edge labelled by $n$ going to $y.$

A: The sensible choice for producing documents -- articles, slides for a presentation, etc. -- including any more than a few logical symbols is of course $\LaTeX$ (which you can install under both Windows and Linux, as well as OSX.)
The website http://latexforlogicians.net (which isn't just for logicians) gives lots of information, including recommendations of packages for producing labelled trees in $\LaTeX$ documents. Look at the page on Tree/Tableau Proofs.


text:
Q: Nteflix streams really choppy I installed netflix on edubuntu 12.04lts. it will stream movies but is real choppy. I know its not my comp  unable to handle because i use to have windows on here and it ran fine. Is there any fixes to get the choppiness to stop

A: On Ubuntu, you are running netflix through wine, a sort of Windows emulation software, because Netflix won't support Linux. This is not so efficient as running the Netflix software natively. I've found it can work, but it seems to be sensitive to everything else running on your system as well as the quality of your wifi signal.
Try it with a good wifi signal with nothing else running.


text:
Q: count number of cells that meet certain criteria between two other cells with certain criteria I am looking for a way to count the number of cells meeting a specific criteria that are located between two other cells.  For example:
  A                B      C       D      E
151867377   01:03.5 63500   1325    ARFC
151867611   01:03.5 63734   1325    BC25
151867611   01:03.5 63734   1325    M25T
151867613   01:03.5 63736   1325    ShowComms 1325 Track classified as HOSTILE.
151868763   01:04.7 64886   1325    BC25
151868763   01:04.7 64886   1325    M25T
151868765   01:04.7 64888   1325    ShowComms 1325 Track classified as HOSTILE.
151870850   01:06.8 66973   1325    AFOK
151870852   01:06.8 66975   1325    KR03
151872490   01:08.5 68613   1325    BC25

In column E, I am looking for the number of cells that start with B between the ARFC and the KR03 cells.

A: You could perhaps use something like this:
=COUNTIF(OFFSET(E2,MATCH(H2,E2:E11,0)-1,0,MATCH(H3,INDEX(E2:E11,MATCH(H2,E2:E11,0)):E11,0)),"B*")

I'm using OFFSET here to define the range in which you will count the cells.
The first MATCH indicates where the range starts, the second match indicates where it ends.
The second match uses INDEX and MATCH to make sure that the 'ending' cell is not before the 'starting' cell.
B* is for matching cells beginning with B.


text:
Q: How to replace quotation marks with angle brackets between two patterns recursively for all file in a directory with sed? The repository I am working on has multiple source files in a non-flat directory structure, e.g.
project
│   main.cpp
│
└───moduleA
    │   A.cpp

All these source files have code something like
#include "A.h"

WINDOWS_DISABLE_WARNING
#include "externalA.h"
#include "externalB.h"
WINDOWS_ENABLE_WARNING

// more code

How can I use sed to replace all quotation marks include with angle brackets include between WINDOWS_DISABLE_WARNING macro and WINDOWS_ENABLE_WARNING macro for all files like below recursively?
#include "A.h"

WINDOWS_DISABLE_WARNING
#include <externalA.h>
#include <externalB.h>
WINDOWS_ENABLE_WARNING

// more code

I know how to replace simple strings recursively like find ./ -type f -exec sed -i 's/oldtext/newtext/' {} \;, but I am struggling to figure out how to replace quotation marks with angle brackets between two patterns.
The reason I am doing is this is because Visual Studio recently introduced /external:anglebrackets, if this flag is enabled, any headers included with angle brackets are treated as external, and the warnings coming from it can be turned off via /external:W0. That means no more ugly macros like WINDOWS_DISABLE_WARNING which is defined as __pragma(warning(push,0)) if on Windows, otherwise empty, via CMake's target_compile_definitions and similarly WINDOWS_ENABLE_WARNING which is defined as __pragma(warning(pop)) if on Windows, otherwise empty, via CMake's target_compile_definitions. Since using sed to remove the macros recursively is pretty straightforward, eventually the code can become clean like the below when working with loosely written third-party libraries with the new /external flags enabled.
#include "A.h"

#include <externalA.h>
#include <externalB.h>

// more code

A: Read about addressing lines in sed
find ... -exec sed -i '/WINDOWS_DISABLE_WARNING/,/WINDOWS_ENABLE_WARNING/ { s/"/</; s/"/>/ }' '{}' +

Make sure to back your files up (sed -i.bak) (or omit the -i option) before experimenting with -i


text:
Q: Find missing doc I have 1M docs in my index. The docs have an "order" key which is the unique order number of the document starting at 1 for the first doc, 1M for the last.
Some of the documents are missing. Is there an efficient way (a query) to find them? The only solution I found is bisection. Search for how many docs have order < 1M/2 gives you the halves in which the docs are missing etc..


text:
Q: CQRS/ES - handling projection errors I'm working on a CQRS+ES system, mainly using the axon framework, but really this question applies to any implementation. So I have a command handler and 1 or more event handlers, running on different JVMs, containers etc, and at some point one of these handlers encounters an error.
We have two cases, an 'expected' business error and an 'unexpected' system error. As I understand it, we are now in an asynchronous handler, and the event is now a fact, so in reality we cannot directly rollback the command for neither case (as it could entail rolling it back in numerous other projections and break CQRS).
So my question is, should such an error be 'resolved' in an accounts ledger sort of way, i.e. by sending a new 'reversal' command that is then propagated to the projections in such a way that the event that failed is now resolved?
As an example, let's say we have a command that updates a customer's credit. The event is published, one projection updates its "total credits" statistic, another one publishes the update to some websocket for the UI and, finally, another one which maintains the credit state - and this last handler fails. Should we send a command for rolling back the business transaction, and again deduct the credit, update the websocket again, etc? And in case of axon is there some way in which this is captured as a transaction?

A: I'd state that the decision making whether taking an action, thus handling a command, is okay, should always lie with the Command Model/Aggregate. The aggregate being in an incorrect state to handle an action will typically lead to a 'business exception/error'.
If you'd make decisions upon event handling failing however, you're adding some decision making logic in a event handling service which in most cases it likely doesn't care about. It such an event handling services updates views/query models, but fails to do so, I'd argue that's not a valid reason to publish a 'compensating command' to your aggregate to 'rollback/undo the event'.
In your example you have a 'credit-state-maintainer', which I'd guess updates a query model. As such I'd deem the problem of dealing with the exception to lie within the service itself, not by performing a compensating action.
From an Axon Framework perspective, you could wrap your CreditStateEventHandler in a TrackingEventProcessor and trigger a reset on that event processor by calling the TrackingEventProcessor#resetTokens() function. This is taken the stance that the exception due to which your CreditStateEventHandler is due to faulty coding of course, otherwise a replay would result in the exact same exception.


text:
Q: HTML Update News Page I have a site which is basically a few HTML Pages. I no have a requirement to create a facility where a site admin can create and maintain a News section.
I am just pondering what my options are?  It needs to be a fairly simple process to maintain news items and ideally not be database driven. Although I'm struggling to see how I can achieve this.
Any help is much appreciated.
Thanks

A: CuteNews should do what you want.  It uses a flat file to store the news items so you don't need a database.

A: Not sure I understood well, but if you mean you have news in static HTML pages and you want to update them, without doing it by hand, you would have to write a script that creates new ones or updates the existing ones, but that's all too complicated in my oppinion.
The way to go is Server-side language (PHP, ASP etc) and database (MySQL, PostgreSQL etc).


text:
Q: Getting client IP from Ruby script through xinetd How can I get the client IP Address from inside a Ruby script that is launched by xinetd through a stream socket?
In PHP I would just use stream_socket_get_name(STDIN, true);
Thanks in advance!

A: After searching a lot for the solution, and even trying to ask on the #ruby channel on Freenode and being completely ignored, I've finally found the solution:
def to_ip(addr)
  (4...8).map{|x|addr[x]}.join('.')
end

socket = Socket.for_fd(STDIN.fileno)
ip = to_ip(socket.getpeername)

Hope this helps someone!


text:
Q: Optional parameters in HttpPost MVC marked as required? In my C# code, I have a method in my Microsoft.AspNetCore.Mvc.ApiController that gets values. However, if I call the GetThingsAsync method without having the Origin header set in the POST call, I get a 400 BadRequest error.
        [HttpPost]
        [Route("route")]
        public async Task<IActionResult> GetThingsAsync(
            [FromBody] SomeRequest someRequest,
            [FromHeader(Name = "Origin")] string origin = "Unknown")
        {
            // Code goes here
        }

The error I get is like this:
{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "REDACTED",
    "errors":
    {
        "Origin":
        [
            "The origin field is required."
        ]
    }
}

Now, I assumed the code I'm writing should have a default value of Unknown if Origin isn't set. However, the origin value either isn't set properly, or the validation might be too zealous in some way. I'd like to know why I am getting an error when running this code without having the Origin header set in the request.
I understand that this problem can be fixed by adding a ? to the string argument like so:
        [HttpPost]
        [Route("route")]
        public async Task<IActionResult> GetThingsAsync(
            [FromBody] SomeRequest someRequest,
            [FromHeader(Name = "Origin")] string? origin = "Unknown")
        {
            // Code goes here
        }

That being said, I want to know why this header is required even when it has a default value. Is it being set to null?

A: Assume that you use ASP.NET 6, It does not makes 400 error for other version.
As this document said:

Beginning with .NET 6, new projects include the
<Nullable>enable</Nullable> element in the project file. Once the
feature is turned on, existing reference variable declarations become
non-nullable reference types.

So that the non-nullable property must be required in asp.net 6, otherwise the ModelState will be invalid.
One way is to remove <Nullable>enable</Nullable> from your project file.
Another way is to add ? like below:
[HttpPost]
[Route("route")]
public void GetThingsAsync(
    [FromBody] SomeRequestsomeRequest,
    [FromHeader(Name = "Origin")] string? origin = "Unknown")
{
    // Code goes here
}


text:
Q: Declaring arrays in soy file I am pretty new to Google closures.  I am not sure how to declare and assign values to arrays in Soy file (google Closure).
Please advise.

A: just moving this to an answer for future reference:
this compiles for me: {let $P : [1,2,3,4]/} -- compiles down to this: var output = opt_sb || new soy.StringBuilder(); var P__soy461 = [1, 2, 3, 4]; so it should work fine


text:
Q: Appending data to an array I created a vertex with a property called interests and it should store an array of strings.
SELECT * FROM cypher('DatingApp', $$
    CREATE (v:Person {
        name: 'Alex',
        age: 27,
        occupation: 'Graphic Designer',
        interests: []
    })
    RETURN v
$$) as (v agtype);

How can I add more strings to this property with another query?

A: You can use the SET clause with the + operator to concatenate two arrays to append new values to the interests array property of the Person node.
For example:
SELECT * FROM cypher('DatingApp', $$
    MATCH (v:Person { name: 'Alex' })
    SET v.interests = v.interests + ['reading', 'traveling']
    RETURN v
$$) as (v agtype);

The SET clause appends the strings 'reading' and 'traveling' to the existing interests array property of the node.