text:
Q: jquery convert promise cascade I have a problem about jquery promise cascade and I want to simplify it. I have a cascade function (func1) that it's working. I set a timeout 2 seconds before executing the next function. I want to replicate and convert it to an array reduce form (func2) but it's not working like func1 (the timeout not same). Here is the code:
var Makes=[1,2,3,5,8];
$(document).ready(function(){
    //func1(); //WORKS
    func2();   //NOT WORKS LIKE func1

});

function func1(){
    timeout().then(function(){
       console.log("1");
       return timeout();
    }).then(function(){
       console.log("2");
       return timeout();
    }).then(function(){
       console.log("3");
       return timeout();
    }).then(function(){
       console.log("4");
       return timeout();
    }).then(function(){
       console.log("5");
       return timeout();
    });
}

function func2(){
    /*Makes.reduce(function(Models,Idx){
        return timeout().then(function(){
            console.log(Idx);
            return timeout();
            //return $.when(timeout());
        });
    },0);*/
    Makes.reduce(function(Models,Idx){
        return Models.then(function(){
            return timeout().then(function(){
                console.log(Idx);
                return timeout();
                //return $.when(timeout());
            });
        });
    },0);
}

function timeout(){
    var d = $.Deferred();
    setTimeout(function(){
        console.log("wait for 2 sec!");
        d.resolve();
    },2000);
    return d.promise();
}

A: You should not return timeout().then in the reduce callback, but build on the promise you have from the previous iteration: Models.then. And you should give an initial promise to start with, one that resolves immediately ($.when()):
function func2(){
    Makes.reduce(function(Models, Idx) {
        return Models.then(function () {
            return timeout().then(function () {
                console.log(Idx);
            });
        });
    }, $.when()); // resolved starter promise
}

var Makes=[1,2,3,5,8];
$(document).ready(function(){
    func2();
});

function func2(){
    Makes.reduce(function(Models, Idx) {
        return Models.then(function () {
            return timeout().then(function () {
                console.log(Idx);
            });
        });
    }, $.when());
}

function timeout(){
    var d = $.Deferred();
    setTimeout(function(){
        console.log("wait for 2 sec!");
        d.resolve();
    },2000);
    return d.promise();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Alternatively, you can use a "recursive" kind of function for implementing an asynchronous loop:
function func2(){
    (function repeat(Idx) {
        if (Idx >= Makes.length) return;
        timeout().then(function () {
            console.log(Makes[Idx]);
            repeat(Idx+1);
        });
    }(0));
}

var Makes=[1,2,3,5,8];
$(document).ready(function(){
    func2();
});

function func2(){
    (function repeat(Idx) {
        if (Idx >= Makes.length) return;
        timeout().then(function () {
            console.log(Makes[Idx]);
            repeat(Idx+1);
        });
    }(0));
}

function timeout(){
    var d = $.Deferred();
    setTimeout(function(){
        console.log("wait for 2 sec!");
        d.resolve();
    },2000);
    return d.promise();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: How to make a POST request to Twilio to call a number with urequests I have recently starting doing things with a raspberry pi zero W and wanted to be able to call a number from it.
Unfortunately it seems very hard to use the normal Twilio library because the pi uses MicroPython so I have to use the raw API.
I also gathered that the API uses the content type x-www-form-urlencoded which urequests seems to have a hard time interacting with.
This is my code so far
url = f"https://api.twilio.com/2010-04-01/Accounts/{TWILIO_USER}/Calls.json"

def call() -> None:
    body = {"To": CALLING_NUMBER, "From": CALLER_NUMBER}
    response = urequests.post(url, json=body, auth=(TWILIO_USER, TWILIO_KEY))

    print("Status Code", response.status_code)
    print("JSON Response ", response.json())

however I get the error
{'code': 21201, 'more_info': 'https://www.twilio.com/docs/errors/21201', 'message': "No 'To' number is specified", 'status': 400}

I have tried a ton of stuff like url encoding the body myself, using it as the parameter for data, json.dumpsing it, nothing seemed to work. Any help would be greatly appreciated.
Please remember I am limited by the picos standard libraries.

A: It seems I was close. All I had to do was copy paste urllib's urlencode and use it on body, then it ended up working.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 7 Activation during image deployment We currently have 40 machines that are being upgraded to Windows 7 Enterprise. One machine will need to have software installed on them, and then imaged and deployed to the other 39 machines. The client has purchased Volume Licenses for these machines and we will be using MAK's for activation.
With MAK keys, you can use the same key on multiple machines. These keys deduct from a pool of activations kept in the VLSC. If we are going to be using these keys on multiple machines can we activate it on the image machine, and deploy the activated machine, or would we have to deploy the unactivated image to all 39 other machines and activate them individually?
We are also doing this for Microsoft Office, I assume the process is similar.

A: I would recommend looking at the Volume Activation Management Toolkit. It can be used to assist with MAK keys, the KMS (Key Management Service) if you are using it, and handles the OS as well as Office.
http://technet.microsoft.com/en-us/library/hh825141.aspx

A: Use sysprep
You can put the product key inside of the unattended.xml
sysprep /generalize
You may or may not need /oobe
When the sysprep'ed machine is started up it will re-detect all the hardware.  You will still need to load drivers for unique hardware, but there should be no show-stopper errors.
For example load nvidia driver and have an ATI card well your desktop will just come up in standard VGA mode until you load the correct drivers.

A: Most likely if you image an activated windows install onto a new machine it will go "out of tolerance" and need reactivating.
You may want to consider setting up a kms server and using that instead of mak keys. There are two advantages to this.

*

*It makes it harder for rouge employees, theives etc to steal your keys.

*You don't need to ring up MS and ask for more activations.

AIUI if you do use a kms and image machines you need to "rearm" the activation system immediately prior to imaging so each machine gets a different ID. Otherwise the kms server won't be able to tell the machines apart and wont reach it's activation threshold.


text:
Q: Cannot apply indexing with [] to an expression of type Torpedo.Mezo Just a very quick question.
I have a classe called "Mezo.cs" that is basically a 'public int[,]'.
A specific copy of this class is a int[,] containing 1 or 0.
I want to find the 1s.
So in the main program I iterate through it with fors but i get the error in the title.
Any help would be appreciated.
static void WriteShips(Mezo mezo, StreamWriter SW)
    {
        for (int i = 0; i < 10; i++)
        {
            for (int j = 0; j < 10; j++)
            {
                if (mezo[i, j] == 1)
                {
                    SW.WriteLine(i.ToString(), j.ToString());
                }

            }
        }

    }

This is in a battleship program where I want to basically want to save the coordinates of the ships in a txt.
mezo[i, j] gives the error
MEZO CLASS:
class Mezo
{
    public int[,] mezo;

    public Mezo()                            // KONSTRUKTOR
    {
        mezo = new int[10, 10];
        kitoltesUressel();

    }

kitoltesUressel() is irrelevant, it just randomly fills the copy with 1s and 0s.

A: In order to use an instance of your class with indexes (pretty much like any collection in the framework), you need to have a property that will act like the index manager.
Here is a simple code of a class that behaves like an array:
public class MyIndexedClass
{
    private string[] _values = new string[]
    {
        "hello",
        "hi",
        "good morning",
        "long time no see"
    };
    public string this[int index]
    {
        get
        {
            Console.WriteLine("Index called with argument value " + index);
            return _values[index];
        }
        set
        {
            Console.WriteLine("Index called with argument value " + index + " and value " + value );
            _values[index] = value;
        }
    }
}

In my example, using the code myIndexedClassInstance[0]; returns a string containing "hello".
I'm guessing your "Mezo" class contains a jagged array inside of it, but not using the "this" keyword.
You can check more about indexes here.
EDIT:
Updated now given the new info about your Mezo class, the code that is giving you the error should look like this:
if (mezo.mezo[i, j] == 1)
{
   SW.WriteLine(i.ToString(), j.ToString());
}

Because you are passing an instance of Mezo, which is the one containing the array called mezo.
You cannot use the instance of the class itself as if it was the jagged array property.


text:
Q: handle null values for string when implementing IXmlSerializable interface I have the following class that implements IXmlSerializable.  When implementing WriteXml(), I need to handle the case where the string members of this class may be null values.  What is the best way of handling this?
Currently, I am using the default constructor in which all the string properties are initialized to empty string values.  This way, when WriteXml() is called, the string will not be null.
One other way I could do this is check using String.IsNullOrEmpty before writing each string in xml.
Any suggestions on how I can improve this code?
    public sealed class FaxSender : IXmlSerializable
    {
        #region Public Constants

        private const string DEFAULT_CLASS_NAME = "FaxSender";

        #endregion Public Constants

        #region Public Properties

        public string Name { get; set; }

        public string Organization { get; set; }

        public string PhoneNumber { get; set; }

        public string FaxNumber { get; set; }

        public string EmailAddress { get; set; }

        #endregion Public Properties

        #region Public Methods

        #region Constructors

        public FaxSender()
        {
            Name = String.Empty;
            Organization = String.Empty;
            PhoneNumber = String.Empty;
            FaxNumber = String.Empty;
            EmailAddress = String.Empty;
        }

        public FaxSender(
            string name,
            string organization,
            string phoneNumber,
            string faxNumber,
            string emailAddress)
        {
            Name = name;
            Organization = organization;
            PhoneNumber = phoneNumber;
            FaxNumber = faxNumber;
            EmailAddress = emailAddress;
        }

        #endregion Constructors

        #region IXmlSerializable Members

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            throw new NotImplementedException();
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            throw new NotImplementedException();
        }

        public void WriteXml(System.Xml.XmlWriter xmlWriter)
        {
            try
            {
                // <sender>
                xmlWriter.WriteStartElement("sender");

                // Write the name of the sender as an element.
                xmlWriter.WriteElementString(
                    "name",
                    this.Name.ToString(CultureInfo.CurrentCulture));

                // Write the organization of the sender as an element.
                xmlWriter.WriteElementString(
                    "organization",
                    this.Organization.ToString(CultureInfo.CurrentCulture));

                // Write the phone number of the sender as an element.
                xmlWriter.WriteElementString(
                    "phone_number",
                    this.PhoneNumber.ToString(CultureInfo.CurrentCulture));

                // Write the fax number of the sender as an element.
                xmlWriter.WriteElementString(
                    "fax_number",
                    this.FaxNumber.ToString(CultureInfo.CurrentCulture));

                // Write the email address of the sender as an element.
                xmlWriter.WriteElementString(
                    "email_address",
                    this.EmailAddress.ToString(CultureInfo.CurrentCulture));

                // </sender>
                xmlWriter.WriteEndElement();

            }
            catch
            {
                // Rethrow any exceptions.
                throw;
            }
        }

        #endregion IXmlSerializable Members

        #endregion Public Methods
    }

A: I have some suggestions:
1 - Only implement IXmlSerializable as a last resort and instead control XML serialization through attributes. It's simpler and easier to maintain. It also handles the properties being a null reference.
[XmlRoot("sender")]
public sealed class FaxSender
{
    [XmlElement("name")]
    public string Name { get; set; }
    [XmlElement("organization")]
    public string Organization { get; set; }
    [XmlElement("phone_number")]
    public string PhoneNumber { get; set; }
    [XmlElement("fax_number")]
    public string FaxNumber { get; set; }
    [XmlElement("email_address")]
    public string EmailAddress { get; set; }

    // Remaining code omitted
}

2 - Do not wrap code in a try\catch if the only thing you are going to do is rethrow every exception;
3 - The guideline for constants in .NET is to use PascalCase which would result in DefaultClassName instead of DEFAULT_CLASS_NAME.


text:
Q: Python - issue with plotting CandleStick plotly chart I am having trouble plotting values on Candlestick plotly chart.
For some reason, I get all green bars instead of green/red bars. Green for when values are up and red when the values go down.
Here is my code that you can run as is if you just install cbpro:
# Import Dependencies
import time
import cbpro
import pandas as pd
import json
import plotly.graph_objects as go
from datetime import datetime

# Establish Public Client
public_client = cbpro.PublicClient()

# Create start and end time variable
stime = public_client.get_time()
etime = list(public_client.get_time().values())[0]
# Get past transaction for ETH
past_transactions = pd.DataFrame(public_client.get_product_historic_rates(product_id='ETH-USD'))
# Rename the columsn
past_transactions.columns= ["Date","Open","High","Low","Close","Volume"]
# Format the date
past_transactions['Date'] = pd.to_datetime(past_transactions['Date'], unit='s')
# Set the date as index
past_transactions.set_index('Date', inplace=True)
# Sorting values by date
past_transactions.sort_values(by='Date', ascending=True, inplace=True)

# Plot the values on CandleStick plotly chart
fig = go.Figure(data=[go.Candlestick(x= past_transactions.index,
                                            open = past_transactions['Open'],
                                            high = past_transactions['High'],
                                            low = past_transactions['Low'],
                                            close = past_transactions['Close']
                                            )])

fig.show()
past_transactions

What am I doing wrong here?

A: This is going to sound a bit strange, but please hear me out. And I might be wrong here, but to me this seems to be a broblem with your dataset. Either the data is strange all the way, or the following references are wrong:
open = past_transactions['Open'],
high = past_transactions['High'],
low = past_transactions['Low'],
close = past_transactions['Close']

By that I mean that lows have been mixed up with close or something to that effect. And what on earth can I mean by the data is strange all the way? I look at candle charts from a variety of markets all day long, and what we're looking at in your figure just can not represent any "normal" market. In theory, there would be absolutely nothing wrong with a chart that looks like yours as lon as close is higher than open for each and every time interval.

And that's exactly what we're looking at in your case with all those "flat" candles, meaning that low = open for all of them. Or in candle chart terms: we're not seeing any Lower Shadow

And that just would not happen for that many observations in any liquid and well functioning market. I may be wrong about that though, but I'm not wrong in that your plotly figure is producing the correct visualization given your data specifications.

A: I tried running the code you have added. But, I do get red and green bars. But the reds are not that visible because they are fewer in number and smaller. The plot:


text:
Q: How to return an instance of Class for an array of a given Class subtype? import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Date;

public class Test {
    public static void main(String[] args) {
        System.out.println(new Test().getClassOfArrayOfSerializable(String.class));
        System.out.println(new Test().getClassOfArrayOfSerializable(Date.class));
    }

    @SuppressWarnings("unchecked")
    private Class<? extends Serializable> getClassOfArrayOfSerializable(final Class<? extends Serializable> subtypeClass) {
        return (Class<Serializable>) Array.newInstance(subtypeClass, 0).getClass();
    }
}

The method getClassOfArrayOfSerializable() above, returns the class for an array of an object of the type passed as the argument.
As you can see, I had to create an instance of the array even though I actually need only its Class.
Is there a way to avoid the instantiation of the array?

A: Turns out that the following works quite well (tested and verified using an online compiler):
System.out.println(String[].class);
System.out.println(Date[].class);

Results in the desired output:
class [Ljava.lang.String;
class [Ljava.util.Date;

No need for the instantiation of the array - assuming you know in advance what class you will require, you can simply request the class type of its encapsulating array.
However, if you must find the array class type during runtime on a given class type, I believe your only option would be to use basin's suggestion of (also verified as a working solution via an online compiler):
Class.forName("[L" + className + ";");

And as a method:
 @SuppressWarnings("unchecked")
    private Class<? extends Serializable> getClassOfArrayOfSerializableNoArrayInitialization
        (final Class<? extends Serializable> subtypeClass) throws ClassNotFoundException
    {
        return (Class<Serializable>) Class.forName("[L" + subtypeClass.getName() + ";");
    }


text:
Q: Examples for existence proofs using the parity of fixed points of involutions On Wikipedia, I have seen a nice proof of Zagier for the existence of representations of primes as sum of two squares:
http://en.wikipedia.org/wiki/Proofs_of_Fermat%27s_theorem_on_sums_of_two_squares#Zagier.27s_.22one-sentence_proof.22
The proof uses the (trivial) fact that the number of fixed points of an involution of a finite set has the same parity as the cardinality of the set itself.

Do you know any other examples for existence proofs using the parity of fixed points of involutions?

A: A more general fact is that the number of fixed points of the action of a finite $p$-group on a finite set has the same cardinality $\bmod p$ as the set itself. This is used, for example, to prove that finite $p$-groups have nontrivial center and it is also part of the proof of the Sylow theorems.
While this isn't an existence proof, it can also be used to give a short proof of Fermat's little theorem: given a positive integer $a$, consider the action of $\mathbb{Z}/p\mathbb{Z}$ by cyclic permutation on the set of words of length $p$ on an alphabet of size $a$. There are $a$ fixed points and $a^p$ words, hence $a^p \equiv a \bmod p$.


text:
Q: How root motion handle obstacles? I'm learning about root motion recently. I know that root motion is to use animation to drive the movement of character capsule (collider). The idea is that to extract the transform of a root bone for root motion and apply it to the transform of character capsule.
However, assuming that there are obstacles in the scene and blocking the character capsule, the character capsule is now influenced by both physics (collision) and animation (root motion).
I'm confused about how root motion handle both influence from physics and animation to make the character capsule act correctly.

A: Root motion changes transform.position. It completely ignores obstacles.
You are likely to see jittery motion near obstacles since root motion and physics will be in conflict as root motion takes you into obstacles and physics tries to prevent that.
I would avoid using root motion and recreate it in code with whatever motion method you're using (RigidBody, CharacterController, etc).
Here is also a forum post about this.


text:
Q: Apache sending POST request twice I have a e-commerce shop and I've been noticing that on random intervals that orders would be created twice, sometimes 3 times. I found something strange in Apache's access logs that seems to be the cause:
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:09 +0200] "POST /da/index.php?option=foo&task=orders.ajaxCheckActionPermissions HTTP/1.1" 200 218 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:18 +0200] "POST /da/ordrer HTTP/1.1" 303 456 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:20 +0200] "GET /da/ordrer HTTP/1.1" 200 13158 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:22 +0200] "GET /da/index.php?option=foo&task=shop.ajaxGetShoppingCart&_=1554702922260 HTTP/1.1" 200 762 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:18 +0200] "POST /da/ordrer HTTP/1.1" 303 456 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:23 +0200] "GET /da/ordrer HTTP/1.1" 200 13158 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"
SAME.IP.ADDRESS - - [08/Apr/2019:07:55:24 +0200] "GET /da/index.php?option=foo&task=shop.ajaxGetShoppingCart&_=1554702924422 HTTP/1.1" 200 761 "http://www.example.org/da/ordrer" "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko"

The second POST is the original form submission and the following 2 GETs are running as normal. However, the very next POST has the same timestamp as the previous POST.
I thought it could have been a form submit button being pressed twice, but I have JS preventing that, not to mention the entire checkout page is powered by JS, so a user wouldn't have been able to complete the checkout process, so it couldn't have been a double click.
Could it be a configuration problem with Apache? Or something entirely different? I'm not very advanced with Apache, but I'll provide info as requested.
I'm running a LAMP stack:

*

*Apache 2.4

*PHP 7.0

A: Apache is not sending the POST twice - it is receiving it twice. This is very likely a bug in the JS part of your application.
To diagnose it, set a global variable orderSent to false on page load, then before sending the POST /da/ordrer first check if it is still false and fail if not, then set it to true (again before sending the request). This helps you find the bug and allows you to create a more permanent solution.


text:
Q: how do I debug a wait_fences error wait_fences: failed to receive reply: 10004003
I continue to get this error. It happens when my app starts up. How would I debug this issue. Is there some way I can watch the wait_fences and see what is going on there. Is there some way to see what threads are blocking what ?
It feels like this error is nothing but a theading black hole with no tools or info getting into or coming out of the void.
Anyone with tips on debugging this error would be greatly appreciated.
New
I have now changed my threading, All threading calls go through this method set to do all their dispatches
NOTE: Also I wish you guys would not vote to close my question just because you have seen another question about this problem. There is no real information about this error. I need to know what causes this error and/or how to debug it. not the common "add the super calls to your viewDidAppear and the such. If those helped, I would not have asked this question.
+ (void) ensureDispatchOfBlock:(dispatch_block_t) block onQueue:(dispatch_queue_t) queue  async:(BOOL) async{
    if (dispatch_get_current_queue() == queue){
        block();
    }
    else {
        if (async){
            dispatch_async(queue, block);
        }
        else {
            dispatch_sync(queue, block);
        }
    }
}

+ (void) ensureDispatchOnMainThread:(dispatch_block_t) block async:(BOOL) async{
    [self ensureDispatchOfBlock:block onQueue:dispatch_get_main_queue() async:async];
}

+ (BOOL) addBlock:(dispatch_block_t) block toQueue:(dispatch_queue_t) queue async:(BOOL) async {
    if (!async && dispatch_get_current_queue() == queue){
        return NO;
    }
    if (async){
        dispatch_async(queue, block);
    }
    else {
        dispatch_sync(queue, block);
    }
    return YES;
}

A: That error usually comes up as a result of trying to animate something that isn't visible on-screen.  If it happens on launch, I'd guess that you're trying to start an animation in viewDidLoad.

A: I'd look for missing calls to super's view(Did/Will)Appear. If these are omitted you will see "wait fences", whatever that means.


text:
Q: MS Access parameterized passthrough query I've got a small problem getting a query with a parameter to work in a MS Access DB I'm building. I can't get the formatting/synthax right when the parameter is in number form.
Here's the code:
Private Sub Command15_Click()
   Dim conn As ADODB.Connection
   Dim strConnection As String

   strConnection = "Driver={Microsoft ODBC for Oracle};Server=SERVER;Uid=USER_ID;Pwd=PASSWORD;"

   Set conn = New ADODB.Connection
   conn.Open strConnection
   conn.Execute " UPDATE L2000.DEPARTURE_STATUS DS " & _
              " SET DS.DEPARTURE_STATUS = '" & Forms!frmDepartureStatus.txtdeparturestatus & "' " & _
              " WHERE DS.DEPARTURE_NO = " & Forms!frmDepartureStatus.txtdepno
   conn.Close
   Set conn = Nothing
End Sub

The value from txtdepno to be send through the parameter is a number, I've tried a few different approaches with no luck.
Here's another similar code that works but this time the parameter is a string:
Private Sub Command16_Click()
   Dim conn As ADODB.Connection
   Dim strConnection As String

   strConnection = "Driver={Microsoft ODBC for Oracle};Server=SERVER;Uid=USER_ID;Pwd=PASSWORD;"

   Set conn = New ADODB.Connection
   conn.Open strConnection
   conn.Execute " UPDATE L2000.USERS U " & _
            " SET U.STORER_ID = '" & Forms!EXAMPLE.txtInput2 & "'" & _
            " WHERE U.USER_ID = '" & Forms!EXAMPLE.txtInput & "'"
   conn.Close
   Set conn = Nothing
End Sub

A: String concatenation is not parametrization. However, if you're using string concatenation, you can solve this pretty easily. Just omit the single quotes, and that way Oracle will treat them as numbers. With the single quotes, they're treated as strings:
Private Sub Command16_Click()
   Dim conn As ADODB.Connection
   Dim strConnection As String

   strConnection = "Driver={Microsoft ODBC for Oracle};Server=SERVER;Uid=USER_ID;Pwd=PASSWORD;"

   Set conn = New ADODB.Connection
   conn.Open strConnection
   conn.Execute " UPDATE L2000.USERS U " & _
            " SET U.STORER_ID = " & Forms!EXAMPLE.txtInput2  & _
            " WHERE U.USER_ID = " & Forms!EXAMPLE.txtInput
   conn.Close
   Set conn = Nothing
End Sub

If you actually wanted to build a parameterized query, it would look something like this:
Private Sub Command16_Click()
   Dim conn As ADODB.Connection
   Dim strConnection As String

   strConnection = "Driver={Microsoft ODBC for Oracle};Server=SERVER;Uid=USER_ID;Pwd=PASSWORD;"

   Set conn = New ADODB.Connection
   conn.Open strConnection
   Dim cmd As New ADODB.Command
   Set cmd.ActiveConnection = conn
   cmd.CommandText =  "UPDATE L2000.USERS U " & _
            " SET U.STORER_ID = ?"
            " WHERE U.USER_ID = ?"
   cmd.Parameters.Append cmd.CreateParameter(, adInteger,adParamInput, 5, Forms!EXAMPLE.txtInput2 )
   cmd.Parameters.Append cmd.CreateParameter(, adInteger,adParamInput, 5, Forms!EXAMPLE.txtInput )
   cmd.Execute
   conn.Close
   Set conn = Nothing
End Sub


text:
Q: Cannot upload .mpg file to SP2013 Asset Library I have a standard Asset Library and want to upload a .mpg file, but when I choose the file I get an alert

"Sorry, format of this video is not supported".

I checked, is available this format in IIS - yes, the feature Rich Media Content is activated. Also I found that .mpg is supported by Media Web Part SP 2013.
Is it mean that it is supported by Asset Library or not?
What cause of this behavior and how to fix it?

A: This file type may be blocked by your administrator. If you have administrative rights then you can enable it from Central Administration.
This are called as Blocked File Types
For this you can follow following steps :

*

*Open Central Administration

*Click Security tab

*In General Security click Define blocked file types

*On the Blocked File Types page, if you want to change the selected web application, on the Web Application menu, click Change Web Application. Use the Select Web Application page to select a web application.

*To stop blocking a file type, select a file type from the list, press the Delete key, and then click OK.

For more information you can click here
If you need to know all the file types which are blocked then you can go here


text:
Q: Elastic search pagination starting with a particular document I am using Elastic search to show a paginated list of products in a grid view in a mobile app. Now the user can scroll through the list and click on any product to view the details.
Now the detail view also supports scrolling through the products via swipe left and right. So for the detail view, I want to fetch paginated results from elastic search starting from a particular product.
For now I am calculating the index of the product in list view and then doing the math to fetch that particular page and scroll to the index.
Is there a better way to do this?

A: You can use the scroll api to get paginated results for your search query.
Alternatively, you can use the search_after api which seems to perform better for large number of results but it is available only for 7.x+ elastic versions.

A: I'm not totally certain — I haven't tested it myself — but I think the suggestion of using the search after API is the way to go.
You need to use something like the point in time feature, which is what the search after uses. Without it, you have no guarantee that the data in the database aren't changing. If the data change, then your search result may change. If that changes, then what comes "next" also changes, and that may no longer correspond to what you want.
E.g., if you currently have 10 search results and your item of interest is at index 5, if someone adds a document that moves your point of interest to index 6, then naïvely asking for the next item would return the same thing!
The point in time feature creates a snapshot of the database at a moment in time, so you don't have to worry about new or modified documents messing things up.
As an aside, using the point in time feature at scale is probably (again, making educated guesses here) not a very good idea. Elasticsearch has to keep a mini-snapshot of the whole database (!) every time you call that for the duration.
You're probably better off limiting the number of items people can page through to something large but manageable, and then reloading a new page if someone gets to the end. If you pull 500 products initially and someone gets to the end (which seems unlikely to me a priori), you could re-issue the search paged forward 500 items, deduplicate at the boundary and no one will be the wiser.


text:
Q: What happens to executing JS when user closes window (or nav away from it)? ScenarioA: synchronous functionA is executed. The user closes the window in the middle of functionA executing. Does execution of code simply stop as soon as the window is closed (or refreshed)? Imagine functionA makes many modifications of a db. Is it possible the db will be altered from the code in the first half of the function? If so, this could cause a problem in my project. Is there a way we can ensure the whole function is completed?
ScenarioB: setTimeout has a callback that executes after some time. The window's closed (just) before the callback's placed on the call-stack. Will the callback ever execute or is it just discarded?

A:
Does execution of code simply stop as soon as the window is closed (or refreshed)?

Yes.

Imagine functionA makes many modifications of a db. Is it possible the db will be altered from the code in the first half of the function?

Yes.

If so, this could cause a problem in my project. Is there a way we can ensure the whole function is completed?

No.
In general, with databases, you can use transactions so if the complete set of changes isn't completed it will rollback.

ScenarioB: setTimeout has a callback that executes after some time. The window's closed (just) before the callback's placed on the call-stack. Will the callback ever execute or is it just discarded?

It is discarded.


text:
Q: Using a MOSFET as a DCR I am trying to design a variable gain amplifier using a non inverting amplifier as a starting topology.

The way I intend to do it is by replacing R2 with a circuit as the following one.

It works great when the mosfet is fully on/off, when the mosfet is fully off, the gain is given by
Vout/Vin =  1 + (R1 / (R2 + R3))
Vout/Vin =  1 + (R1 / (R2 + R3)) = 1 + (1.2k / (400 + 100k)) = 1 + (0.011) = 1.01
Vout/Vin = 1 (aprox)

On the other side, when the MOSFET is fully on, we can neglect Rds on and assume a direct connection to ground is done, hence disabling any current flow through R3 and with that we can simplify the transfer function to:
Vout/Vin = 1 + (R1 / R2)
Vout/Vin = 1 + (1.2k / 400) = (1 + 3) = 4

With this configuration, by using the mosfet in its ohmic region the gain of the amplifier it's fully dependant on the mosfet Vgs. When Vgs < Vgs_th the gain is at its minimum, in this case aproximately 1. On the other side, when Vgs >> Vgs_th, the mosfet is fully on and its gain its at its maximum, in this case 4.
The downside of this configuration is that this introduces distortion to to the output waveform when the mosfet is not fully on/off, below is a picture, where the top plot represents Vgs, the middle represents Vin, and the bottom one is Vout

Is there a better way to aproach this?
Is there a way to reduce this distortion?
Thanks for sharing your thoughts.


text:
Q: Resources Exceeded during query execution I'm trying to run a query joining 2 large sets of data and I'm hitting the resources exceeded during query execution error.  I've read that there are work around when using Join Each and Group Each but not what those workaround would be.
SELECT
  year(users.firstseen) as first_year,
  month(users.firstseen) as first_month,
  DATEDIFF(orders.timestamp,users.firstseen) as days_elapsed,
  count(orders.user_key) as count_orders
FROM
  [project.orders] as orders
JOIN EACH
  [project.users] AS users
ON
  orders.user_key = users.user_key
WHERE orders.store = 'ios'
GROUP EACH BY 1,2,3

Edit: the following worked:
SELECT
  year(users.firstseen) as firstyear,
  month(users.firstseen) as firstmonth,
  DATEDIFF(orders.timestamp, users.firstseen) as days_elapsed,
  COUNT(users.firstseen) AS count_orders FROM [project.orders] as orders
JOIN EACH( SELECT user_key, firstseen FROM [project.users]
WHERE store_key = 'ios') as users ON orders.user_key = users.user_key
GROUP BY firstyear, firstmonth, days_elapsed
ORDER BY firstyear, firstmonth, days_elapsed

A: JOIN EACH can fail if your join keys (in this case, user_key) are unevenly distributed. For example, if you have one user_key that appears abnormally often, you'll get a "resources exceeded" error from the node that handles that key. Alternatively, you could try running the query over a smaller set of user keys by filtering out some portion of the user keys before the join.
GROUP EACH BY can fail if you have too many distinct group keys. You could try whittling down the join output by adding a few more WHERE clauses in order to see if this is the case.
Basically, I'd recommend whittling down the inputs to either the JOIN EACH or the GROUP EACH BY until you get the query to work, and then you'll have a better sense for the limits you're running up against. Once you know that, you can (hopefully) structure your queries to get the most out of the available resources.
(BTW, we expect to tune these operations in the near future to remove some of the limits you may be hitting!)


text:
Q: no such file to load -- openid/store/filesystem (Rails omniauth) This is first time I'm trying to use Omniauth. While I was testing https://github.com/pt/devise-omniauth-example this example from github I came across an error
 .rvm/gems/ruby-1.9.2-p290/gems/activesupport-3.1.3/lib/active_support/dependencies.rb:240:in `require': no such file to load -- openid/store/filesystem (LoadError)

Here is my Gemfile content
source 'http://rubygems.org'

gem 'rake'
gem 'rails'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'devise', :git => 'git://github.com/plataformatec/devise', :branch => 'master'
gem "omniauth", "1.0.1"
gem 'paperclip'
gem "simple_form", "~> 1.5.2"
gem 'twitter_oauth', '0.4.3'
gem "rest-client", "1.6.7", :require => "restclient"
gem "sluggable"

group :development, :test do
 gem 'rspec-rails'
 gem 'fixjour'
end

I search web but there was no luck.

A: According to this:
If you get "openid/store/filesystem (LoadError)" then you may need to add this to your Gemfile:
gem "oa-openid"

A: This is due to various versions of Gems you are using and the dependencies among them.
In the example at https://github.com/pt/devise-omniauth-example,
if you notice the Gemfile ,there is
gem 'omniauth', '0.2.0'

but in your Gemfile above, you are using
gem "omniauth", "1.0.1"

A: Add gem 'ruby-openid-apps-discovery', and add below in application.rb.
require 'omniauth-openid'
require 'openid'
require 'openid/store/filesystem'
require 'gapps_openid'


text:
Q: Apply style to particular row in a table Hi I've a table like below and I wanted to apply style for only tr which is belongs to  section.

            1
            2
            3
            4

            5
            6
            7
            8

When I try like below it is applying for all trs including  trs.

How can I restrict this style to apply only for header part.

A: use,
th
{
height:30px
}

Or else you can use class

A: Try this:

A: You can add a class to that tr and specify that class in the css, like this:

            1
            2
            3
            4

            5
            6
            7
            8

And in the css:

That should do the trick, please choose this as the correct answer if it solves your doubt by clicking on the tick symbol to the left.

A: use it like this

then in your CSS, refer it using a "." infront of your classname('my_class')
.myclass{
    //your styles go here
}


text:
Q: To prove Riemann surface isomorphism Let $A$ and $B$ be Riemann surfaces.
If we want to prove $f$:$A$→$B$ is isomorphism of Riemann surfaces, what we should do?
My book reads like this,
①Computing $f$'s effect on the cotangent spaces of $A$ and $B$
②To show $f$ is local analytic isomorphism ( I don't know it's definition).
③To show $f$ is bijective, then, we can conclude that $f$ is global isomorphism.
My question : What is the definition of local analytic isomorphism?
And why we can say $f$ is global isomorphism if we could show $f$ is also bijective?


text:
Q: Traverse through folder structure with Box API I'm looking for guidance on the best way to traverse a folder structure via the Box API in JavaScript. I need to recursively loop though the structure based on the responses from the Box API and take action on returned files and folders.
When a folder is found I need to get all of it's containing items, and if that folder contains folders with items I need to get those as well, and so on and so forth. See example below:
StartingFolder
    Folder1A
        File1B
        Folder2B
            Folder1C
                File1D
            File2C
        Folder3B
        File4B
    Folder2A
        Folder1B
            File1C
        Folder2B
            Folder1C
                File1D
        File2B
    Folder3A
        File1B

All of these items are identified by an id and a type. So I know that if I find an item with type: "folder" then I need to make another request to Box to get its items using its id. I can easily do this on the first level but I don't know how to traverse the entire structure through to the bottom of each branch.
Any examples or best practices someone could provide would be great!

A: I don't have a JavaScript example but here's one in Python. Hopefully it'll give you some conceptual guidance on how to proceed.
def doSomethingWithFolder(folder):
    # Do something with the folder here

def recurse(folderId):
    # get the folder contents
    contents = client.folder(folder_id=folderId).get_items(limit=1000, offset=0)
    # filter the contents for just the subfolders based on the 'type' property
    folders = filter(lambda x: x.type=="folder", contents)
    # for each subfolder...
    for folder in folders:
        # ... take some action on the subfolder ...
        doSomethingWithFolder(folder)
        # ... and recurse using the 'id' property
        recurse(folder.id)

recurse("0") # recurse starting from the root, or substitute another folder ID.


text:
Q: What does the server difficulty property do? While making edits to the server.properties file, I noticed there was a difficulty setting, which is currently set to 1.
I assume this is related to the client-side setting of the same name, but what options are valid in the properties file, and what does each difficulty setting change?

A: Server Difficulties
The difficulty of a server is configured on the server-side, regardless of what a players client is configured as. The difficulty property is an integer and has 4 potential values. The value defaults to 1, or easy.
Peaceful
Peaceful mode is active when difficulty=0. Hunger is disabled, as is eating, and health is regenerated all the time. Hostile mobs spawn if spawn-monsters is true, but they are removed immediately. (It is worth, therefore, to also set spawn-monsters to false).
Easy
Easy is the default difficulty, and is active when difficulty=1. Hunger is enabled, but will only cause damage when Steve has more than 5 hearts. Hostile mobs have less health and cause less damage, while creepers have a smaller detection radius.
Normal
Normal mode is active when difficulty=2. Hunger is enabled, and can cause damage down to 0.5 hearts. Hostile mobs have 'normal' health and cause 'normal' damage (see table).
Hard
Hard mode is active when difficulty=3. Hunger is enabled, and can kill Steve. Hostile mobs deal greater damage and have a small amount of extra health. Creepers have a larger detection radius for triggering their attacks.
TL;DR:
| difficulty | id | hunger | zombie/enderman | skeleton | spider | creeper |
+------------+----+--------+-----------------+----------+--------+---------+
| peaceful   | 0  | n/a    | n/a             | n/a      | n/a    | n/a     |
| easy       | 1  | 5      | 1               | 1        | .5     | 5.5     |
| normal     | 2  | 0.5    | 2.5             | 2        | 2.5    | 10      |
| hard       | 3  | 0 (die)| 3.5             | 3        | 3.5    | 10.5    |


text:
Q: Update or delete existing file and create new file I want to create a file name with current time and that will be scheduler which runs every one hour. My problem is I need to replace that file name every scheduled time. Please help me guys how to rename or delete existing file and create new file.

A: You could try something like that:
public static void main(String[] args) {
    Timer time = new Timer(); // Instantiate Timer Object
    ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
    time.schedule(st, 0, 60 * 60000); // Create Repetitively task for every 1 hour
}

static class ScheduledTask extends TimerTask {
    private Path lastFilePath = null;
    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MM.yy_hh_mm");

    // Add your task here
    public void run() {
        try {
            if (lastFilePath != null) {
                Files.delete(lastFilePath);
            }
            LocalDateTime date = LocalDateTime.now();
            String fileName = date.format(dtf);
            lastFilePath = Paths.get(fileName);
            Files.createFile(lastFilePath);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
Q: Is window.location.href = 'some_page.html' followed by search engines? Currently our website uses links to allow the user to change their locale.  The problem with this is that you get a lot of random outlinks from each page on the site to... the same page, in other languages.  When a search engine traverses this, it gets an excessively complex view of the site.
We were going to change it to a form post to avoid this.  However, it seems to me that we should just be able to change it to an onclick="window.location.href='change_my_language.php'" rather than an href="change_my_language.php".  Am I right?  Or do the major search engines scan for and follow this sort of thing nowadays?

A: To solve the larger problem of duplicate content, you can use the canonical link tag to specify on the pages in other languages the URL of the preferred document.
<!-- on http://www.example.com/article.php?id=123&language=something-else -->
<link rel="canonical" href="http://www.example.com/article.php?id=123" />

To save search engines the trouble of landing on the other pages, it wouldn't hurt to add rel="nofollow" to the links, to ensure that robots don't waste their time checking them out. However, the canonical link tag is still vital, in case someone links to your other-language content, to ensure that your preferred page gets the ranking credit.

A: I'm fairly certain search engines don't parse JavaScript, so any code that changes the value of any property of the location object wouldn't follow the URL.
EDIT
An interesting article on the topic: http://www.seroundtable.com/archives/019026.html
and bobince's answer on this potential duplicate question suggests the same:  window.location and SEO

A: POST method must be used when the request changes server's state, i.e. request has side-effects:
http://www.cs.tut.fi/~jkorpela/forms/methods.html
No, search engines won't be able to follow javascript links, but POST is more elegant solution.

A:
When a search engine traverses this, it gets an excessively complex view of the site.

This should not be a problem. As long as you are correctly marking up each page with lang="...", the search engine should know what to do with it. What is the actual problem you are facing that leads you to believe search engines are confused by a 'complex' link map?
You can give them a sitemap if you really want to be explicit.

However, it seems to me that we should just be able to change it to an onclick="window.location.href='change_my_language.php'" rather than an href="change_my_language.php"

That would degrade the site's usability and accessibility a little as well as (deliberately) sabotaging the search engine.
In any case, whatever you do you should definitely leave each language version on its own URL (eg. /en/category/title) rather than totally relying on a language-setting cookie, or you really do run the risk of confusing search engines. Normally you do want search engines to index every language version you have, to catch searches from users of other languages.

A: Google is getting increasingly better at parsing JavaScript. I don't think that the search engines will follow this link now...but to be more certain they don't follow you can change your anchor tags to spans instead and use the onclick="document.location='url'" method.
Though what you may want to do is add rel="nofollow" to these links instead. You can also add a canonical link to the main page.


text:
Q: viewDidAppear called before applicationDidBecomeActive I'm just starting an iphone app with a initial viewcontroller which is embeded in a navigationController and have a pushSegue to a tabBarController.
Whenever I run the simulator,  viewDidAppear of the initial viewController called before applicationDidBecomeActive being called.
Isn't it suppose to enter applicationDidBecomeActive in appdelegate before any viewController load?

A: In iOS8, viewDidLoad used to run before applicationDidBecomeActive. However, in iOS9, I'm seeing that with the same code, applicationDidBecomeActive is running before viewDidLoad. Strange.

A: Yes it's ok I think you are just little confuse. How an application will become active until it's load it's view.
When you first time launch the application will call the method in order -
From App Delegate -
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

From View Controller -
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil

- (void)viewDidLoad

- (void)viewWillAppear:(BOOL)animated

- (void)viewDidAppear:(BOOL)animated

From App Delegate -
- (void)applicationDidBecomeActive:(UIApplication *)application

A: applicationDidBecomeActive is a delegate located in your Application Delegate and there's no guarantee that it will be called before any other UIViewController delegates (viewWillAppear, viewDidLoad etc.). If you want to make any logic before loading of any other view controller method is called, you may want to use application:didFinishLaunchingWithOptions:.


text: Q: Vector field interpolation Given a discrete set of vectors in $\mathbb{R}^2$, there seem to be algorithms (https://mathematica.stackexchange.com/questions/77701/interpolate-a-discrete-vector-field) that can 'interpolate' these vectors and give a smooth vector field on all of $\mathbb{R}^2$ that matches with the original vectors at their points. How exactly does this work?


text:
Q: Kth number in lexicographically sorted numbers from 1 to N Given an integer N, find the kth ranked no in a lexicographically sorted numbers array from 1 to N.
Ex: N = 12
Lexicographically sorted numbers are: [1, 10, 11, 12, 2 , 3, 4, 5, 6, 7, 8, 9]
If K=4, the program should return: 12.
The complexity of the program should be O(logN).
The array is generated for the purpose of explaining and not provided as an input. Generation of the array and sorting will take Nlog(N) time, thus defeating the purpose.
I recently faced this question in an interview process. Could not figure out the solution in given time complexity, hence asking for help
Thanks!!

A: Let's take N = 13000, K = 12031. Each digit from 1 to 9 when assigned as left-most gets:
                                      total
1 single digit number 9 * 1              9
10 two-digit numbers  9 * 10            99
100 three-digit numbers 9 * 100        999
1000 four-digit numbers 9 * 1000      9999
10000 five-digit numbers      --->  here we have to start examining

                                             Total
                                             ----
1 gets 13000 - 8 * (1 + 10 + 100 + 1000)  =  4112 of them
2 gets 1111                                  5223
3 gets 1111                                  6334
4 gets 1111                                  7445
5 gets 1111                                  8556
6 gets 1111                                  9667
7 gets 1111                                  10778
8 gets 1111                                  11889
9 gets 1111 ----> answer is somewhere here

Answer: 9xxx. Now the second digit. For each number that ends in one or more zeros, we have to count all lower numbers with an equivalent prefix.
3 numbers with zero or nothing before 9000   11892
9 90 900

100 + 9 numbers with 90xx
9000 9001 9002.., but also 901 902..         12001

Answer: 91xx. Third digit.
2 numbers with zero or nothing before 9100
91 910                                       12003

10 four-digit numbers with 0 as third digit
9100 9101 9102..                             12013

1 number with zero or nothing before 9110
911                                          12014

10 numbers with 1 as third digit
9110 9111 9112..                             12024

1 number with zero or nothing before 9120
912                                          12025

+ 6

Answer: 9126


text:
Q: Prevent WPF Textbox from changing appearance when focused In my custom control I have 2 textboxes. When either one of them is focused, it changes its style slightly... it looses a bit of its border. I would like to prevent this behaviour, which seems to be default textbox behaviour.
Now, I assume that its something to do with the style, possibly with the part of the textbox template
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>

However, is there anyway to prevent this?

A: @Daniel You have to edit Focussed State StoryBoard. For that edit your TextBox Template for changing the State.If you have Expression Blend  it will be easy for you.

A: You have to edit the default TextBox ControlTemplate which you can find here.

A: *

*You need a control template for your custom control.

*In the resources there, you need to style all text box target types. This way, you dont affect regular text boxes.

It would be helpful if you share some code which we can look at/modify to achieve what you need.


text:
Q: CoreData - Relationship One to Many - Data Model
Here is my Core Data structure . I have three Entities Room Key and KeyRoomMap . Now I have two attributes in Room and Key . I want the ID attribute of both of them should be associated with the third table KeyRoomMap and there is also more one element SuggestedTestPlan in the KeyRoomMap .
My Questions are

*

*This is the structure like - SQL Tables here. But I feel this is the
wrong structure in core Data . I want to join keyID and roomID
with some relationship with KeyRoomMap . How can I do it like if I
add keyID and roomID , it should be automatically added in
KeyRoomMap ?

*there are more keys for each rooms . so key1 , key2 are associated
with room1, key3 is with room2 and key4,key5,key6 are with room3
.How can I make such relationship here ?

-----------------------Edited and Added
Actually my confusion also starts with if key1 and key2 are associated with Room1 . I can join them with the one to many relation there . but the keyroomMap entity was defined for saying that key1 and key2 are associated with Room1 . If I dont make this table then only on the basis of relations out of so many keys how should I say that ??

A: Indeed it looks like you are planning it like SQL tables.
From your explanation it sounds like:

*

*A Room can have many keys

and

*

*A Key can unlock one room

Therefore I would say the relationship on your Room entity would be 'keys' and this is a to-many relationship. Keep in mind in core data you need to set up inverse relationships also so the corresponding relationship on the Key entity would be room and would be a to-one relationship.
I have included the datamodel diagram as an image below.

I'm not really sure what your purpose is for the KeyRoomMap? Could that suggestedTestPlan property exist on Key or Room instead? It seems as though KeyRoomMap entity has two relationships in that for a KeyRoomMap to exist it must have a corresponding Room and Key both of which are to-one relationships. I've included a possible diagram for that but without more info I can't be sure.

EDIT: Otherwise is suggestedTestPlan a property that could be derived or calculated based on the other Entities? ie. Fetched properties https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/Articles/cdRelationships.html#//apple_ref/doc/uid/TP40001857-SW7


text:
Q: Rendering a Simple button view in Backbone & Handlebars Totally new to Backbone, and for now my spine is getting stiff getting around a few things.
F.Y.I: I am using Handlebars as my templating engine.
What I am trying to do, is to render a simple Button on my page. For this, in my templates, I have:

And it's view is defined like this:
var SimpleButtonView = Backbone.View.extend({
        tagName: 'button', // how can I define other attribute properties such as Text for button?
        template: $('#newButton').html(),
        initialize: function(){ this.render(); },
        render: function(){
              var tmpl = Handlebars.compile(this.template); // what does compile do
              this.$el.html(tmpl());// why is this a function?
              return this;
        }
});

And finally, I do
var btnView = new SimpleButtonView();

Which doesn't render anything. What am I doing wrong here :) ? Also, questions to my inline comments are also much appreciated coz I am fairly lost.

A: I would do something roughly like this:
HTML:

JS:
var SimpleButtonView = Backbone.View.extend({
    el: $('#app'),

    tagName: 'button',

    $template: $('#button-tpl'),

    initialize: function(options) {
        options = options || {};
        this.buttonText = options.buttonText || 'Default button text';
        this.template = Handlebars.compile(this.$template.html());
        this.render();
    },

    serialize: function() {
        return {
            buttonText: this.buttonText
        };
    },

    getContext: function() {
        var context;

        if (_.isFunction(this.serialize)) {
            context = this.serialize.call(this);
        } else if (_.isObject(this.serialize)) {
            context = this.serialize;
        } else {
            context = {};
        }

        return _.extend({
            model: this.model,
            collection: this.collection
        }, context);
    },

    render: function() {
        this.$el.html(this.template(this.getContext()));
        return this;
    }
});

var simpleButtonView = new SimpleButtonView({
    buttonText: 'Hello motto'
});

Fiddle: http://jsfiddle.net/ferahl/0z1d9zx5/1/
Explanation:
var template = Handlebars.compile(this.$template.html());

This tells handlebars to compile the html from that template. That means that handlebars internally prepares a javascript FUNCTION with the html. This template variable is re-useable because you can pass different CONTEXTS to it and it will spit out html depending on what context (data) you passed.
This is why I put it in the initialize routine - it only has to happen once - you could subsequently call render 100 times with different buttonText and it would be much faster because it has already prepared the template.
this.$el.html(this.template(this.getContext()));

As you can see I have abstracted away the passing of data to the template to a method called  getContext. All that getContext does is return an object of key-values which can be used in the template.
Here's the important bit:
I abstracted it away because in an ideal setup you would have your own View extension which would do common useful stuff. In that extension you would do things like handling rendering and you would put the getContext function there. All views in your app would extend off of that view instead of straight from the Backbone one, so that for each of your views you would only have to do the bare minimum - i.e supply a $template and create a serialize method if you wanted to pass any special stuff to the template.
P.S. Note that some html has to go into the template tag - on it's own the template tag is not an element so some html has to be inside it for it to work.


text:
Q: How do I web scrape data on an HTML page that only shows up on a mouse hover over parts of a map/image using Python? I am trying to scrape the following data from a map on this page: https://a816-dohbesp.nyc.gov/IndicatorPublic/AQHub/explorer.html
Screenshot of the map I am talking about

*

*Groupings by the colors on the map (Low/Medium/High)

*Neighborhood names that show up on a mouse hover

Question: How do I figure out which elements to scrape the data from?
When I inspect the map, it points to this HTML code, but it doesn't seem to change when I move my cursor around the map. I can't seem to find an XPath for the text elements showing the individual names that pop up when you hover your mouse over the map. I am trying to use Python (BeautifulSoup and Selenium).

<canvas width="546" height="500" class="marks">

Ideally I'd like to end up with a spreadsheet that has the the following information like this:

Neighborhood
Building emissions
Building density
Industrial Area
Traffic Density

Midtown-Midtown South
High
High
High
High

This is my first post on stackoverflow, so please let me know how I might better ask my question.

A: Well, you could move the mouse around via ActionChains on the canvas, but probably want the data (and not complicating things).
Try: results = driver.execute_script("return nyccasData").


text:
Q: Entry page for a wordpress multisite I am quite new too WP multisite, so forgive me for my ignorance on things.
I have set up multisite ok and have setup 4 sites (i am using subdomains)

*

*mysite.com // the root site

*london.mysite.com // subsite

*oxford.mysite.com // subsite

*manchester.london.com // subsite

All the subsites are using the same template, well child templates of the main template so i can change the background colour of the site for each particular subdomain.
on the mysite.com doamin, I would like to have a really simple page, could be static html for all i care, simply with links to each of the subdomains, there is to be no other content in this main domain just images or something similar so the visitor can go to the subsite they require.
Whats the best way of doing this? i take i i cant just upload a static index.php as this will break the subsites.
and as i have the default page for the site set to this i guess i have to load in the main wordpress index.php whatever i do.
thanks for your time and suguestions

A: You have at least three options:

*

*use a Child Theme on mysite.com, in which you replace index.php with whatever you want

*Use a different Theme entirely on mysite.com - could be a landing-page Theme or whatever.

*Use your current Theme on mysite.com, but set it to display a static page as front page, put your subsite links in the page content of the page displayed as the site front page, and remove all other content


text:
Q: TextView only updates once I'm having a seemingly strange issue with my android app.
Whether I call append or setText, my TextView will only update once.
I have my IME set to have a "Send" button that listens as follows:
        sendText.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event){
            if(actionId == EditorInfo.IME_ACTION_SEND){
                try {
                    send();
                    scroller.post(new Runnable() {
                        @Override
                        public void run() {
                            scroller.fullScroll(ScrollView.FOCUS_DOWN);
                        }
                    });
                } catch (Exception e) {
                    Log.e("chat", e.toString());
                }
            }
            return true;
        }
    });

The send method:
public void send(){
    final String message = sendText.getText().toString();
    final String ip = ipAddr.getText().toString();
    //rcvMsg.append("Me:  " + message + "\n");
    runOnUiThread(new Runnable(){
        public void run(){
            TextView rcv = (TextView)findViewById(R.id.rcvMsg);
            rcv.setText(rcv.getText()+"Me: "+message+"\n");
        }
    });
}

As you can see, I tried append and a setText in runOnUiThread. Both of those only update the textView the first time send() is called. On subsequent calls, it doesn't change.
But!
If I put the app in the background (hit home), then relaunch it, the TextView has all the proper text.
What am I missing?

A: I figured it out - it was a GUI issue..
I accidentally set the height of the TextView (inside a scrollview) to an exact value. Apparently, this caused the fullScroll method to screw up and not scroll down completely, so the added text was invisible. Setting the height of the TextView to wrap_content solved the problem.

A: Put below line of code after setContentView in your activity and remove from send method
TextView rcv = (TextView)findViewById(R.id.rcvMsg);

Change this line rcv.setText(rcv.getText()+"Me: "+message+"\n");
 to
rcv.setText(rcv.getText().toString()+"Me: "+message+"\n");

in send method

A: You should not put
TextView rcv = (TextView)findViewById(R.id.rcvMsg);
rcv.setText(rcv.getText()+"Me: "+message+"\n");

In a runnable.  Your code should look more like this.
public void send(){

    TextView rcv = (TextView)findViewById(R.id.rcvMsg);
    rcv.setText(rcv.getText()+"Me: "+sendText.getText().toString()+"\n");

}

If you are sending this message using the ip variable somehow you would do that inside of a runable, but setting the textarea inside of a runable is impossible seeing as the two are running on separate threads.


text:
Q: Mongoose - Is it possible to access object properties with schema path? As title. There's an object property vote under ActionSchema. I want to access vote.type, but path('vote.type') doesn't work.
ActionSchema = new Schema({
  vote: {
    type: String
  }
});

// TypeError: Cannot call method 'enum' of undefined
ActionSchema.path('vote.type').enum(['upvote', 'downvote']);

A: The issue is that vote.type isn't the path, vote is. So if you want to modify the vote property, then you want to use ActionSchema.path('vote')
So to add an enum:
ActionSchema.path('vote').enum('upvote', 'downvote');

* Note that you don't pass an array of enum values to this function, you pass the values in as multiple arguments. See the Mongoose documentation for more details.


text:
Q: matplotlib.use required before other imports clashes with pep8. Ignore or fix? I have a Python script that starts like this:
#!/usr/bin/env python
import matplotlib
matplotlib.use("Agg")

from matplotlib.dates import strpdate2num
import numpy as np
import pylab as pl
from cmath import rect, phase

It works like a charm, but my editor complains: E402 module level import not at top of file [pep8].
If I move the matplotlib.use("Agg") down, the script will not work.
Should I just ignore the error? Or is there a way to fix this?
I'm aware that PEP8 says that this is only a suggestion and it may be ignored, but I'm hoping that there exists a nice way to initialise modules without breaking PEP8 guidelines, as I don't think I can make my editor ignore this rule on a per-file-basis.
(I'm using Atom with linter-pylama.)

A: The solution depends on the linter that is being used.
In my case I am using pylama
The manual for this linter suggests adding # noqa to the end of a line containing an error you wish to suppress.
Other linters may have different mechanisms.

A: Another, not so nice, solution, but one that I've temporarily deployed for an environment with matplotlib 1.0.0, is to use a wrapper module.
Inmatplotlib_agg.py:
import matplotlib
matplotlib.use('Agg')

In other files:
import matplotlib_agg
# other imports

Not sure whether this is worth it. I would prefer to ignore it in the editor; but I couldn't get the one I use (PyCharm) to ignore just this one particular violation of PEP8 E402.

A: Apparently, matplotlib now has a switch_backend() function:
import matplotlib.pyplot
# import other modules
matplotlib.pyplot.switch_backend('Agg')

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.switch_backend
But beware, you run the risk of exploding:

Switch the default backend. This feature is experimental, and is only
  expected to work switching to an image backend. e.g., if you have a
  bunch of PostScript scripts that you want to run from an interactive
  ipython session, you may want to switch to the PS backend before
  running them to avoid having a bunch of GUI windows popup. If you try
  to interactively switch from one GUI backend to another, you will
  explode.
Calling this command will close all open windows.

It works nicely for me with matplotlib 1.3.1 but not with 1.0.0.


text:
Q: Unresolved node modules dependency using Webpack and System I have the following ES6 import in my code to import a project dependency from the node_modules folder:
import React from 'react';

By using this webpack configuration, everything works as expected:
{
  module: {
    loaders: [
      {
        loader: 'babel',
        test: /(\.js|\.jsx)/,
        exclude: /(node_modules|bower_components)/
      }
    ]
  }
}

I end up with a bundled file containing the react dependency that has been automatically added.
But if I configure babel to use modules: 'system' to output imports as System.register:
{
  module: {
    loaders: [
      {
        loader: 'babel',
        test: /(\.js|\.jsx)/,
        exclude: /(node_modules|bower_components)/,
        query: {
          modules: 'system',
          moduleIds: true,
          keepModuleIdExtensions: true
        }
      }
    ]
  }
}

then the bundled file does not contain anymore the react dependency and I have to append the systemjs library to the compiled file after going through webpack.
How are we suppose to handle this configuration using webpack? why can't webpack bundle the react dependency using system as it already does when compiling into commonjs?
PS: I am specifically asking to achieve this using webpack, not systemjs-builder or jspm

A: That's not how Webpack works. Webpack can handle AMD and CommonJS modules, it cannot handle SystemJS modules.
For Webpack to support a module system, it needs to be able to look at the JS and statically decide what files depend on what, and then modify the file so that it will work and be compatible with other modules. It doesn't now what SystemJS is, so all it sees is a JS file that doesn't reference any CommonJS modules because it never uses require().


text:
Q: How to show calculator functionality when i click on Area Calculator Text? i am developing the area calculator function. when i click on Area Calculator it has to show the calculator functionality and when i click agin it has to close.
for refernce please find the below link.
https://totaltiles.co.uk/white-marble-effect-matt-porcelain-floor-tile.html
How can i solve this one.
https://codepen.io/somunelavalli/pen/JjrMozd
My code is like below
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
    />

       Area Calculator

              Area(s) to be tiled

                  Width
                  Height
                  Unit
                  Area

                    <input
                      class="areacalc-input"
                      type="text"
                      name="width"
                      data-bind="value: $row.width, valueUpdate: 'keyup'"
                    />

                    <input
                      class="areacalc-input"
                      type="text"
                      name="height"
                      data-bind="value: $row.height, valueUpdate: 'keyup'"
                    />

                    <select
                      name="unit"
                      class="areacalc-select"
                      data-bind="options: $parent.unitsArray, value: selectedUnit"
                    >
                      <option value="m">m</option>
                      <option value="mm">mm</option>
                      <option value="cm">cm</option>
                      <option value="inches">inches</option>
                      <option value="feet">feet</option>
                    </select>

                    0
                    m²

                    Total
                    0
                    m²

              Area(s) to be deducted

                  Width
                  Height
                  Unit
                  Area

                    <input
                      class="areacalc-input"
                      type="text"
                      name="width"
                      data-bind="value: $row.width, valueUpdate: 'keyup'"
                    />

                    <input
                      class="areacalc-input"
                      type="text"
                      name="height"
                      data-bind="value: $row.height, valueUpdate: 'keyup'"
                    />

                    <select
                      name="unit"
                      class="areacalc-select"
                      data-bind="options: $parent.unitsArray, value: selectedUnit"
                    >
                      <option value="m">m</option>
                      <option value="mm">mm</option>
                      <option value="cm">cm</option>
                      <option value="inches">inches</option>
                      <option value="feet">feet</option>
                    </select>

                    0
                    m²

                    Total
                    0
                    m²

You will need

                  Total area:

                    0
                    m²

                  Tiles required:

                    0

                  Est. Grout required:

                    0
                    x 3kg bag(s)

                  Est. Adhesive required:

                    0
                    bag(s)

                    Add
                    10%
                    for wastage?

                    <input
                      type="checkbox"
                      style="float: left; margin-right: 5px"
                      data-bind="checked: $data.isWasteEnabled"
                    />

A: use jquery, also add cdn link to your html

$( document ).ready(function() {
  $('.tt-area-calculator-title').click(function(){
        $(".tt-calculator-container").toggleClass("active");
  })
 });


text:
Q: New custom post type entries are not sorted correctly in admin using pre_get_posts I am working on a WordPress plugin and trying to use the pre_get_posts hook. Everything seems to sort, but when I add new items through the back-end, they get added to the bottom and not sorted for some reason. Hoping a fresh set of eyes could help.
add_action( 'pre_get_posts', 'simple_class_custom_query' );

function simple_class_custom_query ( $query ) {
    // Sort Archive Page Results
    if ( is_post_type_archive( 'simple_class' ) && $query->is_main_query() ) {

        // Sort results by class day
        $query->set( 'meta_key', 'class-day' );

        // orderby class start
        $query->set( 'orderby', array( 'meta_value' => 'ASC', 'class-start' => 'ASC' ) );

        // Hide hidden classes
        $query->set( 'meta_query', array(
            array(
                'key' => 'hide-class',
                'value' => '1',
                'compare' => 'NOT EXISTS'
            )
        ));
    }
}

Thanks in advance! Should add this has a few pieces. The hide-class is a meta checkbox to hide the class and the classes should be sorted by the day of the week the class takes place and then by start time.


text:
Q: PayPal WebHook Verification in PHP Referencing the answer here: PHP verify Paypal webhook signature
Is this still the working solution for today (Jan '22)? Curious why it says on github.com/paypal/PayPal-PHP-SDK that this package is deprecated? (and archived)?

A: That SDK is deprecated and not maintained. There is no support for it.
There are two supported ways to verify a webhook, either post it back to an API endpoint, or verifying the cryptographic message signature yourself.

*

*Verifying a message signature

*Posting back to PayPal
Neither document is specific to PHP, but has the information necessary to adapt into your own implementation in any language.


text:
Q: update query inside view in mysql mysql> create view incremented_salary as
    -> update employee set salary=salary*1.1;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use near
'update employee set salary=salary*1.1' at line 2

can we put update query inside view? If yes then please tell me why I'm getting above error.I want to increment the salary and display it using view.

A: Why dont you
create view incremented_salary as
  select salary*1.1 from wahtevertable

Views do not modify the values of tables.
They give you a new View on them - f.e. joining multiple tables, aggregating and maybe recalculate some values based on tablevalues.
If what you tried would work, everytime you`d viewed the data, it would increase in value.


text:
Q: Can't make tslint work with Sublime Text 3 The problem is I can't make tslint work in my Sublime Text 3. Whenever I open any tsx file it shows "Linting..." in the tray for a while, but then always shows "tslint(ok)". Even though I know there are lots of errors in my code. I checked it by running tslint command in the terminal, where I get a big list of errors.
Here's my environment:
Linux Ubuntu 16.04 LTS
Sublime Text v3.1.1 Build 3176
Typescript v2.9.1 (installed globally)
TSLint v5.10.0 (installed globally)
NVM v0.33.8
Node.js v6.11.4 (runs through NVM)
I have installed all necessary packages in my Sublime Text, as SublimeLinter and SublimeLinter-tslint.
Here's the content of settings of SublimeLinter:
{
"debug": true,
"linters": {
    "tslint": {
        "disable": false,
        "args": ["--project=${folder}/"]
    }
},
"paths": {
    "linux": [
        "/home/akbar/.nvm/versions/node/v6.11.4/bin"
    ]
}
}

As you can see the debug setting is set to true, but there's no error in the console. I also read about tslint not working with NVM. But I fixed that by adding path to node executable in paths setting of SublimeLinter.
But I believe the problem is different here. TSLint seems like working, but it just doesn't catch any errors in Sublime Text.

A: Try adding the env option in the specific linter configuration, it should look like this:
{
  "linters": {
      "tslint": {
          "disable": false,
          "env": "~/.nvm/versions/node/v12.6.0/bin",
          "args": ["--project=${folder}/"]
      }
  },
  "paths": {
      "linux": [
          "~/.nvm/versions/node/v12.6.0/bin"
      ]
  }
}

This should work on this environment:

*

*Sublime Text v3.2.1 Build 3207

*Typescript v3.5.3 (installed globally)

*TSLint v5.18.0 (installed
globally)

*NVM v0.33.11

*Node.js v12.6.0 (runs through NVM)

See related issue here


text:
Q: how to map in hibernate I am new to hibernate.
I am facing problem at the time of mapping
in my table no primary key is there . but two not null values are there
how i can represent them in hibernate
thanks in advance
my table structure is like this
Field                   Type         Collation          Null    Key     Default  Extra           Privileges                       Comment
----------------------  -----------  -----------------  ------  ------  -------  --------------  -------------------------------  -------
ApplicationId           bigint(20)   (NULL)             NO      PRI     (NULL)   auto_increment  select,insert,update,references
ApplicationName         varchar(32)  latin1_swedish_ci  YES             (NULL)                   select,insert,update,references
IsTimeSubsciptionValid  tinyint(4)   (NULL)             YES             0                        select,insert,update,references
IsUserCountValid        tinyint(4)   (NULL)             YES             0                        select,insert,update,references
MaxUserCount            int(11)      (NULL)             YES             0                        select,insert,update,references
IsMaxAccessCountValid   tinyint(4)   (NULL)             YES             0                        select,insert,update,references
MaxAccessCount          bigint(20)   (NULL)             YES             0                        select,insert,update,references
IsParentingAvailable    tinyint(4)   (NULL)             YES             0                        select,insert,update,references
TimePeriodAllowed       bigint(20)   (NULL)             YES             0                        select,insert,update,references

Table Query.

Table             Create Table
----------------  -------------------------------------------------------
ApplicationTable  CREATE TABLE `ApplicationTable` (
                    `ApplicationId` bigint(20) NOT NULL auto_increment,
                    `ApplicationName` varchar(32) default NULL,
                    `IsTimeSubsciptionValid` tinyint(4) default '0',
                    `IsUserCountValid` tinyint(4) default '0',
                    `MaxUserCount` int(11) default '0',
                    `IsMaxAccessCountValid` tinyint(4) default '0',
                    `MaxAccessCount` bigint(20) default '0',
                    `IsParentingAvailable` tinyint(4) default '0',
                    `TimePeriodAllowed` bigint(20) default '0',
                    PRIMARY KEY  (`ApplicationId`)
                  ) ENGINE=MyISAM DEFAULT CHARSET=latin1

A: You've probably already found out that Hibernate requires a primary key, even if there isn't one on the table.  Any unique key will do (and I believe there's a way to use ROWID as well).
It looks like you want something like this:
    <id name="ApplicationId" column="APPLICATIONID">
    </id>

but you say there are 2 not null values you want to map?  I'm a little unclear as to what the problem is.


text:
Q: JEE6: Custom Realm vs ResourceFilter - which one is better for REST resource authentication? I have a JEE6 application, residing on Glassfish 3.1.1, which provides service to remote clients via a number of REST resources. Some of the resources require authentication, others don't.
Currently I'm protecting the secure resources with HTTP Basic Authentication, implemented as a custom realm / LoginModule. If the authentication fails, the login module throws a LoginException, Glassfish maps that to HTTP 401. If the authentication is successful, the resources can access the userPrincipal in the securityContext.
While it works, it does annoy me that I cannot intercept the LoginException. My clients expect xml or json; in the HTTP 401 body, Glassfish gives them text/html. All other application exceptions I can intercept with an ExceptionMapper, just not the LoginException.
At the moment I'm thinking about replacing the Custom Realm with a ResourceFilter, where I would do the HTTP Basic authentication manually. I would expect that if I throw an exception here, it's gonna get intercepted and mapped / marshalled properly.
My questions are:

*

*Is it a good idea to use a ResourceFilter for authentication? What about performance?

*How would I let the REST resource know, who just got authenticated (who's the userPrinicipal)?

A: A bit late but anyway...
Its the container who does the authentication so it will never reach your resource. Personally I like the container managed authentication approach because it nicely separates the authentication from the application.
If you want to use a ResourceFilter you can access the SecurityContext from the request. This contains the Principal. From there you could populate e.g. an ApplicationConfig object which is accessible throughout the application.
Performance depends on the authentication implementation. I guess the overhead when using a ResourceFilter is minimal. If required you could always use a session cookie to keep the session to prevent authentication again.


text:
Q: Propel_Generator - include paths in the classmap-file incorrect i am using the propel runtime v1.5.4 and its related propel_generator in my zend_framework/php project since two years without any problems.
Yesterday i have updated the propel_generator via pear to v1.6.5 and the runtime library to v1.6.6. After the first build-proccess with the new generator i have a problem with the generated classmap-[project]-conf.php file:
Old Generator (v1.5.4)
...

      'AutocompleteQuery' => 'AutocompleteQuery.php',
      'AutocompleteTableMap' => 'map/AutocompleteTableMap.php',
      'BaseAclAssertion' => 'om/BaseAclAssertion.php'

...

New Generator (v1.6.5)
...

      'AutocompleteQuery' => 'AutocompleteQuery.php',
      'AutocompleteTableMap' => '/map/AutocompleteTableMap.php',
      'BaseAclAssertion' => '/om/BaseAclAssertion.php'

...

The new generator adds a leading slash before the 'map' and 'om' path. So the propel autoloader can not find the class-files.
Is there any config-option or a generator-template where i can change this?
Thanks.

A: It seems the targetPackage build property is empty in your configuration. By default, Propel uses the project name as target package, so that you always have a directory before your classes:
  // ...
  'AutocompleteQuery'    => 'project/AutocompleteQuery.php',
  'AutocompleteTableMap' => 'project/map/AutocompleteTableMap.php',
  'BaseAclAssertion'     => 'project/om/BaseAclAssertion.php'

I fixed Propel to remove this limitation, that way it will generate a valid package path. I'm talking about packages here because packages are used to determine where to write files.
Documentation to understand packages in Propel:
http://www.propelorm.org/cookbook/multi-component-data-model.html#understanding_packages
Fixed by commit:
https://github.com/propelorm/Propel/commit/b03569a802471b86e6e52287974de17f836c9baa


text:
Q: Reliability of Path_INFO server variable in classic ASP Am I always going to be able to use PATH_INFO to derive the root of my application as in the following function?
function CommonFunctions_getRoot()

    pathinfo=Request.ServerVariables("PATH_INFO")

    Set myRegExp = New RegExp
    myRegExp.IgnoreCase = True
    myRegExp.Global = True
    myRegExp.Pattern = "^(/\w*/).*"
    CommonFunctions_getRoot = myRegExp.Replace (pathinfo, "$1")

end function

A: PATH_INFO is reliable. The only problem I can think of is that you may have issues if you use URL rewriting.


text:
Q: Can two containers swap serving the same IP:PORT back and forth in AWS? The context
I am trying to run a Minecraft server on TCP/25565, which requires a constantly running server that has access to a large amount of memory and CPU. This would be expensive to run constantly. However, without running it constantly, there's no way for a client to easily connect and turn it on. In order to provide the illusion of an always running service I've come up with a two server solution, one full server and one standby.
The solution so far
I have two Docker containers which run servers on TCP/25565.
The full server runs Minecraft along with a background process that shuts itself down if it ever detects that there are no clients logged in. This code is working just fine.
The standby server runs a fake Minecraft server which adheres to the protocol and responds to any login with a message that says "The real server is not yet running. Please wait." and then immediately starts the full server. This code also works.
The problem
The issue I have is how to make the standby server and the full server share an IP address so that port 25565 is routed to the standby server by default but to the full server whenever it's running. Currently, the standby server always runs in the cheapest way it can with the lowest amount of resources. It starts the full server, but, the full server cannot be connected to in anyway. It's IP address is unknown to the user. I can't seem to find any way in ECS to hot swap the two containers easily. Does anyone know how to do this?
Possible solutions
I believe this is possible with an Application Load Balancer, however, this would cost $16 a month to run constantly which is not exactly saving money. I'm hoping to run this for less than $5 per month assuming there's no activity on the full server. When there is activity on the full server, it will be paid for by the minute that it's running.
I have looked into a way for an AWS Lambda or something to respond to arbitrary port traffic or spin up an ECS container as a response to port traffic, obviating the need for the always on standby server but I cannot seem to find a solution that does this.
I could completely skip the process and provide a webpage that users go to if the server is not on and this webpage will allow anyone to simply turn on the server.


text:
Q: JavaScript: Array accessible by index only inside function, not outside too Long story short: I have to read data from a .csv file with JavaScript and I have a function which fills my global defined array with data (= each array's entry is a new Object).
The problem is that I can access the array by its index only inside the function (console.log(requestors[0].ID);) AND I need it accessible outside the function so I can modify / use it.
What's the wrong thing I am doing?
Thanks a lot!
var requestors  = [];

class Requestor {
    constructor(ID, RequestorName, RequestorSurname, RequestorGivenname, RequestorUID, RequestorEmail, Location, Department) {
        this.ID = ID;
        this.RequestorName = RequestorName;
        this.RequestorSurname = RequestorSurname;
        this.RequestorGivenname = RequestorGivenname;
        this.RequestorUID = RequestorUID;
        this.RequestorEmail = RequestorEmail;
        this.Location = Location;
        this.Department = Department;
    }
}

$(document).ready(function() {
    $.ajax({
        type: "GET",
        url: "./app/csv/requestors.csv",
        dataType: "text",
        success: function(data) {
            processRequestors(data);
        }
     });
});

var h = 0;
function processRequestors(allRequestorsEntries) {
    var allRequestorsRows = allRequestorsEntries.split(/\r\n|\n/);
    var headers = allRequestorsRows[0].split(',');

    for (var i = 1; i < allRequestorsRows.length; i ++) {
        var data = allRequestorsRows[i].split(',');
        if (data.length === headers.length) {
            requestors[h] = new Requestor();
            for (var j = 0; j < headers.length; j ++) {
                requestors[h][headers[j]] = data[j];
            }
            h ++;
        }
    }

    console.log(requestors[0].RequestorName); // value
}

console.log(requestors[0].RequestorName); // undefined


text:
Q: Two rails models both with a habtm relationship to a third model I have a question about has and belongs to many when it applies to multiple models.  I've seen a couple other similar questions about habtm with multiple models but none quite like this (they usually apply to two models, not three).
Suppose I have The following classes:

*

*Students

*Clubs

*Rooms

Students habtm Clubs--Students can join multiple Clubs and Clubs have multiple Students.
Rooms habtm Clubs--a Room may have multiple Clubs that use it and a Club may use multiple Rooms.
There is no direct relationship between Students and Rooms.
I don't see any issue with using two habtm relationships in the same class (the Club class), but there may be subtleties that I'm missing.
class Student < ActiveRecord::Base
  has_and_belongs_to_many :clubs
end

class Clubs < ActiveRecord::Base
  has_and_belongs_to_many :students
  has_and_belongs_to_many :rooms
end

class Rooms < ActiveRecord::Base
  has_and_belongs_to_many :clubs
end

I assume in such a case I can also use :through on one or both of the relationships.

*

*Are there any known issues?

*Is there some other pattern in Rails I should use instead that I'm not thinking of?

A: What you've posted is the correct and optimal design for this.
There's no similarities between room and student so a polymorphic isnt suitable and the relationships are right.


text:
Q: Div not showing on image hover I've got a div wrapped in another div and this div has to show up when hovered on the image. But the thing is that when an image is placed (img src) in that div container the div won't show anymore on hover.. I don't know how to fix this, and I don't understand why it does work for the other div.
This is my html code:

Khumba(2013)

 Watch trailer // more info

Here's the fiddle: http://jsfiddle.net/ffXX9/
(the heart icon won't show up on hover when an image is placed in that div..)

A: You need to reposition the div
EXAMPLE http://jsfiddle.net/ffXX9/2/

PPPOOOOPPP (YEAR)


text:
Q: Tableview update 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows? Yes there are so many question ask on stack overflow on similar title of question. I read those all but i never see my problem equivalent to them.
Now my problem is if when i update table section 0 having 3 rows on click of headerview on section 0 and then again i click on same header for delete all 3 rows from the section 0, this work fine with me. But if i open(update section 0 with 3 rows) and then i click on another header section (another section i want to open then after 0th section) my application crashed. I mean i want to if i click other section then my other section should have open and previous open section should have to close. see my code for insertion and deletion sections and rows,
 -(void)sectionHeaderView:(TableHeaderView*)sectionHeaderView sectionOpened:(NSInteger)section{

self.sectionOpen = YES;
//Create an array containing data of rows and section which to be inserted in tableView.
NSMutableArray *dataInsertArray = [NSMutableArray arrayWithArray:[self.tableDataSourceDictionary objectForKey: [self.sortedKeys objectAtIndex:section]]];
NSInteger countOfRowsToInsert = [dataInsertArray count];

NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
    [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:section]];
}
[self.tableContents setObject:dataInsertArray forKey:[self.sortedKeys objectAtIndex:section]];

//Create an array containing data of rows and section which to be delete from tableView.
NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
NSInteger previousOpenSectionIndex = self.openSectionIndex;
if (previousOpenSectionIndex != NSNotFound )  {

    self.sectionOpen = NO;
    [previousTableHeader toggleOpenWithUserAction:NO];
    NSInteger countOfRowsToDelete = [[self.tableContents objectForKey: [self.sortedKeys objectAtIndex:section]] count];
    for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
        [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex]];
    }

    [self.tableContents removeObjectForKey:[self.sortedKeys objectAtIndex:previousOpenSectionIndex]];
}

// Apply the updates.
[self.tableView beginUpdates];
[self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationFade];
[self.tableView endUpdates];

self.openSectionIndex = section;
self.previousTableHeader = sectionHeaderView;
}

And my data-source methods,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
NSInteger numberOfSection = [self.sortedKeys count];
return numberOfSection;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *listData =[self.tableContents objectForKey: [self.sortedKeys objectAtIndex:section]];
NSInteger numberOfRows = [listData count];
return numberOfRows;
}

My crash report,
Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2372/UITableView.m:1070
2013-02-18 11:44:49.343 ManageId[1029:c07]  Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (0) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'
Simply  Suppose my 2 sections has contain 3 - 3 rows then it will worked file But if 2 sections contain 3 - 2 rows then it crash. I want to toggle two sections click on updating header of section with inconsistent numbers of rows in those sections.
Than

A: I found that please replace that code in your code with that code. you have to delete data with old one index not with current one....
the commented line was yours please check that...
if (previousOpenSectionIndex != NSNotFound){
 self.sectionOpen = NO;
 [previousTableHeader toggleOpenWithUserAction:NO];

//NSInteger countOfRowsToDelete = [[self.tableContents objectForKey: [self.sortedKeys objectAtIndex:section]] count];
NSInteger countOfRowsToDelete = [[self.tableContents objectForKey: [self.sortedKeys objectAtIndex:previousOpenSectionIndex]] count];

for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
[indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex]];
 }

[[self.tableContents objectForKey: [self.sortedKeys objectAtIndex:previousOpenSectionIndex]] removeAllObjects];
}