text:
Q: Go Daddy's intermediate CA certificate missing An unaffected PC (Windows 10 Pro connected to AD DS domain)

Affected PCs (Windows 10 Pro standalones)

What could cause intermediate but not root CA certificates to be missing?
I've verified that local policy Computer Configuration\Administrative Templates\System\Internet Communication Management\Internet Communication settings\Turn off Automatic Root Certificates Update isn't configured.
I've verified that Windows service Cryptographic Services / CryptSvc is running and restarting it didn't make a difference.
I've found that no relevant events are logged, as far as I can see.
https://support.microsoft.com/en-gb/help/3004394/support-for-urgent-trusted-root-updates-for-windows-root-certificate-p says:

The Windows Root Certificate Program enables trusted root certificates
  to be distributed automatically in Windows. Usually, a client computer
  polls root certificate updates one time a week.

How do you manually force an update?

A: A server providing a TLS/SSL connection (as in a HTTPS web-server) should send the client all certificates in the chain.  That is, the end-entity certificate, all subordinate CAs and optionally (but not mandatory) the Root CA certificate.
Your so called Affected PCs are showing the symptom of a web-server that has been misconfigured and is simply sending the end-entity certificate.  Your browser gets this certificate and has no way to chain it to the Root CA that's installed in your trust-anchor store.
Your Unaffected PC is showing the symptom of a Windows computer which conveniently has the subordinate CA certificates cached in its certificate store.  These are usually placed there when a user browses to another website which uses the same subordinate CAs but whose administrator knows what they are doing :-)  The PC is still only receiving the end-entity certificate from the server, but as it has the subordinate CAs certificates cached, it can join them together and build the chain.
Now, Windows has a facility to download any subordinate CAs from a repository, but this will only work if (a) the URL of this repository is contained within the certificate, (b) the certificate is actually installed on that repository, and (c) the repository is online and accessible.
To resolve this, you need to have a stern word with the administrator of the website and tell them to read RFC 5246.  Specifically, section 7.4.2.


text:
Q: почему не решает уравнение? int main()
{
    setlocale(0,"");
    int a,b,c,x;
    int t = x^2;
    double x_1,x_2;
    cout<<"Введите значения :"<<endl;
    cin >> a;
    cin >> b;
    cin >> c;

    cout << "Значение а = " << a <<endl;
    cout << "Значение b = " << b << endl;
    cout << "Значение c = " << c << endl;

    int count = a*t^2 + b*t + c;
    double d = b^2 - 4*a*c;

    if (count >= 0 )
    {
        x_1 = (-b + sqrt(d)) / 2 * a;
        x_2 = (-b - sqrt(d)) / 2 * a;
        cout<<"Первый корень = "<<x_1<<endl;
        cout<<"Второй корень = "<<x_2<<endl;
    }
    else {
        cout<<"Корней нет!";
        cout << "А не должно быть равно нулю!";
    }

    system("pause");
    return 0;
}

A: int t = x^2;

Предположим, есть такой оператор "шапочка" :-), который возводит число в степень. Чему равно t после этой строчки?
https://www.tutorialspoint.com/cprogramming/c_operators.htm
Уберите из кода все строчки, где встречается переменная t. И измените проверку на
double d = b*b - 4*a*c;
if (d >= 0)
{
  x_1 = (-b + sqrt(d)) / (2 * a);
  x_2 = (-b - sqrt(d)) / (2 * a);
  ...

Update
Плюс, вычисление корней из x_1 и x_2 - как в ответе @SeniorPomidor.

A: это биквадратное уравнение. Имеет вид ax^4 + bx^2 + c, но мы будем использовать замену. пусть t=x^2.  тогда уравнение имеет вид at^2 + bt + c
#include <iostream>
#include <cmath>

using namespace std;
int main()
{
    setlocale(0,"");
    int a,b,c,x;
    double x_1,x_2;
    cout<<"Введите значения :"<<endl;
    cin >> a;
    cin >> b;
    cin >> c;

    cout << "Значение а = " << a <<endl;
    cout << "Значение b = " << b << endl;
    cout << "Значение c = " << c << endl;

    double d = b^2 - 4*a*c;

    if (count >= 0 )
    {
        x_1 = (-b + sqrt(d)) / 2 * a;
        x_2 = (-b - sqrt(d)) / 2 * a;
        // так как t может быть только положительным числом из-за t=x^2,
       //то нужно проверить, что корни не отризательные
        if(x_1 > 0){
            int root1 = sqrt(x_1);

            cout<<"Первый корень = "<<root1<<endl;
            cout<<"Второй корень = -"<<root1<<endl;
        }
        // и второй корень тоже
        if(x_2 > 0){
            int root1 = sqrt(x_2);

            cout<<"Третий корень = "<<root1<<endl;
            cout<<"4 корень = -"<<root1<<endl;
        }
    }
    else {
        cout<<"Корней нет!";
        cout << "А не должно быть равно нулю!";
    }

    return 0;
}

A: ^ — это побитовое исключающее или. Для возведения в степень используйте std::pow() из заголовочного файла <cmath>:
int t = std::pow(x, 2);

Но ещё лучшим решением, раз у вас целые числа, будет замена возведения в квадрат на умножение числа самого на себя:
int t = x * x;

Это будет быстрее по времени вычисления, а также не приведёт к потере точности при больших числах.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark + Kafka app, getting "ClassNotFoundException: Failed to find data source: org.apache.spark.sql.cassandra" Solved Link(but have the other bug haha... )
spark stream cassandra, pyspark JNR is excluded from the classpath
Python | spark  |  kafka  | Cassandra
3.6.8  | 3.1.2  |  2.8.1  | [cqlsh 5.0.1 | Cassandra 3.0.8 | CQL spec 3.3.1 | Native protocol v4]
run code
spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.2 test.py

I succeeded in reading kafka topic with spark stream. So I tried to write the read topic to cassandra with writeStream, but it didn't work.
my code is on a different IP than the spark master IP.
this image is my Stream structor
ps. cassandra place masterIp
enter image description here
my code
from pyspark.sql import SparkSession

while True:
    # Spark Bridge local to master == Connect master
    spark = SparkSession.builder \
        .master("spark://masterIp:7077") \
        .appName("Spark_Streaming+kafka+cassandra") \
        .getOrCreate()

    # Read Stream From test0003 at BootStrap
    df = spark.readStream \
      .format("kafka") \
      .option("kafka.bootstrap.servers", "DBip:9092") \
      .option('startingOffsets','earliest') \
      .option('failOnDataLoss','False') \
      .option("subscribe", "test0003") \
      .load()

    df.printSchema()

    # write Stream at cassandra
    ds = df \
      .writeStream \
      .trigger(processingTime='15 seconds') \
      .format("org.apache.spark.sql.cassandra") \
      .outputMode('append') \
      .option("checkpointLocation","./kafka") \
      .option("kafka.bootstrap.servers", "master_Ip:9092") \
      .option("keyspace","testkey") \
      .option("table","testtable") \
      .start()

    break

error
I saw Traceback so checked my table, but i have testtable.
Traceback (most recent call last):
  File "./test.py", line 30, in <module>
    .option("table","testtable") \
  File "./venv/lib64/python3.6/site-packages/pyspark/python/lib/pyspark.zip/pyspark/sql/streaming.py", line 1202, in start
  File "./venv/lib64/python3.6/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/java_gateway.py", line 1322, in __call__
  File "./venv/lib64/python3.6/site-packages/pyspark/python/lib/pyspark.zip/pyspark/sql/utils.py", line 111, in deco
  File "./venv/lib64/python3.6/site-packages/pyspark/python/lib/py4j-0.10.9.5-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JJavaError: An error occurred while calling o47.start.
: java.lang.ClassNotFoundException:
Failed to find data source: org.apache.spark.sql.cassandra. Please find packages at

i reference this code
Writing Spark streaming PySpark dataframe to Cassandra overwrites table instead of appending
if you feel this post unkind and foolish, sorry. i am 1month junior developer and this post my first post on stackoverflow


text:
Q: if statement to determine String or Integer from Scanner(System.in) Is it possible to implement the commented lines in order to distinguish between an Integer and a String when a user inputs said value into the console?  The code works with the rest of my program, but I want the user to be able to input the Employee ID (an int) in addition to name and/or address.
public void query(){

    String newValue;

    System.out.println("Please enter the name, address, or employee "
            + "ID you are looking for");
    Scanner input = new Scanner(System.in);
    //if (Integer.parseInt(input);
        //newValue = input.nextInt();
    //else
    newValue = input.nextLine();
    input.close();

    if (name.equals(newValue) | address.equals(newValue) )
        System.out.println(toString());
    else System.out.println("There is no employee with that name, address, or ID");

}

A: Yes, you can do that using isNumeric and isAlpha methods of StringUtils class from Apache Commons library.


text:
Q: IE7-9 testing workflow on a Mac I'm at my wits end right now trying to get a website working in IE7-9, the issue I'm having is getting text-shadow to appear in a decent matter. I've been using the 960 grid system so changes are very minimum, I've been checking changes with IE Netrender. However lately IE Netrender has been having issues so I can't test the layout in a timely fashion.
I did have VM Ware set up but I'm really tired of reactivating my Windows copy and installing a separate image for each version of the browser. I don't have Windows 7 for IE9 as well. I'm looking for a free option. I've tried searching but everything seems outdated.
So my question is, how does everyone test their site for IE7-9?

A: The IE Developer Tools let you set IE7 and IE8 modes on IE9, so you can get 98% testing with one version.
There are some issues that don't crop up there though, so its a good idea to do a quick real browser check at the end.
MS has free VMs you can download with the different versions of IE on them. I'm not sure if you can run them on a Mac though.
http://www.microsoft.com/download/en/details.aspx?id=11575

A: By having a Windows license. Perhaps not the answer you're looking for, but there's no such thing as a free meal. The only truly guaranteed method of testing a site in Internet Explorer is to actually use it in Internet Explorer, be it in a virtual machine or on a real PC. Spoon used to have an Internet Explorer virtualization web app, but that has since been removed at Microsoft's behest.


text:
Q: Out of Memory Error in OpenJDK Docker Container I built a Docker container for my JBoss application. Container ran in AWS EKS Fargate. I found that an OutOfMemory error occurred after the application ran for several minutes. However, it would be fine if the root user is used rather than the created user.
My Dockerfile:
FROM openjdk:8u342-oraclelinux8

ENV WILDFLY_VERSION 11.0.0.Final
ENV JBOSS_HOME /usr/local/jboss_api
ENV HOME /usr/local

RUN groupadd -r jboss && useradd -ms /bin/bash -l -r -g  jboss jboss \
    && chown jboss /usr/local

USER jboss

WORKDIR ${HOME}
COPY ./wildfly .
RUN tar -xvf wildfly-$WILDFLY_VERSION.tar.gz
RUN rm ./wildfly-$WILDFLY_VERSION.tar.gz
RUN mv ./wildfly-$WILDFLY_VERSION ./jboss_api \
    && mkdir ${JBOSS_HOME}/standalone/configuration/properties

WORKDIR ${JBOSS_HOME}
COPY ./script ./bin
COPY ./properties ./standalone/configuration
COPY ./configurations/standalone.conf ./bin/standalone.conf

COPY ./ROOT.war ./standalone/deployments/ROOT.war

WORKDIR ${JBOSS_HOME}
CMD ./bin/server.sh start

I figured out there is a memory issue for JVM. Therefore -Xmx2500m is set in java config.
-XX:+UnlockExperimentalVMOptions and -XX:+UseCGroupMemoryLimitForHeap are also added by reading some reference articles but the problem still cannot be solved.
Does anyone have an idea about this?


text:
Q: Why can't my Java functional interface modify its Integer input? EDIT 1: I am aware this question has been marked as a duplicate and I initially deleted it.  However, after reading in this Meta Post that deleting is bad and that I should edit my question rather than deleting it, I undeleted and am trying to improve the question for anyone else who might have the same issue I did.
After the post marked as "already answered" linked to something I already knew (and a post I've read often) but didn't represent my question/confusion, I tried to expand my test case and realized my problem was not in knowing about references, but rather misunderstanding of how autoboxing worked and the relationship between an Integer reference and its (immutable) value.  See edit below the original question which demonstrates what my confusion was.
Original Question:
I'm still trying to learn how to leverage Java 8+ lambda functional interfaces.  While I know it's not necessarily a best practice to modify a parameter passed to a method, I am not sure why the input value to a lambda expression, modified within the expression, is not modified.
Here's an example program which I would expect to modify the value of its input (t) to the value 42:
import java.util.function.Consumer;

public class Main {
    static Consumer<Integer> foo = n -> {
        n = 42;
    };

    public static void main(String... args) {
        Integer t = 0;
        foo.accept(t);
        System.out.println("Why is " + t + " not equal to 42?");
    }
}

Output:

Why is 0 not equal to 42?

EDIT 2:
As has been pointed out by the first commenter, the problem was trying to reassign the parameter (an immutable Integer container).  I wasn't really trying to change the reference of the Integer, I was trying to change the boxed value and assumed that Java would do that for me automagically.  I was wrong.
Below, I have modified the earlier code to demonstrate what I thought would happen and what I was expecting.  While the marked duplicate about "pass by value" is related and one of several associated issues, it was not the source of my confusion.  It was ultimately my misunderstanding of how autoboxing works (creating a new object, rather than modifying the boxed value of the existing object) that was the root of my issue.
import java.util.function.Consumer;

public class Main {
    /**
     * How I thought {@link Integer} worked, not how it works.
     */
    class BoxedInt {
        int boxed;

        BoxedInt(int i) {
            box(i);
        }

        void box(int i) {
            this.boxed = i;
        }

        int unbox() {
            return boxed;
        }

        public String toString() {
            return String.valueOf(unbox());
        }
    }

    static Consumer<BoxedInt> foo = n -> {
        n.box(42); // what I thought happened with n = 42
    };

    public static void main(String... args) {
        BoxedInt t = new Main().new BoxedInt(0);
        foo.accept(t);
        System.out.println("See how " + t + " is equal to 42.");
    }
}

Result:

See how 42 is equal to 42.


text:
Q: Laravel 5.3 Pagination - ErrorException in Collection.php line 432 Every time I try to setup my pagination:

Missing argument 1 for Illuminate\Support\Collection::get()

My controller:
public function index()
{
    $products = DB::table('products')
        ->where('product_group_id', '=', 1)
        ->paginate(15)
        ->get();

    return view('product.index', [
        'products' => $products,
    ]);
}

My view:
{{ $products->links() }}

What goes wrong here?

A: You don't need ->get() here. ->paginate() gets your records from the database and returns a collection of those 15 items.
When you're running ->get() here you're attempting to run it on the collection that is returned which expects a $key and is used to get a specific item out of a collection.
You should do this:
$products = DB::table('products')
    ->where('product_group_id', '=', 1)
    ->paginate(15);

return view('product.index', [
    'products' => $products,
]);

or with Eloquent
$product = Product::where('product_group_id', '=', 1)
    ->paginate(15);

return view('product.index', [
    'products' => $products,
]);

Note: I have put the filters before the paginate() call to ensure that the where clause is part of the database query rather than trying to filter the resulting collection/paginator

A: When you call the paginate() method on a Illuminate\Database\Query\Builder object, You will get an instance of \Illuminate\Pagination\LengthAwarePaginator. That itself does not have a get()-Method, but the Illuminate\Pagination\AbstractPaginator it extends has a magic __call() function which forwards the call to the underlying Collection.
Now, Illuminate\Support\Collection does have a get() method, but it takes the key of the element you want to get out of the Collection as an argument, hence the error you get.
Now, I suppose what you actually want to achieve standard pagination with links for page numbers and "forward" and "back" buttons. If so, you should just stick to the documentation: Get the data just the way you did, just leave out the get(), then display it in a view the way its shown here.
EDIT: Just read about the Method links does not exist error you get. That is indeed strange. Builder::paginate() definitely returns an Instance of LengthAwarePaginator which itself definitely has a links() method.
Is there perhaps some more code that is relevant to this problem which you havent shown us yet? Maybe in your view?


text: Q: Not able to find tabletogrid function inJQ grid version 5.0.2 We are currently using JQ grid version 4.1.2 in our application, however we are upgrading JQ grid version from 4.1.2 to 5.0.2 version, we are not able to find tabletogrid function in version 5.0.2. Can anyone help us any alternative tabletogrid function in JQ grid version 5.0.2.


text:
Q: jQuery .val() return empty string I am trying to sum the values of a column table, each time it gets updated. So for that I have this function, that gets executed each time the table inserts or deletes a row, but for now, it's just sending the value to the console:
function update_price(){
  $("#table-content tr td:nth-child(3)").each(function() {
    console.log($(this).find("div").val());
  });
}

The HTML code associated with it looks like this:

        9789898818386
        Fale Menos, Comunique Mais

                <input type="number" data-number-to-fixed="2" data-number-stepfactor="1" class="auto form-control price" value="12" step=".01">

        2

     ...

For some odd reason, when I use .html() instead of .val(), it returns me the HTML code for the user input, but the same doesn't happen when I use .val().
Please let me know if you have any suggestion, maybe I'm doing something wrong and I didn't checked yet.
Thanks,
mikeysantana

A: you need to swap $(this).find("div").text() with $(this).find("div input").val();
The div actually don't contain any text, even though the input is inside it. So you have to target the input to get the value
demo

function update_price() {
  $("#table-content tr td:nth-child(3)").each(function() {
    console.log($(this).find("div input").val());
  });
}

update_price();

      9789898818386
      Fale Menos, Comunique Mais

<input type="number" data-number-to-fixed="2" data-number-stepfactor="1" class="auto form-control price" value="12" step=".01">

      2

    ...

A: Val() is used for html form elements.  Use text() instead for non form elements.


text:
Q: Where to start for understanding databases internals? Q: Where to start for understanding databases internals? And developing a (simple) database?
Note: STSDb has a fascinating performance as an embedded database. I took a look on the source but I can't get it (so far). So I thought starting to understanding database internals by implementing a little one would bu helpful. So what books (tutorials, essays, ...) would help for this?
Thank you

A: Go to SQLite to learn this because it is a darn useful tool, includes SQL as well as the core database functionality, and source code is available. There is also a nice book called The Definitive Guide to SQLite which has a nice chapter on internals. Just follow the link to the book to preview that chapter.

A: In his book An Introduction to Database Systems, 7th ed., Chris Date recommends The Ingres Papers: Anatomy of a Relational Database System.

A: I am not sure what you will learn about STSdb from books or implementing your own since STSdb's own marketing materiel states:

It provides intuitive use, blazing performance and brand new database techniques.

... and there is no 'one' database technology or structure.  There is certainly a distinction between traditional relational databases and object oriented databases which is what STSdb is.
It goes on to say

Supports different storage modes (on-disk, in-memory and combined).

I suspect that that is the primary reason for its apparent performance; the use of in-memory data storage.  Performance is likely related to available memory and database size.  Looking at their comparative tests, the 10M record data base was only 430Mb, so can be entirely in-memory on the 2Gb test platform they used.  That, and tight coupling with the application (that is where the term 'embeddded' applies), are probably the biggest factors in its relative performance.


text:
Q: How can I only give text to a label once a data request is complete? I tried using a closure since it seemed like the obvious choice but I'm still having a problem with this. Basically I have the user login with Facebook, and once they have an access token, their data is fetched (just name and email). I have two labels in my view that I want to display their name and email.
EDIT: After Matt's suggestion:
// Get user info
func getUserInfo(finished: @escaping () -> Void) {
    let params = ["fields" : "email, name"]
    let graphRequest = GraphRequest(graphPath: "me", parameters: params)
    graphRequest.start {
        (urlResponse, requestResult) in
        DispatchQueue.main.async {

        switch requestResult {
        case .failed(let error):
            print("error in graph request:", error)
            break
        case .success(let graphResponse):
            if let responseDictionary = graphResponse.dictionaryValue {
                print(responseDictionary)

                if let name = responseDictionary["name"] {
                    self.nameLabel.text = "Logged in as: \n\(name)"
                }

                if let email = responseDictionary["email"] {
                    self.emailLabel.text = "Your email is: \n\(email)"
                } else {
                    self.emailLabel.text = "Your email is: "
                }
                print(responseDictionary["name"])
                print(responseDictionary["email"])
            }
        }
            finished()
        }

    }

}

And in viewDidLoad
    if AccessToken.current != nil {
        getUserInfo {
            self.view.addSubview(self.emailLabel)
            self.view.addSubview(self.nameLabel)
            self.setupNameLabel()
            self.setupEmailLabel()
        }

    }

Initializing the labels
let emailLabel: UILabel = {
    let frame = CGRect(x: 100, y: 100, width: 400, height: 200)
    let label = UILabel(frame: frame)
    label.textAlignment = NSTextAlignment.center
    label.text = ""
    label.numberOfLines = 2
    label.textColor = UIColor.black
    label.translatesAutoresizingMaskIntoConstraints = false

    return label
}()

let nameLabel: UILabel = {
    let frame = CGRect(x: 100, y: 100, width: 400, height: 200)
    let nLabel = UILabel(frame: frame)
    nLabel.textAlignment = NSTextAlignment.center
    nLabel.text = ""
    nLabel.numberOfLines = 2
    nLabel.textColor = UIColor.black
    nLabel.translatesAutoresizingMaskIntoConstraints = false

    return nLabel
}()

Constraints for the labels
func setupEmailLabel() {
    emailLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    emailLabel.topAnchor.constraint(equalTo: nameLabel.bottomAnchor, constant: 30).isActive = true
    emailLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
    emailLabel.heightAnchor.constraint(equalToConstant: 73).isActive = true
}

func setupNameLabel() {
    nameLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    nameLabel.topAnchor.constraint(equalTo: facebookShareButton.topAnchor, constant: -230).isActive = true
    nameLabel.widthAnchor.constraint(equalToConstant: 150).isActive = true
    nameLabel.heightAnchor.constraint(equalToConstant: 73).isActive = true
}

A: The only problems with what you're doing are:

*

*that you are not calling finished() in the completion handler, and

*that you are failing to make sure you're on the main thread.
So, it's easy to fix. You have this:
graphRequest.start {
    (urlResponse, requestResult) in
    // ... your stuff (switch statement)
}
finished()

Change it to this:
graphRequest.start {
    (urlResponse, requestResult) in
    DispatchQueue.main.async {
        // ... your stuff (switch statement)
        finished()
    }
}


text:
Q: How can I authenticate Vertx MongoClient to a docker with Mongodb and Restheart? Error code 13 I'm studying the Vertx MongoClient API. I previously installed Restheart from Docker and it's own copy of mongodb, so now I have the default configuration for Restheart and the default configuration of Mongo in docker-compose.yml:
        MONGO_INITDB_ROOT_USERNAME: restheart
        MONGO_INITDB_ROOT_PASSWORD: R3ste4rt!

I put the Vertx Mongoclient into a Verticle:
public class MongoClientVerticle extends AbstractVerticle {
    MongoClient mongoClient;
    String db = "monica";
    String collection = "sessions";
    String uri = "mongodb://localhost:27017";
    String username = "admin";
    String password = "password";
    MongoAuth authProvider;

    @Override
    public void start() throws Exception {

        JsonObject config = Vertx.currentContext().config();

        JsonObject mongoconfig = new JsonObject()
                .put("connection_string", uri)
                .put("db_name", db);

        mongoClient = MongoClient.createShared(vertx, mongoconfig);
        JsonObject authProperties = new JsonObject();
        authProvider = MongoAuth.create(mongoClient, authProperties);
//        authProvider.setHashAlgorithm(HashAlgorithm.SHA512);
        JsonObject authInfo = new JsonObject()
                .put("username", username)
                .put("password", password);
        authProvider.authenticate(authInfo, res -> {
            if (res.succeeded()) {
                User user = res.result();
                System.out.println("User " + user.principal() + " is now authenticated");
            } else {
                res.cause().printStackTrace();
            }
        });
    }

and I built a simple query:
public void find(int limit) {
    JsonObject query = new JsonObject();
    FindOptions options = new FindOptions();
    options.setLimit(1000);
    mongoClient.findWithOptions(collection, query, options, res -> {
        if (res.succeeded()) {
            List<JsonObject> result = res.result();
            result.forEach(System.out::println);
        } else {
            res.cause().printStackTrace();
        }
    });
}

but when I access the db I get this error:
MongoQueryException: Query failed with error code 13 and error message 'there are no users authenticated' on server localhost:27017
What am I missing in the authentication process?
I'm using lastest restheart + mongodb and vertx 3.5.3

A: To be clear, RESTHeart doesn't come with its own copy of Mongodb but connects to any existing instance of Mongodb. The instance you can start via docker compose is for demo purposes only.
This question is much related to Vertx + Mongodb. I'm not an expert of it, but apparently Vert.x Auth Mongo does not use database accounts to authenticate users, it uses a specific collection (by default the "user" collection). You could double check the Vertx docs in case to be sure about this.
However, note that RESTHeart's main purpose is to provide direct HTTP access to Mongodb, without the need to program any specific client or driver. So the side point is that if you are using Vertx then you presumably don't need RESTHeart, and vice versa. Otherwise, you could simply connect to RESTHeart via Vertx's HTTP client, entirely skipping the MongoClient API.


text:
Q: Linked Lists Append To Tail I am trying to create an appendToTail function which will add a node to the end of a singly linked list.
I am having trouble in adding a node if the head is NULL(the linked list is empty)
class Node {
private:
    Node* next;
    int data;

public:
    Node(int d, Node* n = NULL)
        : data(d)
        , next(n)
    {
    }
    void appendToTail(int);
    //other trivial functions(getters and setters etc. ) defined and
    //declared
};

void Node::appendToTail(int d)
{
    Node* end = new Node(d);

    Node* n = this;

    if (n == NULL)
        n = end;

    else {
        while (n->next != NULL)
            n = n->next;
        n->next = end;
        n->next->next = NULL;
    }

    end = NULL;
    delete end;
}

int main()
{
    Node* n = NULL;
    n->appendToTail(5);
    std::cout << n->getData(); //getData() is a function which
    //retrieves the Data member variable
}

I am expecting to get 5 but I am getting an error which appears to be caused because my node remains null.

A: Now with modern C++ idioms we use smart pointers instead of raw pointers, it gives you the benefit of RAII (Resource acquisition is initialization) mechanism. In addition if you want an elegant solution to your problem you should introduce a List class with which you can express more clearly the concept of an empty list. It would give something like this:
#include <memory>
#include <iostream>

class List
{
public:
    class Node
    {
    private:
        std::shared_ptr<Node> next;
        int data;
    public:
        Node(int d):next(nullptr),data(d){}
        inline int getData() const {return data;}
        inline std::shared_ptr<Node> getNext() const {return next;}

        friend List;
    };
    List():head(nullptr),tail(nullptr){}

    void appendToTail(int );

    inline std::shared_ptr<Node> getHead() const {return head;}
    inline std::shared_ptr<Node> getTail() const {return tail;}
private:
    std::shared_ptr<Node>   head;
    std::shared_ptr<Node>   tail;
};

void List::appendToTail(int d)
{
    auto newTail = std::make_shared<Node>(d);

    if (head == nullptr)
    {
        head = tail = newTail;
    }
    else
    {
        tail->next = newTail;
        tail = newTail;
    }
}

int main()
{
    List    l;
    l.appendToTail(5);
    std::cout<<l.getHead()->getData();
}

But you should definitely prefer std::list<T> or std::vector<T>.

A: Unfortunately there several errors with your approach. Semantic errors and a logical error with your interpretation of a linked list. Let's start with your initial misunderstanding. You cannot add a new tail to an empty list. Because it is emtpy. Meaning, not yet existing. Only if some object is existing/instantiated you can add a tail. You cannot add something to not existing stuff. So your idea to start with a Node* n = nullptr cannot work logically.
Additionally you are dereferencing a nullptr (major bug). That is also the main problem of your code. Nothing works. You need an instantiated object, before you can call it's member functions.
So before you can populate the list, you need to create/instantiate it initially. So you need to explicitly create the first node in your main function with
 Node* n = new Node (5)

Then the list is existing and from now on you can add new members with calling appendToTail.
There are more semantic errors in your code which have luckily no side effects.
You must not delete the 'end' variable in your function. You want to keep the newly allocated memory for the new tail. But you introduced an additional sematic error by setting 'end' to nullptr and then call delete. Deleting a nullptr is a noOp and will do nothing. So, although you have a semantic error, this will not cause any trouble.
There is more:
For a pointer to Null you should always use nullptr.
And, your
if (n == NULL)

is always false. Before that, you assigned this to n. This is never NULL. You can delete the if else. Keep the statements from the else, except the
n->next->next = NULL;

That's not necessary. The constructor did that already for you. As explained, the next 2 statements should also be elimanted.
Additionally you may want to read a little more on the concept of linked lists.
I hope I could help a little


text:
Q: Azure REST WebClient PUT Blob I'm trying to simply upload a new blob to an Azure Storage countainer using WebClient like this :
var sas = "[a new generated sas with Read, Write, List & Delete permissions]";
var sData = "This is a test!";
var sEndPoint = "http://myaccount.blob.core.windows.net/mycontainer/MyTest.txt" + sas;

var clt = new WebClient();
var res = await clt.UploadStringTaskAsync(sEndPoint, "PUT", sData);

This is giving me a "(400) Bad Request." error.  Am I doing anything wrong here?
Thanks
(By the way, I need to use REST instead of Client API since I'm in a Silverlight project)

A: You would need to define a request header (x-ms-blob-type) for blob type and set it's value to BlockBlob. Also for Put requests you would need to define the Content-Length request header as well. I wrote a blog post on Shared Access Signatures and performing some blob operations using that (with both REST API and Storage Client library) which you can read here: http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/.
and here's the code from that post on uploading blob. It uses HttpWebRequest/HttpWebResponse instead of WebClient:
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
    string blobName = "sample.txt";
    string sampleContent = "This is sample text.";
    int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
    string queryString = (new Uri(blobContainerSasUri)).Query;
    string blobContainerUri = blobContainerSasUri.Substring(0, blobContainerSasUri.Length - queryString.Length);
    string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
    request.Method = "PUT";
    request.Headers.Add("x-ms-blob-type", "BlockBlob");
    request.ContentLength = contentLength;
    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
    }
    using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
    {

    }
}

A: When testing against the blob emulator this is the code I need to get it working:
        var connection = ConfigurationManager.AppSettings["AzureStorageConnectionString"];
        var storageAccount = CloudStorageAccount.Parse(connection);

        var client = new WebClient();
        client.Headers.Add("x-ms-blob-type", "BlockBlob");
        client.Headers.Add("x-ms-version", "2012-02-12");
        client.UploadData(string.Format(@"{0}/$root/{1}{2}", storageAccount.BlobEndpoint, myFileName, sharedAccessSignature), "PUT", _content);


text:
Q: SpriteKit: Howto make holes in layer with blendMode I have a simple scene with some elements added to it.
Now i want focus on a specific element with a mask a cut a whole at the same position as the element I want to focus on. Very similar to what we can see on some games when they are started first time showing some kind of tutorial.
Basically I am adding a fullscreen layer with alpha=0.7 (so user still see all the content) but then add a circle at a specific position as this layers child and set blendMode=. Subtract so it "cuts" out a circle from this fullscreen layer so within this circle you have a clear view.
I have the following code after I have added all the elements onto the screen.
// before this code i added some basic elements like circles and backgrounds
let mask = SKSpriteNode(color: .blackColor(), size: self._screenSize)
mask.anchorPoint = CGPoint.zero
mask.position = CGPoint.zero
mask.zPosition = 100
mask.alpha = 0.7

let circle = SKShapeNode(circleOfRadius: Constants.Config.playersize*2)
circle.fillColor = .blackColor()
circle.lineWidth = 0
let circle_mask = SKSpriteNode(texture: SKView().textureFromNode(circle, crop: circle.frame))
circle_mask.blendMode = .Subtract
circle_mask.zPosition = 101

// now show the layer with alpha=0.7 and the circle mask being at the same position as my player element i want to focus on
mask.addChild(circle_mask)
circle_mask.position = player.position
self.addChild(mask)

But this simply adds the fullscreen layer, no circle holes. Looks like it is ignoring the circle_mask node. What am I doing wrong?
My plan is also to keep moving the circle mask to focus on other elements on this scene. As I understand. Subtract it should subtract only from its parent node, which is the fullscreen layer with alpa=0.7, right?
I just tried with SKCropNode. Added the fullscreen layer as a child into the crop node, then assigned the circle as mask. But now its cutting out nearly everything but just showing a circle of my fullscreen layer, i actually need the inverted result of this crop node.
The problem with blendMode is that is runs it on the final framebuffer, but what i need is to run it on the parent node only, so it does not cut everything behind the node when using .Subtract

A: Here is an example on how to create a translucent layer with a hole punched into it:
-(NOTE: .subtract blend mode does not take alpha of the sprite into consideration, so you need to use a crop node)
self.backgroundColor = .red

//Our transparent overlay
let fullScreen = SKSpriteNode(color: .black, size: self.size)
fullScreen.position = CGPoint.zero
fullScreen.zPosition = 100
fullScreen.alpha = 0.7

//let's make a mask to punch circles in our shape
let mask = SKSpriteNode(color: .white, size: self.size)
mask.position = CGPoint.zero
mask.zPosition = 100
mask.alpha = 1

let circle = SKShapeNode(circleOfRadius: 20*2)
circle.fillColor = .white
circle.lineWidth = 0
circle.alpha = 1

//let circle_mask = SKSpriteNode()
circle.blendMode = .subtract
mask.addChild(circle)

//let's create the node to place on screen
let crop = SKCropNode()
crop.maskNode = mask
crop.addChild(fullScreen)

self.addChild(crop)


text:
Q: Run custom script in SQL Server Express I am trying to run a script on Task Scheduler to update a column in my database every 1 hour.
I have table vw_invoices and a column ExportLock with a default value of 0 which is "unlocked".
I want to run a query to update ExportLock to 1. Currently I am running
update Worldwide.dbo.vw_Invoices
set ExportLocked = 1

I really appreciate your help.

A: USE SQLCMD along with windows task scheduler to mimic SQL Agent on SQL Server Express:
sqlcmd
    -S <ComputerName>\<InstanceName>
    -i <c:\MyScript.sql>
    -o <c:myutput.txt

Keep the above in a notepad and save it as .BAT file and schedule through task scheduler

A:
I found what I was looking for and here is what I did worked great, I appreciate everyone's help


text:
Q: track users details in php website for security resasons i read in an article that we should track users about their ip, browser details, geolocations etc... to help prevent any threat in future and to handle the situation when our website is under attack.
.
Is it good practice to track user details and would it be ever useful to help prevent when my website is under attack using that tracked data, based on some algorithms? If yes, then what attributes or detais of users should i store for future.
.
The article also suggested to create log files on database updates to know when and what is happening on the website.
.
would anyOne please guide me or suggest me some tutorial link on the same.
waiting for your valuable response...
thanks for any reply.

A: I'd dare to say it's mostly useless for the following reasons:

*

*IP address - the attacker may be behind a proxy, may use VPN, Tor, may be in a wi-fi cafe or a lot of other options. You can't rely on that.

*Browser details - the User-agent he sends you may be absolutely anything. He can be on Firefox and pretend he's on Chrome. Or that he's a potato. Or a chromed potato. You can't rely on that either.

*Geolocation - most likely you will be able to track the location of his ISP, but for the reasons in point 1, again you can't rely on that.

*Logging these details for every user  and every request is going to be a headache if you've got a large amounts of traffic on your website.

Generally anyone who wants to do something bad and knows how to stay anonymous is going to stay anonymous, and you can't help that - deal with it and be careful when you write your code to minimize the possibility of anonymous guys doing bad things.
With this in mind, it's a good idea to look once or twice per month through your webserver's error log and check for unusual activity. If you've got cPanel running, AWStats is a good tool for that.
Cheers!


text:
Q: How to check if a file is corrupt? I have a loop that opens word documents however there are a few that are corrupted, I can't open them manually either,
The code I'm using to open is,
Set newdoc = objWord.Documents.Open(saveFolder & Filename)

This fails with the error

"Run-time error 5792, the file appears to be corrupted".

Is it possible to tell that the file is corrupt before trying to open it?

A: No, but you can test it while trying to open it.
On Error Resume Next ' deactivate error reporting
Set newdoc = Nothing
Set newdoc = objWord.Documents.Open(saveFolder & Filename)

' check if trying to open it produced an error
If Err.Number = 5792 Then
    Msgbox "'" & saveFolder & Filename & "' is corrupt."
    Err.Clear
End If

On Error Goto 0  ' re-activate error reporting. Do not forget this!

' if an error occured during opening then newdoc is nothing
If Not newdoc Is Nothing

    ' do what you want to do with the opened file

Else

    ' do what you want to do with a corrupt file

End If

A: your best bet here is to use error handling.
Something like
On Error GoTo skip
Set newdoc = objWord.Documents.Open(saveFolder & Filename)
On Error GoTo 0
Exit Function
skip:

A: In VBA it is best to keep errors to well defined functions (TryFunctions) that deal with one action and return true(no error)  or false(there was an error), and use a byref parameter to return the actual result.
Public Function TryOpenDoc(byVal ipPath as string, ByRef ipDoc as Word.Document) as Boolean

    On Error Resume Next
    set ipDoc = Application.Documents.Open(ipPath)
    TryOpenDoc = Err.Number = 0
    Err.Clear

End Function

This function could be then used as follows
If TryOpenDoc(saveFolder & Filename, newdoc) then

    <Code to process opened document>

Else

    ' raise an error, do a MsgBox or debug.print a message
    Debug.print "Could not open " & saveFolder & Filename"

End If

Although it is more common to use  'If Not Try....' so that you can deal with the error before continuing on the happy code path.


text:
Q: Biblatex: Two bibliographies with different styles and sortings II The answer of moewe to the question Biblatex: Two bibliographies with different styles and sortings is almost what I want to achieve. Because of the large number of entries in my document, I would prefer to use the style numeric-comp instead of just numeric. How can I get this?

Extended MWE:
\documentclass{article}

\usepackage{filecontents}

\begin{filecontents}{biblatextest1.bib}
@BOOK{BookA03,
  author    = {Author Aaa},
  title     = {Some Title},
  publisher = {Some Publisher},
  year      = 2003,
}
@BOOK{BookB02,
  author    = {Author Bbb},
  title     = {Some Title},
  publisher = {Some Publisher},
  year      = 2002,
}
@BOOK{BookB09,
    author    = {Author Jjj},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
@BOOK{BookB10,
    author    = {Author Kkk},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
@BOOK{BookB11,
    author    = {Author Lll},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
\end{filecontents}

\begin{filecontents}{biblatextest2.bib}
@MISC{LinkC04,
  author  = {Author Ccc},
  title   = {Some Title},
  year    = 2004,
  url     = {www.test1.com/bild.jpg},
}
@MISC{LinkD01,
  author  = {Author Ddd},
  title   = {Some Title},
  year    = 2001,
  url     = {www.test2.com/bild.jpg},
}
@MISC{LinkD05,
    author  = {Author Eee},
    title   = {Some Title},
    year    = 2004,
    url     = {www.test3.com/bild.jpg},
}
@MISC{LinkD06,
    author  = {Author Fff},
    title   = {Some Title},
    year    = 2001,
    url     = {www.test4.com/bild.jpg},
}
@MISC{LinkD07,
    author  = {Author Ggg},
    title   = {Some Title},
    year    = 2004,
    url     = {www.test5.com/bild.jpg},
}
@MISC{LinkD08,
    author  = {Author Hhh},
    title   = {Some Title},
    year    = 2001,
    url     = {www.test6.com/bild.jpg},
}
\end{filecontents}

\usepackage[style = alphabetic, labelnumber, defernumbers = true,  backend = biber]{biblatex}
\addbibresource{biblatextest1.bib}
\addbibresource{biblatextest2.bib}

\usepackage{hyperref}

%Append keywords to identify different bibliography entries.
\DeclareSourcemap{
    \maps[datatype=bibtex, overwrite]{
        \map{
            \perdatasource{biblatextest1.bib}
            \step[fieldset=KEYWORDS, fieldvalue=primary, append]
        }
        \map{
            \perdatasource{biblatextest2.bib}
            \step[fieldset=KEYWORDS, fieldvalue=secondary, append]
        }
    }
}

\DeclareFieldFormat{labelnumberwidth}{\mkbibbrackets{#1}}
\renewbibmacro*{cite}{%
    \printtext[bibhyperref]{%
        \printfield{labelprefix}%
        \ifkeyword{secondary}
        {\printfield{labelnumber}}
        {\printfield{labelalpha}%
            \printfield{extraalpha}}}}

\defbibenvironment{bibliographyNUM}
{\list
    {\printtext[labelnumberwidth]{%
            \printfield{prefixnumber}%
            \printfield{labelnumber}}}
    {\setlength{\labelwidth}{\labelnumberwidth}%
        \setlength{\leftmargin}{\labelwidth}%
        \setlength{\labelsep}{\biblabelsep}%
        \addtolength{\leftmargin}{\labelsep}%
        \setlength{\itemsep}{\bibitemsep}%
        \setlength{\parsep}{\bibparsep}}%
    \renewcommand*{\makelabel}[1]{\hss##1}}
{\endlist}
{\item}

\assignrefcontextkeyws[sorting=none]{secondary}
\begin{document}

    The first two citations \cite{LinkD07,LinkC04} and \cite{BookB10,BookB11,BookB02,BookB09}.
    The others are \cite{LinkD08,LinkD01,LinkD05,LinkD06} and \cite{BookA03}.

    \printbibliography[title=Bibliography, keyword=primary]

    \newrefcontext[sorting=none]
    \printbibliography[env=bibliographyNUM,title=References, keyword=secondary, resetnumbers]
\end{document}

Thank you for your help in advance.

A: I think I managed to get somewhere based on the numeric-comp and than trying to bring labelalpha information to the shorthand field, which is dealt with natively by the numeric-comp, so you don't need to redefine the cite macros/commands.
I initially tried to do this in the source map, but somehow it didn't work, so I ended up using \AtEveryCitekey for that.
You will probably still have to tune sorting. And you will also notice that the mixed citation of primary and secondary references is less than ideal (I couldn't find out what was determining the sortcite in this case). But the overall result looks reasonable.
\documentclass{article}

\usepackage{filecontents}

\begin{filecontents}{biblatextest1.bib}
@BOOK{BookA03,
  author    = {Author Aaa},
  title     = {Some Title},
  publisher = {Some Publisher},
  year      = 2003,
}
@BOOK{BookB02,
  author    = {Author Bbb},
  title     = {Some Title},
  publisher = {Some Publisher},
  year      = 2002,
}
@BOOK{BookB09,
    author    = {Author Jjj},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
@BOOK{BookB10,
    author    = {Author Kkk},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
@BOOK{BookB11,
    author    = {Author Lll},
    title     = {Some Title},
    publisher = {Some Publisher},
    year      = 2002,
}
\end{filecontents}

\begin{filecontents}{biblatextest2.bib}
@MISC{LinkC04,
  author  = {Author Ccc},
  title   = {Some Title},
  year    = 2004,
  url     = {www.test1.com/bild.jpg},
}
@MISC{LinkD01,
  author  = {Author Ddd},
  title   = {Some Title},
  year    = 2001,
  url     = {www.test2.com/bild.jpg},
}
@MISC{LinkD05,
    author  = {Author Eee},
    title   = {Some Title},
    year    = 2004,
    url     = {www.test3.com/bild.jpg},
}
@MISC{LinkD06,
    author  = {Author Fff},
    title   = {Some Title},
    year    = 2001,
    url     = {www.test4.com/bild.jpg},
}
@MISC{LinkD07,
    author  = {Author Ggg},
    title   = {Some Title},
    year    = 2004,
    url     = {www.test5.com/bild.jpg},
}
@MISC{LinkD08,
    author  = {Author Hhh},
    title   = {Some Title},
    year    = 2001,
    url     = {www.test6.com/bild.jpg},
}
\end{filecontents}

\usepackage[style = numeric-comp, labelalpha, defernumbers]{biblatex}
\addbibresource{biblatextest1.bib}
\addbibresource{biblatextest2.bib}

\usepackage{hyperref}

%Append keywords to identify different bibliography entries.
\DeclareSourcemap{
    \maps[datatype=bibtex, overwrite]{
        \map{
            \perdatasource{biblatextest1.bib}
            \step[fieldset=KEYWORDS, fieldvalue=primary]
        }
        \map{
            \perdatasource{biblatextest2.bib}
            \step[fieldset=KEYWORDS, fieldvalue=secondary]
        }
    }
}

\makeatletter
\newcommand*{\labelalphatoshorthand}{\csdef{abx@field@shorthand}{\strfield{labelprefix}\strfield{labelalpha}\strfield{extraalpha}}}
\makeatother

\AtEveryCitekey{\ifkeyword{primary}{\labelalphatoshorthand}{}}

\DeclareFieldFormat{labelalphawidth}{\mkbibbrackets{#1}}

\defbibenvironment{bibliographyALPHA}
  {\list
     {\printtext[labelalphawidth]{%
        \printfield{labelprefix}%
        \printfield{labelalpha}%
        \printfield{extraalpha}}}
     {\setlength{\labelwidth}{\labelalphawidth}%
      \setlength{\leftmargin}{\labelwidth}%
      \setlength{\labelsep}{\biblabelsep}%
      \addtolength{\leftmargin}{\labelsep}%
      \setlength{\itemsep}{\bibitemsep}%
      \setlength{\parsep}{\bibparsep}}%
      \renewcommand*{\makelabel}[1]{##1\hss}}
  {\endlist}
  {\item}

\begin{document}

The first two citations \cite{LinkD07,LinkC04} and
\cite{BookB10,BookB11,BookB02,BookB09}.

Mixing both primary and secondary
\cite{LinkD08,LinkD01,LinkD05,LinkD06,BookB10,BookB11,BookB02,BookB09}.

The others are \cite{LinkD08,LinkD01,LinkD05,LinkD06,LinkD07}
and \cite{BookA03}.

\printbibliography[env=bibliographyALPHA, title=Bibliography, keyword=primary]

\newrefcontext
\printbibliography[title=References, keyword=secondary, resetnumbers]

\end{document}

Off-topic: notice I removed your append instructions from your DeclareSourcemap steps. The idea of appending is a good one. But suppose you have one field with a keyword mykeyword and append primary to it. You will get mykeywordprimary, which is neither mykeyword nor primary, and your keyword based mechanism for separating the bibliographies will fail (actually you will have missing bibliography entries). So to do that, you would have to include a comma between the keywords and handle the case of the field being empty or not, and so on.


text:
Q: Why the scope goes wrong in this Typescript/jscript piece of code the code below is inside a "view" and is having scope issues with "this"
Typescript:
getInvitations() {
        var invitationsUri = "/Api/Invitations/";

        $.ajax({
            url: invitationsUri ,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json'
        })
            .done((result) => {
                $.each(result, (index, item) => {
                    var invitation = new Invitation();
                    invitation.InvitationId(item.InvitationId);
                    invitation.Invited(true);
                    invitation.Email(item.Email);

                    this.Business.Invitations.push(invitation);
                });
            })
            .fail((x, y, z) => {
                alert(x + '\n' + y + '\n' + z + ' - failed to get invitations');
            });
    }

    getUsers() {
        var usersUri = "/Api/Users/";

        $.ajax({
            url: usersUri,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json'
        })
            .done((result) => {
                $.each(result, (index, item) => {
                    var user = new User();
                    user.Id(item.Id);
                    user.UserName(item.UserName);
                    user.Email(item.Email);

                    this.Business.Users.push(user);
                });
            })
            .fail((x, y, z) => {
                alert(x + '\n' + y + '\n' + z + ' - failed to get users');
            });
    }

The first method works well, the second thinks "this" is referring to "item", so it does not recognize "Business" as a property and with that the objective is not achieved.
Any ideas what could be happening here?
EDIT:
Here is the generated code (jscript)
BusinessView.prototype.getInvitations = function () {
        var _this = this;
        var invitationsUri = "/Api/Invitations/";

        $.ajax({
            url: invitationsUri,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json'
        }).done(function (result) {
            $.each(result, function (index, item) {
                var invitation = new Invitation();
                invitation.InvitationId(item.InvitationId);
                invitation.Invited(true);
                invitation.Email(item.Email);

                _this.Business.Invitations.push(invitation);
            });
        }).fail(function (x, y, z) {
            alert(x + '\n' + y + '\n' + z + ' - failed to get invitations');
        });
    };

    BusinessView.prototype.getUsers = function () {
        var _this = this;
        var usersUri = "/Api/Users/";

        $.ajax({
            url: usersUri,
            type: 'GET',
            dataType: 'json',
            contentType: 'application/json'
        }).done(function (result) {
            $.each(result, function (index, item) {
                var user = new User();
                user.Id(item.Id);
                user.UserName(item.UserName);
                user.Email(item.Email);

                _this.Business.Users.push(user);
            });
        }).fail(function (x, y, z) {
            alert(x + '\n' + y + '\n' + z + ' - failed to get users');
        });
    };

A: Inside a jQuery .each() callback, this is always set by jQuery so it won't be what this was in a higher level scope.  If you need to access the value of this from the higher level scope, then the usual work-around is to save it to a local variable at that higher level scope and you can then access that local variable from within the .each() callback function.
From the code snippet you included in your answer, it is not clear what this value you want to access.  You may also need to know that call a regular function such as calling getInvitations() will change the this pointer to point to either the global object or in strict mode to undefined.  this is set by the javascript interpreter on every function call based on how the function call is made.

A: You got the lambda correct in the each calls i.e. $.each(result, (index, item) => { You should do the same for the function definitions to ensure that this gets scoped correct all the way through i.e. getInvitations = () => { and getUsers = () => {


text:
Q: How do I solve the brain level in G30? In chapter 6 of G30, there is a puzzle titled "Brain" which involves unscrambling four sections of a brain.

I've been able to unscramble all 4 sections to resemble prices of a brain, but I can't figure out how to make each piece fit together.

How do I solve the brain level in G30?


text:
Q: Llenar campos segun opcion elegida quiero llenar dos campos según la opción elegida por el usuario.
Mi código es este:

                Cuatrimestre
                <select id="cuatrimestre" name="cuatrimestre" class="form control">
                  <?php
                    $bd = new ManejoDB();
                    $bd->conectar_base($x,$x,$x);
                    $sql = "SELECT * FROM x";
                    $bd->qBD($sql);
                    while ($row = $bd->obtenerReg()){
                      //echo "<option value='".$row['id']."'>'".$row['descripcion']."'</option>";
                      echo "<option>".$row['descripcion']."</option>";
                    }
                  ?>
                </select>

                                Desde
                    <input type="text" name="desde" id="desde">

                                Hasta
                    <input type="text" name="hasta" id="hasta">

código js
$(document).ready(function(){
            $('#cuatrimestre').on('change',function(){
                var cuatrimestre = $(this).val();
                $.ajax({
                    url : "getCuatri.php",
                    dataType: 'json',
                    type: 'POST',
                    async : false,
                    data : { cuatrimestre : cuatrimestre},
                    success : function(data) {
                        userData = json.parse(data);
                        $('#desde').val(userData.fecha_desde);
                        $('#hasta').val(userData.fecha_hasta);
                    }
                });
            });
        });

getCuatri.php

$bd = new ManejoDB();
$bd->conectar_base($x,$x,$x);
$sql = "SELECT fecha_desde, fecha_hasta from Encuesta_Compras_Cuatrimestre where descripcion= '".$descripcion."' ";
$bd->qBD($sql);
$row = $bd->obtenerReg();
json_encode($row); die;

Ese es mi código pero no funciona.
Hago un include y el js lo tengo separado y también lo incluyo.
Qué tengo mal?
Muchas gracias, un saludo

A: Aun no puedo comentar :(
en tu archivo getCuatri.php te falta imprimir el resultado
$bd = new ManejoDB();
$bd->conectar_base($x,$x,$x);
$sql = "SELECT fecha_desde, fecha_hasta from Encuesta_Compras_Cuatrimestre where descripcion= '".$descripcion."' ";
$bd->qBD($sql);
$row = $bd->obtenerReg();
echo json_encode($row); die;

Solo te hace falta el echo antes del json_encode


text:
Q: How to use C++ libraries in Objective C HI,
I was wondering how can I use C++ libraries in Objective C ?? Do i need to convert it to Objective C++ or I can use them Directly??
I read few post which ask the similar question but they have libraries for specific thing like Networking, My libraries are for graphics.
Also how would I test that which function of the library is supported and which is not??

A: Yes you will need to call then from and use the C++ heders in an Objective C++ file but this is just and Objective C code file with a .mm extension that uses C++ syntax rather than C. the methods and functions (if functions are declare extern "C") can be called from Objective C. Any C++ classes can only be used in the Objective C++ files unless cast to void* pointers to be passed through the Objective C.
Xcode/ OSX developer tools will manage these differences automatically.

A: Objective-C++ works exactly how you would hope it would -- you name the file with a .mm, and then commix code written in the two languages.  Including a precompiled C++ library works fine from a .mm file.

A: Link the object code with your compiler.


text:
Q: PhoneGap Android Market Publishing Hi I'm looking for a good phoneGap tutorial all the way tru publishing an app, I've seen several but none have been able to help me successfully publish my apps.
I currently write on Html CSS Javascript
Any tips will greatly be appreciated thank you!!
I mostly get how to use phoneGap to where you make the folder with the "www" folder inside now after that when I try to insert my html into there and go tru the adobe phoneGap build it does build butttttttt when I make it into an Apk file and try to upload it to the market it gives the error that needs debugging and can't upload it to android. And that's where I am stuck....
<!doc type>

simple html game
Simple html game for android market!
 any tips please submit thank you

A: Found my answer all I needed to do is make it from debug able to signed so it can be published to the market and booooom to the store.


text:
Q: Building applications on Windows 7 for Windows XP I believe that some API has changed or has been replaced with another API between Windows 7 and Windows XP. So my app which has been built on Windows 7, fails to load on Windows XP .
Is it possible that I can pass some flag to the Visual C/C++ compiler (Visual Studio 2008) or set some environment flag to tell Visual Studio to build my application for Windows XP while building on Windows 7?
One solution is to build it on Windows XP but that is something I want to avoid.

A: In your project properties, define preprocessor constants: WINVER=0x0501 and _WIN32_WINNT=0x0501. Or you can #define them in all header files, before you #include any of the standard headers.
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501

See more information on MSDN (for some reason I cannot add direct link to MSDN here, but you should be able to search for it).


text:
Q: SQLiteConstraintException on inserting values in table I am new to android development and I have an android database table with following code
public class SoftCopyDatabase extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "SoftCopy.db";
private static final int DATABASE_VERSION = 1;

public SoftCopyDatabase(Context ctx) {
    super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + _ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SUBJECT
            + " TEXT NOT NULL," + TOPIC + " TEXT NOT NULL, "
            + LECTURENUMBER + " TEXT NOT NULL, " + PAGENUMBER
            + " TEXT NOT NULL, " + DATE + " TEXT NOT NULL, " + _DATA
            + " TEXT NOT NULL);");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}}

I am trying to add to this table using the method addInfo(), which is as follows:
private void addInfo(){
    ContentValues values = new ContentValues();
    values.put(SUBJECT, SaveData._subject);
    values.put(TOPIC, SaveData._topic);
    values.put(LECTURENUMBER, SaveData._lecturenumber);
    values.put(PAGENUMBER, Integer.toString(PAGE_NUMBER));
    values.put(DATE, SaveData._date);
    values.put(_DATA, SaveData.FILE_NAME + ".png");
    softCopyDB.getWritableDatabase().insertOrThrow(TABLE_NAME, null, values);

}

But when I increase the value of PAGE_NUMBER( Page_NUMBER is an Integer) while keeping all other entries same and call addInfo(), I receive an error at
 softCopyDB.getWritableDatabase().insertOrThrow(TABLE_NAME, null, values);
which is as follows
08-21 18:16:11.216: ERROR/AndroidRuntime(329): Caused by: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
08-21 18:16:11.216: ERROR/AndroidRuntime(329):     at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
08-21 18:16:11.216: ERROR/AndroidRuntime(329):     at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:55)
08-21 18:16:11.216: ERROR/AndroidRuntime(329):     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1549)
08-21 18:16:11.216: ERROR/AndroidRuntime(329):     at android.database.sqlite.SQLiteDatabase.insertOrThrow(SQLiteDatabase.java:1432)
08-21 18:16:11.216: ERROR/AndroidRuntime(329):     at neduet.telecom.softcopy.surface.LectureNoting.addInfo(LectureNoting.java:161)
Please help me in sorting this.

A: The only constraints I can see is PK and NOT NULL. As _ID is not part of your insert I would check your text values for null.


text:
Q: libGDX: Outer Glow for image using shader I am game developer using libGDX framework, but new in shader OpenGL. I was trying to do outer glow like this image:

I found simple tutorials in different sites for example like this 2D Selection Outline Shader in LibGDX. It works fine but Outline only drew and the image didn't draw I don't know why !
The image:

In render method:
@Override
public void render() {
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    shaderOutline.begin();
    shaderOutline.setUniformf("u_viewportInverse", new Vector2(1f / 99, 1f / 94));
    shaderOutline.setUniformf("u_offset", 2);
    shaderOutline.setUniformf("u_step", Math.min(1f, 99 / 70f));
    shaderOutline.setUniformf("u_color", new Vector3(123/255, 1, 71/255));
    shaderOutline.end();

    batch.setShader(shaderOutline);
    batch.begin();
    batch.draw(img, 240, 400);
    batch.end();
    batch.setShader(null);

}

Output:

Finally, I need any advice in this field (shading language).

A: You need to add the drawing of the image itself as well:
In render:
batch.setShader(shaderOutline);
batch.begin();
batch.draw(img, 240, 400);
batch.end();
batch.setShader(null);
// Add this:
batch.begin();
batch.draw(img, 240, 400);
batch.end();


text: Q: Play store and Google play markets ratings on webpage My friend made application for iOS and Android and added it to play store and google play. I would like to make website to promote them, but I wonder how to add ratings from those stores on our website. I couldn't find anything on the web so my first approach is to parse website from this store and copy ratings from their source codes. This would be so slow. Anyone has an idea how to make it faster?


text:
Q: PyQt4 and Qwt Error when opening i´m trying to do a simple plot, using PyQt4 and Qwt5. When i start the app, it shows as i expected,  but i can´t do anything, such as click or zoom for example. And if i minimize it, the plot disappears.
This is my code:
import sys
from PyQt4 import Qt
import numpy as np
import PyQt4.Qwt5.iqt
from PyQt4.Qwt5.qplt
class SimpleData(QwtPlot):
def __init__(self):
    QwtPlot.__init__(self)

    x = np.arange(-2*np.pi, 2*np.pi, 0.01)
    p = IPlot(Curve(x, np.cos(x), Pen(Magenta,2), "cos(x)"),
        Curve(x, np.exp(x), Pen(Red), "exp(x)", Y2),
        Axis(Right, Log),"Ejemplo de PyQt con PyQwt")

    x = x[0: -1: 10]

    p.plot(Curve(x, np.cos(x-np.pi/4), Symbol(Circle, Yellow), "circle"),
        Curve(x, np.cos(x+np.pi/4), Pen(Blue), Symbol(Square, Cyan), "Square"))

app = QApplication(sys.argv)
app.exec_()

The indentation is correct, maybe i made a mistake writting it here, but it´s ok.
Another thing, when i close the app, i get this error:
QObject::killTimers: timers cannot be stopped from another thread
[Finished in 2.6s with exit code -1073741510]
Thank you for your time and answers. I hope you can help me.


text:
Q: C++ Program in Xcode not outputting simple text file using outFile I am running a program using this simple example code to output a text file. I am using Xcode and simply started a new C++ project from command line tools. For some reason the program does not output any file onto my Mac. Please help figure out why XCode will not output any file to my computer? Thanks!
#include <iostream>
#include <fstream>

using namespace std;

int main() {
double myNumber = 42.5;
fstream outfile("test.txt", fstream::out);
outfile << "The answer is almost " << myNumber << endl;
outfile.close();
}

A: Dang I can't believe I figured it out, it was an option in Xcode. So I clicked on the bar at the top of xcode near the stop button with the text (Project Name > My Mac 64-bit)
Then clicked edit scheme. The clicked on the options tab and clicked use custom working directory. Then selected a working directory. Now the text file appears!

A: As mentioned above, editing the scheme worked for me but getting to the scheme was different.

*

*Use the Product Menu

*Select the Scheme option

*Select the Edit Scheme option

*Click the Options Tab

*Tick the "Working Directory" item

*Click the small icon at the right end of the text box.

*Select the directory

I also had the Run/Debug option selected in the left hand pane of the window.

A: To find the current working directory, in the project navigator, under the "Products" folder, right-click the product and choose "Show in Finder". In this directory you will also find the compiled code.
For example:
~/Library/Developer/Xcode/DerivedData/<project name>-gweghgfqkjkidjfhcgetdryechjz/Build/Products/Debug


text:
Q: Как установить стартовую позицию тексту в контейнере со скроллом?
В общем-то вопрос в том, можно ли задать стартовую позицию для текста в контейнере с возможностью сролла, так чтобы при скролле текст уходил вверх за эту линию?

A: Догадался сам :)
Можно создать пустой див прямо перед текстом и задать ему размеры.
Возможно это не самый хороший вариант, но все же работает как я и хотел.


text:
Q: Repeatedly Updating a JPanel Inside of a For-loop Inside of an Actionlistener for Animation I'm trying to get a JPanel to update repeatedly after a JButton gets clicked.  I have a method called updatePanelGrid(), which is activated with a JButton ActionListener, and everything there works perfectly fine.  I have another method called updatePanelGridVisual(), which calls updatePanelGrid() many hundreds of times, and is activated with a JButton ActionListener; however, it does not work so well.  The goal is for it to update every 0.1 seconds in the same way as updatePanelGrid(), making kinda a little animation.  (By the way, I'm new to Java.)
Here is the class method updatePanelGridVisual():
public void updatePanelGridVisual(JPanel panelGrid, ArrayList<Grid> backtrackingGrids) {
    new Thread() {
        @Override
        public void run() {
            for (int i=0; i<backtrackingGrids.size(); i++) {
                updatePanelGrid(panelGrid, backtrackingGrids.get(i));//Not working.
                System.out.println(backtrackingGrids.get(i));//For testing, prints fine.
                try {
                    //Pause for 0.1 seconds
                    Thread.sleep(100);//Time in milliseconds.
                } catch (InterruptedException ex) {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }.start();
}

Here is the JButton ActionListener, which resides inside the main:
button.addActionListener(
    new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            updatePanelGridVisual(panelGrid);
        }
    }
);

Everything is printing to the console exactly as I would expect it to, but when updatePanelGrid(panelGrid, backtrackingGrids.get(i)) is called, it will either do nothing or update only partially, creating only a portion of the grid that I have on panelGrid.


text:
Q: XFCE login screen: All passwords are correct Everytime I boot my computer or just log out, the random password I enter in the XFCE login screen, is correct (even when it's not). I'm running XUbuntu 14.04.
I also have a second machine running the exact same version of XUbuntu with almost the same settings, but on that one it works fine.
How do I fix this? Is this a known bug?

A: This is not related to Xfce, but to lightdm (or whatever desktop manager Xubuntu is using). The desktop manager uses PAM for authentication. PAM does several things, but in the end it checks your/etc/shadowfor the valid password. See http://linux.die.net/man/5/shadow how to interpret this file. And only usevipw -sfor editing this file.


text:
Q: How do you get people to value abstraction and flexibility over "just getting it done"? I sometimes have difficulties with other people who wish to solve a problem when they wish to skip the official interfaces and access underlying implementation details directly.
They argue that doing so will allow them to solve the problem more quickly.  I argue that doing so will cause our architecture to become more tightly coupled and difficult to change as new requirements emerge.
I point out all of the work that went into the current design and the philosophy of the design and the value of flexibility, the cost of trying to maintain and change brittle code, the value of encapsulation and data hiding and layered architectures and being robust so that small changes in the specification lead to small changes in the code.  And they say "But this would be easier."
How do you handle these people?

A: Have them work on some legacy code fixing the bugs in it. This is pretty much how most people I know have learned these really valuable lessons ... the hard way.

A: Convince them that taking shortcuts is a false economy.
Explain that the initial coding effort is less than 30% of the initial development effort, and less than 10% (in my experience) of the overall project effort (including maintenance).
If they remain unconvinced, and you have the authority to do so, then tell them to do it your way. If you don't have the authority, then do nothing else. Eventually your supervisor, if she is worth anything, will recognize this and you will then be in the position of authority.

A: "Easier" when?  Now, when everything isn't in a state of flux?  Or three months from now when the customer's requirements have changed and they've got a 'solution' that isn't a solution any longer?
I'm not much for structure and rules for the sake of structure and rules, but it is good to know A)  who is driving the boat B) what the rules are and C) why we chose to do it this way.
In my shop we don't like to have to rewrite code because we screwed up and hardcoded a bunch of stuff or created some brittle 'solution' to the problem.  It tends not to be any harder to follow the more flexible approach once folks realize that it will reduce the frustrations later on when things are turned upside down by a bunch of requirement changes.  We code for the 'long haul' not for the 'need it today', typically, so the design is made for a reason and the design is followed for the same reason.
I spent a week of my life (7 days straight) rewriting a module because I was in 'get it done quick' mode.  Seven days of grueling time, 10-12 hour days doing it the right way, late in the game, when I could have been watching the Super Bowl.  That stunk.  I learned a lesson there. It may be that your 'friends' will need to experience that sort of eye opener themselves too.
Best of luck!

A: I actually hate to take the dissenting opinion on this, but...
To quote Van Halen (quoting cliche), "there's a time and place for everything." While I certainly don't advocate writing badly, ever, sometimes you do need to just get it done, and find that happy medium between robust/enduring and hacked/documented. (The documented part being particularly important, on two fronts: one, that you clearly indicate that whatever it is you're doing is being done simply in the interests of getting it done and is taking certain shortcuts; and, two, a rough idea as to what the more correct way of approaching the problem might be.
As programmers, we often strive to write the perfect code (well, some of us do), and sometimes lose sight of the big picture - there are any number of reasons why it might be ok (on a level) to play fast and loose with the code, while minimizing the impact that will have down the road.
Please do not use this as justification - the 80/20 rule applies here, of course. Most of the time you absolutely want to crush any shortcuts along these lines; but sometimes...

A: The best thing is probably to promote them to management so they can't do quite so much damage.

A: Show them! Let them do a small module in "But this would be easier." style while you do it the right way. Then ask them to make 2 to 5 changes to the requirements (it must be them making the changes) and have a timed contest on implementing the changes. It may take a day or two but they will get it. If you don't, you will have the same discussion on every new project or task.

A: You could try an analogy on them....
The rules of chess are pretty simple.  You can teach them to a child: "the horsey moves like this", "the castle moves like this", etc.
If that's all you know, you can play some chess and probably have a good time, but someone with a deeper knowledge of the game is going to wipe the board with you every time.  You'll get beat so bad it won't even be fun anymore, because you'll have no idea how they're doing it.
The same principle applies to programming.  Knowing the syntax of the language and a few simple data structures is enough to get you a working program, but you're not going to have much luck with a large-scale application that has to survive multiple release cycles.
Chess has set openings, attack strategies, etc.  We have Design Patterns.

A: The problem is most people don't even know about software design other than the most basic  concepts and drag and drop style development. For every one developer who researches and educates themselves on all the best new concepts and technologies, there are ten who go home and don't look at a PC. You have to teach them.

A: I designed a big and complicated system about five years ago. I spent the next five years injecting myself into every project that affected "my" system to keep the barbarians from sullying my architecture. As long as I applied constant, unrelenting pressure I was able to keep the architecture pretty clean, but I was fighting a losing battle. Here's why:
1) Most people are judged on whether they got the job done today. Nobody has ever been reprimanded because they cut a corner (or two) three years ago to get a project out the door on time. On the other hand, many people have been reprimanded for not getting projects out the door on time.
2) You may want to keep the system tidy because you have a sense of ownership over the code, or the application, or the users, etc. Many people will not have a sense of ownership and therefore are all too happy to hack something up so they can be done with it. You can lead a horse to water, but you can't make him care.
3) If you do convince everybody to maintain the code properly, new people will come on board and need to be taught how to do things right. So even if you're successful you can feel like you're failing because you're always fighting the same battle against new opponents.
4) You might actually be wrong. Would it make financial sense for Microsoft to spend twice as many programmer hours making MS-Paint robust and maintainable? Sometimes an ugly hacked-together system is Good Enough. Most good programmers have trouble understanding this, but this is usually because they're good programmers.
5) I swear there are some people who take perverse pleasure in hacking things together either because they can do it faster, or they'll be the only ones who understand it, or they have a childish need to break rules. You can't reason with these people, and the more time you spend arguing with them the closer the project deadline gets, which will force you to hack something together anyway.
6) There's a good chance you understand the system better than they do. What looks like an ugly hack to you might look like "treading lightly" to a person who isn't as familiar with the system. Or the extra effort to make the code robust will protect the programmer against a problem he's never had before and therefore can't grok. You don't learn to check return codes until something goes wrong because you didn't check a return code. At that point it stops being "extra work" and starts being "required work".
If you have a small, tight development team it's possible. But the bigger the organization the less likely you are to succeed. If you manage to get a 250-person IT shop to value doing things right over doing things fast then your powers of persuasion are legendary.

A: http://catb.org/jargon/html/L/LART.html
SCNR, etc. pp ;)

A: Tell them to read (not that they ever will) Encapsulation theory:
http://www.edmundkirwan.com/


text:
Q: Edit text in android Hi am having one Edit Text which is used to get the information about the user.i have set the following properties to edit text
<EditText
        android:id="@+id/profile_about"
        android:layout_below="@id/AboutYou"
        android:layout_centerInParent="true"
        android:layout_marginLeft="8dip"
        android:layout_marginBottom="10dip"
        android:layout_marginRight="18dip"
        android:gravity="top|left"
        android:inputType="textCapWords"
        android:textColor="#000000"
        android:background="@drawable/edittext"

        android:layout_width="300dip"
        android:layout_height="100dip"
        android:textSize="16sp"
    />

the problem is it scrolls horizontal only.not go the newline after entering certain characters.can anybody help me?

A: I replaced android:inputType="textCapWords" by     android:inputType="textMultiLine|textCapWords", and it works.

A: Try using android:singleLine="false"

A: android:singleLine="false"
if this property is set then the charecters after a certain limit will go to next line automatically...
try this too
 android:scrollHorizontally="false"


text:
Q: Phalcon validate field depends on another fields I using Phalcon framework, i have a Collection Model, in validate() function of this model, i validate my fields like below:
class Users extends Collection
{

    public function validation()
    {

        $this->validate(
            new EmailValidator(
                array(
                    "field"   => "email",
                    "message" => "email is not valid"
                )
            )
        );

        $this->validate(
            new NumericalityValidator(
                array(
                    "field"   => "phone",
                    "message" => "phone is not valid"
                )
            )
        );

        return $this->validationHasFailed() != true;
    }

}

How can i tel to this model one of these two fields are mandatory ?
for example if tel is not empty, email can be empty, or if email is not empty, tel can empty, and when both fields are empty, validation should be failed.

A: Something like this ?
public function validation()
{
    if(empty($this->phone)) {
        $this->validate(
            new EmailValidator(
                array(
                    "field"   => "email",
                    "message" => "email is not valid"
                )
            )
        );
    }

    if(empty($this->email)) {
        $this->validate(
            new NumericalityValidator(
                array(
                    "field"   => "phone",
                    "message" => "phone is not valid"
                )
            )
        );
    }

    return $this->validationHasFailed() != true;
}

A: You should be able to append a message.
https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Message.html
<?php

use Phalcon\Mvc\Model\Message as Message;

public function validation()
{
    if(empty($this->phone) && empty($this->email)) {
        $message = new Message('Phone or email must be provided',
                               array('phone','email'),
                               'PresenceOf');
    $this->appendMessage($message);
    return $this->validationHasFailed() != true;
}


text:
Q: Getting children and grand children for a parent in Hive I have a hierarchy Hive table with two columns, Parent and Child.
I need to get the list of all descendants associated with the parent records. Please note that
recursive SQL is not supported in Hive/Imapala.
Source Table
+----+-----------+
| Parent | Child |
+----+-----------+
|  a     |     b |
|  b     |     c |
|  c     |     d |
|  d     |     e |
|  e     |     f |
|  f     |     x |
+----+-----------+

Expected Result:
+----+-----------+
| Parent | Child |
+----+-----------+
|  a     |     b |  // As b is the child of a, all the descendants of b
|  a     |     c |  // are also descendants of a.
|  a     |     d |
|  a     |     e |
|  a     |     f |
|  a     |     x |
|  b     |     c |  // As c is the child of b, all the descendants of c
|  b     |     d |  // are also descendants of b.
|  b     |     e |
|  b     |     f |
|  b     |     x |
|  c     |     d |
|  c     |     e |
|  c     |     f |
|  c     |     x |
|  d     |     e |
|  d     |     f |
|  d     |     x |
|  e     |     f |
|  e     |     x |
|  f     |     x |
+----+-----------+

Thank you!


text:
Q: Select Specific Elements from XML I have the following XML structure
<books>
   <crime>
      <crime_book title="abc" />
      <crime_book title="def" />
   </crime>
   <vacation>
      <vacation_book title="ghi" />
   </vacation>
   <drama />
</books>

How can I get all books in one list?
I have
var doc = XDocument.Load("filename");
var query = from element in doc.Root.Elements()
            select element;

but that gives me only the book types. I want to skip that level.

A: Simple,
var query = doc.Descendants("book");

EDIT
To get the book in all levels
var query = xDoc.Descendants()
            .Where(d => d.Name.LocalName.EndsWith("_book"));

or
var query = xDoc.Descendants()
            .Where(d => d.Parent != null)
            .Where(d => d.Name.LocalName == d.Parent.Name.LocalName + "_book");

A: Enumerable.SelectMany:
doc.Root.Elements().SelectMany(n => n.Elements());

Basically the same as Select, but it flattens the sequence one level.

A: How about using XPath? assuming only books have an attribute title
var query = doc.XPathSelectElements("//*[@title]");

A: I'm guessing you want a list of titles, so this would put them in an IEnumerable<XAttribute>:
var titleAttributes = doc.Descendants().SelectMany(e => e.Attributes("title"));

Works no matter how nested elements with a title attribute are and regardless of element names being different at various levels as per your comments on the other answer.

A: Another one liner option is to check for the title attribute
var result = doc.Descendants().Where(x=>x.Attribute("title") != null);


text:
Q: how to run papi rapl on intel atom I am trying to run the rapl of papi-5.3.2 on intel atom (Intel(R) Atom(TM) CPU  C2758  @ 2.40GHz).
When I try to run make file in the rapl, msg I get is
"make: * No rule to make target -L../../..', needed byrapl_basic'.  Stop."
Can you please guide me how to run the rapl on atom?
I am using ubuntu version 13.10.

A: you dont need to implement difficult compilations to install papi in Ubuntu. It is in the Official Ubuntu Repository.
You can install it as:
sudo apt-get install libpapi5.3


text:
Q: How to pass multiple parameters using web-api I want to pass two params using json in web-api, but I get null each time I try, what am I missing ? is there a better way to pass more than one parameter?
//HTML
var uri = "api/Login";

//after I click a button this function fires
function checkUser() {
        var email = "ttt@ggg.com";
       var password = "itsme";
          var details = "{ email:'"+ email+"', pass:'"+ password+"'}";
        $.ajax({
            type: "Get",
            data: JSON.stringify(details),
            url: uri,
            contentType: "application/json"
        });
    }

// LoginController
[HttpGet]
public HttpResponseMessage Get([FromBody]string  data)
{
     HttpResponseMessage msg = null;
     //the code run this function, but the 'data' is null
     string userinfo = data;
     return msg;
}

A: In addition to GET vs. POST issue noted by @su8898, you are already building a string in details and then trying to stringify it.  You should define details as object literal like this:
var details = {
    'email': email,
    'pass': password
};

This would give you an actual object to stringify.

A: [FromBody] attribute won't work on GET requests because there is no body in a GET request.
You must either pass the values as parameters or change the method to [HttpPost]. I suggest you change the method to [HttpPost] and change your ajax request method to POST.
[HttpPost]
public HttpResponseMessage Get([FromBody]string  data)
{
    HttpResponseMessage msg = null;
    //the code run this function, but the 'data' is null
    string userinfo = data;
    return msg;
}

and in your ajax request
function checkUser() {
    var email = "ttt@ggg.com";
    var password = "itsme";
      var details = "{ email:'"+ email+"', pass:'"+ password+"'}";
    $.ajax({
        type: "POST",
        data: JSON.stringify(details),
        url: uri,
        contentType: "application/json"
    });
}


text:
Q: Which Sharepoint 2007 development book is most dedicated to client-side programming? I need to learn how to develop web pages in Sharepoint 2007, so I'm looking for a book.  However, I only have client-side access, and it's not clear which of the SP2007 developer textbooks concentrate on client-side programming.
I've read the reviews for:

*

*Pro SharePoint Solution Development: Combining .NET, SharePoint and
Office 2007

*Professional SharePoint 2007 Development

*MicrosoftSharePoint 2007 Development Unleashed

*Microsoft® Office SharePoint®
Designer 2007 Step by Step

Are any of these books especially good for client-side development?

A: Client-side programming wasn't really a big part of SharePoint 2007. No API's, no "javascript-way" of doing things. It wasn't until SharePoint 2010 it really started becoming a thing in SharePoint.
So I'm afraid it's a bit of a Mission Impossible to try and find books about client-side programming for SharePoint 2007.

A: Inside Windows SharePoint Services 3.0 has a chapter devoted to Ajax and client-side programming.


text:
Q: What is the syntax for scanner be utilized to read from files in JAVA? I am trying to set up a stream from a file that is entered into the method fromFile, yet when I try to access this from within in my method, I get error. How can I fix this.
public int[] fromFile(String fileName)
{
    // TO-DO: convert the file to a int[]
    int[] ret = new int [9];
    int i = 0;

    File file = new File(fileName);

        while (i < 10){
        Scanner s = new Scanner(file); //HERE I get FileNotFoundException

        ret [i] = Integer.parseInt(s.next());
        i++;

     }

A: There are actually a few issues with your code; first, you need to close the Scanner after you use it when it wraps a File (or you leak file handles) here I use a try-with-resources. Second, you can check if the file exists and is readable by calling File.canRead() before you try to read it. Also, you can use Scanner.nextInt() instead of manually parsing your values (and you should probably call Scanner.hasNextInt() first). Something like,
public static int[] fromFile(String fileName) {
    int[] ret = new int[9];
    int i = 0;

    File file = new File(fileName);
    if (!file.canRead()) {
        try {
            System.err.printf("Cant read file at %s%n", file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    try (Scanner s = new Scanner(file)) {
        while (i < 10 && s.hasNextInt()) {
            ret[i] = s.nextInt();
            i++;
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return ret;
}


text:
Q: Parse child of XML (AJAX) I know this is very simple question but how I can parse child of xml item?
I have WebUrl, but I need Description and Url.
This is my XML File :
<d:WebURL m:type="SP.FieldUrlValue">
    <d:Description>Google</d:Description>
    <d:Url>http://google.com</d:Url>
</d:WebURL>
<d:PublishingStartDate m:null="true"/>
<d:PublishingExpirationDate m:null="true">

This is my JS code :
function takeresult() {
    var myurl = "";
    var executor = new CE.RequestExecutor();
    executor.executeAsync({
        url: itemsUrl,
        method: "GET",
        success: myresult,
        error: error
    });
}

function myresult(data) {
    var jsonObject = JSON.parse(data.body);
    var resultat = jsonObject.d.results;
    $(resultat).each(function(){
        var weburl = $(this)[0].WebURL;
        var description = ??
    });
}

A: since you're using jQuery already, and I'm assuming your server is returning XML.
function myresult(data) {
    xmlDoc = $.parseXML(data.body);
    $xml = $( xmlDoc ),
    $description = $xml.find( "description" );
    alert($description.text());
}


text:
Q: Retrieve html from textbox and display in popup I'm retrieving a string from a textbox which will contain html eg

.
Basically i have got the content from the textbox, but cant get the popup to display like a html page.
In my jquery code i have
          var html = document.getElementById('<%=txtHtmlBody.ClientID%>').value;
          $(html).dialog();

At the moment the content looks like it is squashed into a small box, with a transparent background.
How can i get this to display like a html page in a popup?, any help is appreciated
Thanks in advance

A: You need a div that is filled with the contents of your textbox.
var myhtml = document.getElementById('<%=txtHtmlBody.ClientID%>').value;
$('#mydiv').html(myhtml);
$('#mydiv').dialog();

A: you should add one empty element in your page.

so, put value of field into your element, and show this:
$('#dialog').html($('#<%=txtHtmlBody.ClientID%>').val());
$('#dialog').dialog();


text:
Q: Git checkout file - casing in file name
Git newbie here :)
Faced casing-related problem: file aspnetdb.mdf was removed from repository several commits ago, I decided to restore it from some of earlier commits and did it is such way:
git checkout master~3 aspnetdb.mdf

wanted to get file from 3rd back commit
But git said, that there was no such file.
Then I executed following:
git checkout master~3 ASPNETDB.MDF

which worked fine - I had got needed file.
HOWEVER. Command git checkout master~3 aspnetdb_log.ldf (with low-case file name) command executed fine. During all dev. Process both files were processing in same way (no hack renames etc. :) ).
How explain such behavior? What had I done wrong?

A: As mentioned in the comment, since you are using Git on a case insensitive system (Windows), try and set core.ignorecase properly. Check with:
$ git-config --list

If not set:
$ git-config --global core.ignorecase true


text:
Q: csv data into python I got a quite a large csv file with data and I want to take the data (just a bunch of floating numbers) from a row and turn it into a list. Preferably without using a for-loop because there is quite a lot of data.
The file looks like this (+600 columns):
image
import pandas as pd
data = pd.read_csv('BM1-2022-Gruppe_18_stål_8mm.csv')
print(data)
Traceback (most recent call last):
File "pandas_libs\parsers.pyx", line 1083, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas_libs\parsers.pyx", line 1233, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas_libs\parsers.pyx", line 1246, in pandas._libs.parsers.TextReader._string_convert
File "pandas_libs\parsers.pyx", line 1444, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 16: invalid continuation byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\terje\Desktop\test (2).py", line 3, in
data = pd.read_csv('BM1-2022-Gruppe_18_stål_8mm.csv')
File "C:\Python310\lib\site-packages\pandas\util_decorators.py", line 211, in wrapper
return func(*args, **kwargs)
File "C:\Python310\lib\site-packages\pandas\util_decorators.py", line 317, in wrapper
return func(*args, **kwargs)
File "C:\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 950, in read_csv
return _read(filepath_or_buffer, kwds)
File "C:\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 611, in _read
return parser.read(nrows)
File "C:\Python310\lib\site-packages\pandas\io\parsers\readers.py", line 1772, in read
) = self._engine.read(  # type: ignore[attr-defined]
File "C:\Python310\lib\site-packages\pandas\io\parsers\c_parser_wrapper.py", line 243, in read
chunks = self._reader.read_low_memory(nrows)
File "pandas_libs\parsers.pyx", line 808, in pandas._libs.parsers.TextReader.read_low_memory
File "pandas_libs\parsers.pyx", line 890, in pandas._libs.parsers.TextReader._read_rows
File "pandas_libs\parsers.pyx", line 1037, in pandas._libs.parsers.TextReader._convert_column_data
File "pandas_libs\parsers.pyx", line 1090, in pandas._libs.parsers.TextReader._convert_tokens
File "pandas_libs\parsers.pyx", line 1233, in pandas._libs.parsers.TextReader._convert_with_dtype
File "pandas_libs\parsers.pyx", line 1246, in pandas._libs.parsers.TextReader._string_convert
File "pandas_libs\parsers.pyx", line 1444, in pandas._libs.parsers._string_box_utf8
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 16: invalid continuation byte


text:
Q: issue using DBT commands in visual studio even though i have the models, yaml files etc I hope you can help me! I have used DBT before with no issues on a macbook before but for some reason even after installing DBT on windows I am receiving errors in the visual studio terminal, giving me the error
dbt : The term 'dbt' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
i have tried using dbt debug,dbt run,  configured my sample profiles_yaml, project profiles_yaml and my profiles.yaml file and i still get the above error n my terminal. Please can someone help me, I am happy to share more with you if needed and am so worried over this as I am stumped as to what the issue may be. I tried reinstalling it via powershell and get an error saying some dependencies may be missing, though bigquery dbt is installed.
Thank you for your help
Lily

A: I have installed dbt through pip. It's under the Script folder in the individual python environment. If I have not activated the python environment, it will not work.

A: I think this is happening because VS Code is using PowerShell as the default terminal, if you run in cmd like the first screenshot you shared below, it should behave as expected, for this you can use ctrl + shift + p in VS Code, and at the bar type Open Settings (JSON) in there you can add the following:
"terminal.integrated.shell.windows": "C:\\Windows\\System32\\cmd.exe"

This way VS Code will use CMD instead of PowerShell to run commands in Windows.

A: Python on Windows is tricky. Did you install Anaconda already? How about the Visual Studio Code Python extension? You may want to add the Python install that has dbt to your PATH variable.
https://docs.python.org/3.9/using/windows.html#configuring-python