text:
Q: How to create operating system using Java? Is there anyway I could create a operating system using java? Is there anyway I could embed the windows java library so I could develop my OS with things like JFrame, JFileChooser, JTextArea, etc? Or would I be better off In the long run learning C or C++?

A: Short answer: no.
First, Java using the OS to run your java code. A lot of the windows are using the OS to render.
Second, you should note that most, if not all, OS are started with machine/assembly code. If you have the goal of making an OS yourself and completely from scratch, you will need to learn assembly and there is no way around that. Luckily, you only need to write a small amount of assembly before you can get something written in C or C++ to run (and note that Java runtime is written in C/C++).
Since Java using the OS' native code to manage/render windows and controls, and assuming you've compiled Java from source without using said libraries, if you wrote your only code to handle all of the graphics of rendering controls and windows then yeah, suppose you could write a majority of the the OS in java once you got the basic stuff done. You should know that you wouldn't be able to use much of javafx or swing for anything since they rely on the OS.
Finally, I would strongly recommend going to college and getting a solid education , then I would further recommend working for a company with a team of experience programmers for at least 4 years (at minimum) before you take on such a herculean task as creating an OS. You aren't going to write a useful OS by yourself and with the amount of knowledge you seem to have in any language.
EDIT:
There are machines who's microprocessor natively understand java bytecode as mention in other answer. However an OS written for that processor would only work on that processor and would not be widely distribute atm. For learning purposes, you would be better just sticking with JVM on whatever you have access to now in you really don't gain much.
Also, learning to write an OS is a task I encourage all programmers to learn. It will give you a better understanding of how computers work inside and out. From a programming point of view, in relation to high level languages, you don't lose or gain much by using one language over another. Some argue (and perhaps I agree) that Java doesn't use pointer and so that is lost to most however if your intent is to do everything in Java, then all you need to understand is Java.
As a matter of opinion, I would argue you are better off learning every programming language you come across, and every language that are the predecessors to those. I don't mean become a master programmer in BCPL or COBOL or anything on that level, but at least research, learn how to do basic things and know they exist and (in most cases) can do everything every other language can do.
My professional advice, learn and master what ever language your employer would have you use. If you change jobs be prepared to learn something new. Not all jobs use Java, or C++ so if you limit yourself to just Java or even C/C++ you will not be as marketable on the job market.

A: Yes, you can.
Many options available to do so:

*

*JNI provides communication of Java code with native code. you can develop boot loader in native code, but UI in Java

*Java Processor: implementation of JVM in hardware

*Java Optimized Processors

*Embedded Java

*picoJava

and so on..
There's nothing that can stop you from developing OS in Java. You can find many OSes written in Java: from CISCO to NASA...
However, even creating a tiny OS requires a lot of effort.


text:
Q: How do I install Apigility if I don't have Composer? I have a hosting in shared web server. I don't have Composer there. How can I make it run, the Apigility?
Edit: I don't have administrative right there.

A: 1) You can install the ZF2 skeleton application first using git submodules. Take a look at the install section of the ZF2 skeleton application.
2) You can take a look at all the dependencies for Apigility in the composer.json file. https://github.com/zfcampus/zf-apigility/blob/master/composer.json you can start installing each dependencies using git submodules in to your vendor directory and activate them in the application.config.php file.
3) launch the php built in webserver ( $ php -S 0.0.0.0:8080 -t public/ public/index.php )
It is recommended to use php 5.4.* or later to use apigility.
I wrote a blog post showing how to include the apigility in to your exiting zf2 project (I am using the composer there), see if that helps.
http://www.ttiaf.com/2013/10/install-apigility-in-to-your-existing.html

A: step1;
download from Github
then just go to your project_root_folder/config/development.config.php
create a new php file with the path shown above.
<?php

    return array(
    // Development time modules
    'modules' => array(
        'ZFTool',
        'ZF\Apigility\Admin',
        'ZF\Apigility\Example',
    ),
    // development time configuration globbing
    'module_listener_options' => array(
        'config_glob_paths' => array('config/autoload/{,*.}{global,local}-development.php')
    )
);

A: *

*Install Composer on the machine you are using for uploading to your shared host.

*Download the dependencies there.

*Upload the whole directory tree to the server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to parse javascript/jquery to echo / execute within/after ajax result Ajax returns all expected html result from php code, except the javacript and jQuery inside the "script" tags
 var frm = $('#cell');
    frm.submit(function (ev) {
        $.ajax({
            type: "POST",
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function (html) {

    //Create jQuery object from the response HTML.
    var $return=$(html);
    //Query the jQuery object for the values
    var oneval = $return.filter('#cellWidthSlider').html();
    alert(oneval);

                $("#cellWidthDiv").html(oneval);

            }
        });

        ev.preventDefault();
    });

I have tried to append to head, but the jQuery code would execute only - before the elements.
var $response=$(html);

$("head").append($response);

var oneval = $response.filter('#cellWidthSlider').html();

A: As much as I've been afraid of JSON, it was actually much simpler than I thought and it really took me only around 3 hours to get the general understanding, feeling good, now so so much started to look familiar in ajax and jQuery:)
So The changes I've done...
Instead of generating js within external php I have created array with values e.g.:
$result = array(
                array(
                       'prevCellId' => $prevCellId,
                       'prevCellWidth' => $prevCellWidth,
                       'thisCellId' => $latestCellId,
                       'thisWidth'=>$thisWidth,
                       'thisRowId' => $thisRowId,
                       'thisRowOrder' => $thisRowOrder,
                       'maxWidth' => $maxWidth,
                       'prevCellRowOrder' => $prevCellRowOrder));

echo json_encode($result);

Then, after long search I've managed to implement json values in my jQuery function:
    $.getJSON( "cellWidth.php", function( json ) {
                   $.each(json, function(i, item) {
                   $('#slider').slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+'', slide: handleSliderChange,   stop: sendNew});
                   var $slider = $("#slider").slider({ max:''+item.maxWidth+'',min: 10,step: 5, value:''+item.thisWidth+''});
                   })
 })

So simply used keyword "item." + "names of arrays" to "echo" / "use values" within jQuery - in this case this is a jQuery slider :))


text:
Q: All Possible Pairs of 18 I will be having 18 Students in my class this year. I'd like to have them learn in pairs rotating every day with a different student in the class. What are all the possible pairings.
for example on Day 1: Student 1 learns with 2/ 3 with 4/5 with 6 etc etc
I need an 18 day rotation for this please
Thanks

A: This is equivalent to asking in how many ways a $2n-$element set  can be partitioned into two-element subsets. Let $T_{2n}$ be that number.
Let's define
$T_0 = 1$
$T_2$ clearly equals $1$.
We can express $T_{2(n+1)}$ in terms of $T_{2n}$ and $T_{2(n-1)}$?
Let's consider the set with $2n+2$ elements $\{1,2,3,\dots,2n\}\cup\{a,b\}.$
If we choose $\{a,b\}$ to be in the partition, then we know that there are $T_{2n}$ ways to partition the remaining $2n$ elements.
We can choose partition elements of the form
$\{a,u\}$ and $\{b,v\}$ where $1 \le u \ne v \le 2n$
in $2n(2n-1)$ ways and there will always be $T_{2n-2}$ ways to partition the remaining $2n-2$ elements.
This implies that
$$T_{2(n+1)} = T_{2n} + 2n(2n-1)T_{2n-2}$$
The OEIS points out that
$$T_{2n} = (2n-1)!! = (2n-1)(2n-3)\cdots1$$
In either case
$T_{18} = 34459425$


text:
Q: Training Accuracy Stuck at 0.50+- I have been working on a comparison of the CNN and RNN deep learning models for sentimental analysis.
I built the CNN following this guide:
https://machinelearningmastery.com/develop-word-embedding-model-predicting-movie-review-sentiment/ , and I got an accuracy of 90+ in CNN.
However, when I tried to recreate a LSTM model, the accuracy seems to hover around 0.5+-, and doesnt seems to improve over time. I wonder what is wrong with my codes I the only thing I have done is to replace the existing CNN model with LSTM in the model.add section. I have tried to change the loss from "binary" to "categorical", and different activation function. It still doesn't resolve the issue.
CNN RESULTS
LSTM RESULTS
This is my CNN model which worked fine
 # load the vocabulary

    vocab_filename = 'vocab.txt'
    vocab = load_doc(vocab_filename)
    vocab = vocab.split()
    vocab = set(vocab)

    # load all training reviews

    positive_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/pos', vocab, True)
    negative_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/neg', vocab, True)
    train_docs = negative_docs + positive_docs

    # create the tokenizer

    tokenizer = Tokenizer()

    # fit the tokenizer on the documents

    tokenizer.fit_on_texts(train_docs)

    # sequence encode

    encoded_docs = tokenizer.texts_to_sequences(train_docs)

    # pad sequences

    max_length = max([len(s.split()) for s in train_docs])
    Xtrain = pad_sequences(encoded_docs, maxlen=max_length, padding='post')

    # define training labels, TRAINING DATASET

    ytrain = array([0 for _ in range(900)] + [1 for _ in range(900)])

    # load all test reviews

    positive_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/pos', vocab, False)
    negative_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/neg', vocab, False)
    test_docs = negative_docs + positive_docs

    # sequence encode

    encoded_docs = tokenizer.texts_to_sequences(test_docs)

    # pad sequences

    Xtest = pad_sequences(encoded_docs, maxlen=max_length, padding='post')

    # define test labels, TESTING DATASET

    ytest = array([0 for _ in range(100)] + [1 for _ in range(100)])

    # define vocabulary size (largest integer value)

    vocab_size = len(tokenizer.word_index) + 1
    print(vocab_size)

    # define model

    model = Sequential()
    model.add(Embedding(vocab_size, 100, input_length=max_length))
    model.add(Conv1D(filters=32, kernel_size=8, activation='relu'))
    model.add(MaxPooling1D(pool_size=2))
    model.add(Dropout(0.5))
    model.add(Flatten())
    model.add(Dense(10, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    print(model.summary())

    # compile network

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

    # fit network

    history=model.fit(Xtrain, ytrain, epochs=10, verbose=2)

    # evaluate

    loss, acc = model.evaluate(Xtest, ytest, verbose=0)
    print('Test Accuracy: %f' % (acc*100))
    print(history.history.keys())

#summarize history for accuracy

    plt.plot(history.history['accuracy'])
    plt.plot(history.history['val_accuracy'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()

# summarize history for loss

    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()

This is my current LSTM model
    # load the vocabulary

    vocab_filename = 'vocab.txt'
    vocab = load_doc(vocab_filename)
    vocab = vocab.split()
    vocab = set(vocab)

    # load all training reviews

    positive_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/pos', vocab, True)
    negative_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/neg', vocab, True)
    train_docs = negative_docs + positive_docs

    # create the tokenizer

    tokenizer = Tokenizer()

    # fit the tokenizer on the documents

    tokenizer.fit_on_texts(train_docs)

    # sequence encode

    encoded_docs = tokenizer.texts_to_sequences(train_docs)

    # pad sequences

    max_length = max([len(s.split()) for s in train_docs])
    Xtrain = pad_sequences(encoded_docs, maxlen=max_length, padding='post')

    # define training labels, TRAINING DATASET

    ytrain = array([0 for _ in range(900)] + [1 for _ in range(900)])

    # load all test reviews

    positive_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/pos', vocab, False)
    negative_docs = process_docs('C:/Users/zenhu/OneDrive/Desktop/Final Year Project/archive/review_polarity/txt_sentoken/neg', vocab, False)
    test_docs = negative_docs + positive_docs

    # sequence encode

    encoded_docs = tokenizer.texts_to_sequences(test_docs)

    # pad sequences

    Xtest = pad_sequences(encoded_docs, maxlen=max_length, padding='post')

    # define test labels, TESTING DATASET

    ytest = array([0 for _ in range(100)] + [1 for _ in range(100)])

    # define vocabulary size (largest integer value)

    vocab_size = len(tokenizer.word_index) + 1

    # define model

    model = Sequential()
    model.add(Embedding(vocab_size, 100, input_length=max_length))
    model.add(LSTM(units=100))
    model.add(Dense(10))
    model.add(Dense(1, activation='sigmoid'))
    print(model.summary())

    # compile network

    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

    # fit network

    history=model.fit(Xtrain, ytrain, epochs=10, verbose=2)

    # evaluate

    loss, acc = model.evaluate(Xtest, ytest, verbose=0)
    print('Test Accuracy: %f' % (acc*100))

    print(history.history.keys())`

#summarize history for accuracy

    plt.plot(history.history['accuracy'])
    plt.plot(history.history['val_accuracy'])
    plt.title('model accuracy')
    plt.ylabel('accuracy')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()

# summarize history for loss

    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.title('model loss')
    plt.ylabel('loss')
    plt.xlabel('epoch')
    plt.legend(['train', 'test'], loc='upper left')
    plt.show()

A: The problem is in your LSTM layer. It is not returning a sequence of the same length. You must set return_sequences=True when stacking layer so that the second layer has a three-dimensional sequence input. After adding return_sequences = True parameter in your LSTM layer, it will give you around 90% accuracy for sure.
model.add(LSTM(units=100, return_sequences = True))


text:
Q: SyntaxError EOL while scanning string literal I'm trying to use this Python one liner script:
python -c 'import hashlib,hmac; hash=raw_input("Hash > "); salt=raw_input("Salt > "); print "HMAC",hmac.new(salt,hash,hashlib.sha1).hexdigest().upper()'

And it gives me this error:
File "<string>", line 1
    'import
          ^
SyntaxError: EOL while scanning string literal

I'm using Windows 10 64bit and I'm working with ConEmu.

A: You can use single or double quotes within Python, but at the command-line terminal (cmd or Powershell) you have to use double quotes to enclose the argument you wish to send. Enclose it with double quotes, and use single quotes within it:
python -c "import hashlib,hmac; hash=raw_input('Hash > '); salt=raw_input('Salt > '); print 'HMAC',hmac.new(salt,hash,hashlib.sha1).hexdigest().upper()"


text:
Q: Parameterised Query Visual Basic I've been having trouble getting parametrised queries to work. The code is working fine without parameterised SQL.
The error I'm getting is Must declare the scalar variable @RegNo.
Dim conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\dbsBank.mdf;Integrated Security=True")

Dim queryString As String = "SELECT PAC FROM Customers WHERE Registration_No = @RegNo"

Dim cmd As New SqlCommand(queryString, conn)
Dim param As SqlParameter = New SqlParameter("@RegNo", SqlDbType.Int)
param.Value = mtbPassword.Text
cmd.Parameters.Add(param)

Dim adap As New SqlDataAdapter(queryString, conn)

dTable = New DataTable

Try
    adap.Fill(dTable)
Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

A: You build your Command object but never use it. So your DataAdapter never has the parameter definition.
Replace
Dim adap As New SqlDataAdapter(queryString, conn)

with
Dim adap As New SqlDataAdapter(cmd)

This should most likely solve your problem


text:
Q: How to indicate that a method was unsuccessful I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there.
Ideally I would like the methods to 'look' similar; one solution could be to define them as
public Point CalculatePoint(... out Boolean boSuccess);
public List<Point> CalculateListOfPoints(... out Boolean boSuccess);

or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive.
Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something...
What is best practice?
Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected.

A: Why would they fail? If it's because of something the caller has done (i.e. the arguments provided) then throwing ArgumentException is entirely appropriate. A Try[...] method which avoids the exception is fine.
I think it's a good idea to provide the version which throws an exception though, so that callers who expect that they will always provide good data will receive a suitably strong message (i.e. an exception) if they're ever wrong.

A: Another alternative is to throw an exception.  However, you generally only want to throw exceptions in "exceptional cases".
If the failure cases are common (and not exceptional), then you've already listed out your  two options.  EDIT: There may be a convention in your project as how to handle such non-exceptional cases (whether one should return success or the object).  If there is no existing convention, then I agree with lucasbfr and suggest you return success (which agrees with how TryParse(...) is designed).

A: Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not
public bool CalculatePoint(... out Point result);
I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries).

A: If the failure is for a specific reason then I think its ok to return null, or bool and have an out parameter.  If however you return null regardless of the failure then I don't recommend it.  Exceptions provide a rich set of information including the reason WHY something failed, if all you get back is a null then how do you know if its because the data is wrong, you've ran out of memory or some other weird behavior.
Even in .net the TryParse has a Parse brother so that you can get the exception if you want to.
If I provided a TrySomething method I would also provide a Something method that threw an exception in the event of failure.  Then it's up to the caller.

A: The model I've used is the same one MS uses with the TryParse methods of various classes.
Your original code:
public Point CalculatePoint(... out Boolean boSuccess);
public List CalculateListOfPoints(... out Boolean boSuccess);
Would turn into
public bool CalculatePoint(... out (or ref) Point CalculatedValue);
public bool CalculateListOfPoints(... out (or ref) List CalculatedValues);
Basically you make the success/failure the return value.

A: To summarise there are a couple of approaches you can take:

*

*When the return type is a value-type, like Point, use the Nullable feature of C# and return a Point? (aka Nullable), that way you can still return null on a failure

*Throw an exception when there's a failure. The whole argument/discussion regarding what is and isn't "exceptional" is a moot point, it's your API, you decide what's exceptional behaviour.

*Adopt a model similar to that implemented by Microsoft in the base types like Int32, provide a CalculatePoint and TryCalculatePoint (int32.Parse and int32.TryParse) and have one throw and one return a bool.

*Return a generic struct from your methods that has two properties, bool Success and GenericType Value.

Dependent on the scenario I tend to use a combination of returning null or throwing an exception as they seem "cleanest" to me and fit best with the existing codebase at the company I work for. So my personal best practice would be approaches 1 and 2.

A: It mostly depends on the behavior of your methods and their usage.
If failure is common and non-critical, then have your methods return a boolean indicating their success and use an out parameter to convey the result. Looking up a key in a hash, attempting to read data on a non-blocking socket when no data is available, all these examples fall in that category.
If failure is unexpected, return directly the result and convey errors with exceptions. Opening a file read-only, connecting to a TCP server, are good candidates.
And sometimes both ways make sense...

A: Return Point.Empty. It's a .NET design patter to return a special field when you want to check if structure creation was successful. Avoid out parameters when you can.
public static readonly Point Empty

A: A pattern that I'm experimenting with is returning a Maybe. It has the semantics of the TryParse pattern, but a similar signature to the null-return-on-error pattern.
I'm not yet convinced one way or the other, but I offer it for your collective consideration. It does have the benefit of not requiring a variable to defined before the method call to hold the out parameter at the call site of the method. It could also be extended with an Errors or Messages collection to indicate the reason for the failure.
The Maybe class looks something like this:
/// <summary>
/// Represents the return value from an operation that might fail
/// </summary>
/// <typeparam name="T"></typeparam>
public struct Maybe<T>
{
    T _value;
    bool _hasValue;

    public Maybe(T value)
    {
        _value = value;
        _hasValue = true;
    }

    public Maybe()
    {
        _hasValue = false;
        _value = default(T);
    }

    public bool Success
    {
        get { return _hasValue; }
    }

    public T Value
    {
        get
            { // could throw an exception if _hasValue is false
              return _value;
            }
    }
}

A: I would say best practice is a return value means success, and an exception means failure.
I see no reason in the examples you provided that you shouldn't be using exceptions in the event of a failure.

A: Using an exception is a bad idea in some cases (especially when writing a server). You would need two flavors of the method. Also look at the dictionary class for an indication of what you should do.
// NB:  A bool is the return value.
//      This makes it possible to put this beast in if statements.
public bool TryCalculatePoint(... out Point result) { }

public Point CalculatePoint(...)
{
   Point result;
   if(!TryCalculatePoint(... out result))
       throw new BogusPointException();
   return result;
}

Best of both worlds!

A: The bool TrySomething() is at least a practice, which works ok for .net's parse methods, but I don't think I like it in general.
Throwing an exception is often a good thing, though it should not be used for situations you would expect to happen in many normal situations, and it has an associated performance cost.
Returning null when possible is in most cases ok, when you don't want an exception.
However - your approach is a bit procedural - what about creating something like a PointCalculator class - taking the required data as parameters in the constructor? Then you call CalculatePoint on it, and access the result through properties (separate properties for Point and for Success).

A: You don't want to be throwing exceptions when there is something expected happening, as @Kevin stated exceptions are for exceptional cases.
You should return something that is expected for the 'failure', generally null is my choice of bad return.
The documentation for your method should inform the users of what to expect when the data does not compute.

A: We once wrote an entire Framework where all the public methods either returned true (executed successfully) or false (an error occurred).  If we needed to return a value we used output parameters.  Contrary to popular belief, this way of programming actually simplified a lot of our code.

A: Well with Point, you can send back Point.Empty as a return value in case of failure. Now all this really does is return a point with 0 for the X and Y value, so if that can be a valid return value, I'd stay away from that, but if your method will never return a (0,0) point, then you can use that.

A: Sorry, I just remembered the Nullable type, you should look at that. I am not too sure what the overhead is though.


text:
Q: How to detect all authentication challenges originated from uiwebview page I have UIWebView page on which there is a button of Login which does login using basic authentication and HTTP POST method call to a server api https://www.abc.com/login. I am not able to detect the the authentication challenge for it through NSURLConnection as specified here
Display Authentication Challenge iOS. Because of the reason that authentication request is not the request that is originally loaded in the webview.
The hack to this can be when authentication request is made load a custom url in webview detect that in iOS code and start a new request in iOS with the URL to  https://www.abc.com/login which works fine. But is there any other way to do it?


text:
Q: Access using ExceL VBA to format data as Excel Table See this question. It shows a solution for formatting excel data as a table in Excel.
The code is
  Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

I am trying to use this code in Access VBA where I create an Excel output file with Access data then I want to format it similarly. Here is my code.
Dim objXL As Object
Dim objWorkbook As Object
Dim objWorkSheet As Object
Dim sourcefilepath As String
Dim tbl As ListObject
Dim rng As Range

Set objXL = New Excel.Application
objXL.Application.Visible = False

sourcefilepath = Application.CurrentProject.Path & "\CF Break Report " & Format(Date, "mm-dd-yy") & ".xls"
Set objWorkbook = objXL.Application.Workbooks.Open(FileName:=sourcefilepath)
Set objWorkSheet = objWorkbook.Worksheets("_400_CF_BREAK_LOG")

Set rng = objWorkSheet.Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell))
Set tbl = objWorkSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"

Update: The line that is failing is
   Set rng = objWorkSheet.Range(Range("A1"), ActiveCell.SpecialCells(xlLastCell))

With the error "application-defined or object-defined error

A: Try:
Set rng = objWorkSheet.Range(objWorkSheet.Range("A1"), ActiveCell.SpecialCells(xlLastCell))
Worked for me.

A: Found an answer hidden away here
With xlWB.Sheets("Summary")
Set rng = .Cells(1, 1).CurrentRegion
End With
Set tbl = xlWS.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium2"
tbl.ShowTotals = True


text:
Q: How to redirect to stdin in bash but with a delay between each line? The platform I am working is Ubuntu 18.04. I have a binary program (so I cannot change the program) say foo and it reads commands line by line from stdin. I have the commands in a file named 'commands' and I want to run foo with redirecting commands to its stdin. So far I know I can do this just by simply pipe the output of the file to foo like cat commands | foo.
However I would like to give the commands one by one with some delay e.g. 10 seconds. So foo may wait for the input on the stdin and I do not care. How can I do that in bash? So basically, I want to give the inputs like interactively but not actually interactive, it is automatically.

A: With bash and a loop:
while read -r line; do echo "$line"; sleep 10; done < commands | foo


text:
Q: How to enable user_xattr in Mint Cinnamon? I just installed Netflix Desktop on my Cinnamon Mint, but I can't start it. When I run the program, I get the following message:

It appears that you do not have extended file system attributes enabled. Please enable the user_xattr option for your filesystem and try again.

I tried to edit the fstab file as told in a couple different posts, but they don't work; I don't have a line that looks like this in my file:
UUID=94f7fc1e-fa27-4b24-99f3-4b461665a4a4       /       ext4    errors=remount-ro,user_xattr       0       1

And when I add it and restart, nothing changes.

A: You need to leave your UUID for your hard drive in that modification. This UUID in the example is different than yours:
UUID=94f7fc1e-fa27-4b24-99f3-4b461665a4a4

An entry for your / should've already been present for your HDD.
If you're unsure what UUID your HDD has you can use the blkid command to get the UUIDs' for your HDDs.
Example
$ sudo blkid
/dev/sda1: UUID="1f2832de-ee34-461f-8fb1-cb86ffde8d44" TYPE="ext2"
/dev/sda5: UUID="6qwe112-dGB3-vCp2-XibP-qsmE-nWbs-E123eJ" TYPE="LVM2_member"
/dev/mapper/ubuntu-root: UUID="5b6417237-ab46-1234-11f9-81dcf2111129" TYPE="ext4"
/dev/mapper/ubuntu-swap_1: UUID="5ab3q12h-26a7-85qw-12fd-57e7c95e2232" TYPE="swap"

Your fstab file may have a line like this:
/dev/mapper/ubuntu-root /               ext4    errors=remount-ro 0       1

You should change the options from this errors=remount-ro to this errors=remount-ro,user_xattr.


text:
Q: Wordpress - Single Post full size images I'm looking for a way to have ALL of my single post pages (single.php) show the full size image regardless of the custom sizes i've posted for my home index page.
Amongst my many tries and fails i attempted this featured image solution but it didn't really work for my purposes.
http://voodoopress.com/2011/04/woking-with-featured-image-in-wordpress/
Is there a plugin for this that maybe I don't know about?
My PHP knowledge is limited to say the least.
Is there a php code that i can put into the single.php file to make this happen?
Any help is greatly appreciated .
Thanks.

A: You can pass a size parameter of 'full' to the the_post_thumbnail() function like this
<?php the_post_thumbnail('full'); ?>


text:
Q: How to display route between two makers in map using javascript I have facing problem while creating route map with multiple Latitude and Longitude
, I tried lot of ways for creating route map but I am getting marker places only,
it is not display route between two markers on map.
I need to route  between two markers on map for multiple Latitude and Longitude,
I have posted below code which i tried ,
var MapPoints = '[{"address":{"lat":"23.7012517","lng":"86.0591489"},"title":"Dalmia Cement,JHARKHAND"},{"address":{"lat":"24.5246","lng":"84.2845"},"title":"NAVIN CEMENT STORE"},{"address":{"lat":"24.2493788","lng":"83.9261005"},"title":"SAKSHI TRADERS"}]';
      var directionsDisplay;
      var directionsService = new google.maps.DirectionsService();
      var map;

      function initialize() {
          var pointA = new google.maps.LatLng(23.7012517, 86.0591489);
        if (jQuery('#map').length > 0) {
            map = new google.maps.Map(document.getElementById('map'), {
                 zoom: 15,
                center: pointA,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scrollwheel: false
              });

            directionsDisplay = new google.maps.DirectionsRenderer({
                map: map,
                suppressMarkers: true
              });
          var locations = jQuery.parseJSON(MapPoints);

          directionsDisplay.setMap(map);

          var infowindow = new google.maps.InfoWindow();
          var shippingCoordinates = [];
          var bounds = new google.maps.LatLngBounds();

          for (i = 0; i < locations.length; i++) {
            marker = new google.maps.Marker({
              position: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
              map: map
            });
            shippingCoordinates.push(marker.getPosition());
            bounds.extend(marker.position);

            google.maps.event.addListener(marker, 'click', (function(marker, i) {
              return function() {
                infowindow.setContent(locations[i]['title']);
                infowindow.open(map, marker);
              }
            })(marker, i));
          }

          map.fitBounds(bounds);

          // directions service configuration
          var start = shippingCoordinates[0];
          var end = shippingCoordinates[shippingCoordinates.length - 1];
          var waypts = [];
          for (var i = 1; i < shippingCoordinates.length - 1; i++) {
            waypts.push({
              location: shippingCoordinates[i],
              stopover: true
            });
          }
          finalRootMap(start, end, waypts);
        }
      }

      function finalRootMap(start, end, waypts) {
        var request = {
          origin: start,
          destination: end,
          waypoints: waypts,
          optimizeWaypoints: true,
          travelMode: google.maps.TravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            var route = response.routes[0];
            var summaryPanel = document.getElementById('directions_panel');
            summaryPanel.innerHTML = '';
            // For each route, display summary information.
            for (var i = 0; i < route.legs.length; i++) {
              var routeSegment = i + 1;
              summaryPanel.innerHTML += 'Route Segment: ' + routeSegment + '
';
              summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
              summaryPanel.innerHTML += route.legs[i].end_address + '
';
              summaryPanel.innerHTML += route.legs[i].distance.text + '

';
            }
          }
        });
      }
      google.maps.event.addDomListener(window, 'load', initialize);

A: use Directions Waypoints
Reference https://developers.google.com/maps/documentation/javascript/examples/directions-waypoints
var waypts = [];

for (i = 0; i < locations.length; i++) {
     waypts.push({
        location: new google.maps.LatLng(locations[i].address.lat, locations[i].address.lng),
        stopover: true
     });
}

directionsService.route({
  origin: new google.maps.LatLng(locations[0].address.lat, locations[0].address.lng),
  destination: new google.maps.LatLng(locations[locations.length - 1].address.lat, locations[locations.length - 1].address.lng),
  waypoints: waypts,
  optimizeWaypoints: true,
  travelMode: 'DRIVING'
}, function(response, status) {
  if (status === 'OK') {
    directionsDisplay.setDirections(response);
    var route = response.routes[0];
  } else {
    window.alert('Directions request failed due to ' + status);
  }
});


text:
Q: Clarifying responsibility with named parameters More and more often recently I've wanted to do something like the following:
def refund(amount, yes_i_know_i_need_to_handle_credit):
    __refund(amount)

total = 600
card_total = 400
user_credit_refund = total - card_total

# This raises an error
refund(total)

# This works
refund(card_total, True)

user.print_credit += user_credit_refund

Pseudocode, obviously, but the issue I want to point out is that the refund function without the second parameter is a leaky abstraction - the user has to look inside it to figure out whether it handles user credit refunds. If they passed the full total to the refund method, they would refund more than the user paid in real money.
The reason I feel like this is useful is to clarify changes that are happening during a refactor. The refund function used to handle refunding user credit, but I'm decoupling the billing stuff from the product manipulation, so the refund function no longer handles print credit - the user of the function has to do that part separately.
I've never seen this design pattern anywhere, though I have seen the like in more strongly typed languages for type checking, etc. And there's no purely programmatic reason for it, since an interface should be well documented and just do what it does. But historically, the behavior of this function has changed, and I want to enforce remembering that.
So what do you all think? Idiocy? Useful? Achieved some other way?

A: Don't require an argument which has no purpose other than forcing the user to pass a useless value. (Imagine how annoying that would be a year from now when everyone has updated their code but still forced to kowtow to the gods of a nagging API.)
Changing the API is always painful since it will break user's code, and is bound to cause some confusion.
However, if you are willing to suffer the pain to achieve a better code base, then I would suggest changing the function name instead of adding a parameter:
def handle_refund_and_credit(total, card_total, user):
    total = 600
    card_total = 400
    user_credit_refund = total - card_total
    handle_refund(total)
    user.print_credit += user_credit_refund

def handle_refund(amount):
    __refund(amount)

Since there is no function named refund, the user will be force to select the function they need: either handle_refund_and_credit, or just handle_refund. They'll have to research what each one does, and they'll be guided by the list of required arguments.


text:
Q: Excel Ribbon Macro not enabled We have custom ribbons on many Excel workbooks. Occasionally we experience an error message from Excel saying the '_getEnabled' macro is disabled (see image). This message appears for every ribbon control that uses a macro to control the enabled property.

The xml in the ribbon is (some names are redacted):
<button id="name_btn" size="large" image="imagename" label="somelabel" getEnabled="VBA_####.######_getEnabled" onAction="VBA_####.######_onAction"/>

and the VBA is:
Sub ######_getEnabled(control As IRibbonControl, ByRef returnedVal)
    returnedVal = CheckPermissions("SomeName")
End Sub

Has anyone else seen this error? The error messages appear when another workbook is the active workbook but Excel seems to be trying to refresh the ribbon controls for the workbook that contains the code. As mentioned earlier, this happens occasionally and we have not seen any identifiable pattern.

A: You can replicate the behaviour if you set a breakpoint in one of the callbacks in VBA (GetImage, GelLabel, GetEnabled etc.) and when the code breaks you go and activate another workbook. Finally, when you continue running the code (ex. press F5) the error will occur.
You can force a ribbon refresh using the ribbon .Invalidate method (if you previously saved the ribbon object). You can save the ribbon object by defining an onLoad callback:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="InitRibbon">

with this in VBA:
Private moduleLevelRibbonObject As IRibbonUI

Public Sub InitRibbon(ribbon As IRibbonUI)
    Set moduleLevelRibbonObject = ribbon
End Sub

Calling moduleLevelRibbonObject.Invalidate will refresh the ribbon (if state was not lost - but that is a different topic).
Quick fix that I've found. Just add something like this:
If Not ThisWorkbook Is ActiveWorkbook Then ThisWorkbook.Activate

to all your callbacks, so that when the callback returns to the caller, the correct workbook is active and the next callback is called correctly. Add the line preferably at the end of the method just before End Sub/Function. Example:
Public Sub GetPressed(ctrl As IRibbonControl, ByRef isChecked As Variant)
    Select Case ctrl.ID
    Case "AdminMode"
        isChecked = IsAdminModeOn()
    Case Else
        Debug.Print "Toggle <" & ctrl.ID & "> does not have a return " _
            & "boolean for GetPressed!"
    End Select
    If Not ThisWorkbook Is ActiveWorkbook Then ThisWorkbook.Activate
End Sub

Edit #1
When forcing the refresh of the ribbon using the IRibbonUI.Invalidate method then there is also a need to activate the workbook before Invalidate is called.
Best is to have a separate method:
'Utility - avoids errors when callbacks are called on the wrong workbook
Private Sub ActivateBook()
    If Not ThisWorkbook.IsAddin Then ThisWorkbook.Activate
End Sub

that is called before any Invalidate call and also at the end of each of the callbacks.


text:
Q: How to write preference values with androidx.preference:preference:1.1.1 in kotlin? I know that preference operation has upgraded to androidx.preference:preference:1.1.1
I can Code A to read the preference values "signature".
How can I write a new value to the preference values "signature" with androidx.preference:preference:1.1.1 in kotlin?
Code A
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity_context)
val name = sharedPreferences.getString("signature", "")

A: Use it like the old preference library:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity_context)
sharedPreferences.edit().putString("signature", value).apply()

Just make sure that you import from:
import androidx.preference.PreferenceManager;


text:
Q: Pagination not working because of two select statements $today = date('D, d M, Y');
$sql = "SELECT * FROM table WHERE date = '$today'";
if ($_POST!="") {
    $mydate = mysql_real_escape_string($_POST['datepicker']);
    if ($mydate != "") {
        $sql = "SELECT * FROM table WHERE date = '$mydate'";
    }
}
$num_results_per_page = 8;
$num_page_links_per_page = 5;
$pg_param = "";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param);
if($pg_error == '')
{
    if(mysql_num_rows($pg_result) > 0)
    {
        while($data = mysql_fetch_assoc($pg_result))
        {
            echo "";
        }
        echo "
". $pagination_output;
    }
    else
    {
        echo "No Data.";
    }
}
else
{
    echo $pg_error;
}

For the above code the pagination is not working properly. I am thinking that it is because of two select statements. It will be OK if we can combine those two. Any suggestions? How can I combine those two select statements?
Pagination is working correctly for select $today, but not working properly for select $mydate. For example if the user clicks page number two in select $mydate, its again going to select $today.
pagination.php
$pg_error = '';
$pg_result = '';
$pagination_output = '';
$max_pages = '';
$page_id = '';
$page_numbers_per_page = '';
$pg_user_param = '';
function pagination($sql, $num_results_per_page, $num_page_links_per_page, $pg_param)
{
global $pg_error, $pg_result, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$user_sql = $sql;
$page_numbers_per_page = $num_page_links_per_page;
$results_per_page = $num_results_per_page;
$pg_user_param = $pg_param;
$all_results = mysql_query($user_sql);
if($all_results)
{
    if(empty($all_results))
    {
        $total_results = 0;
    }
    else
    {
        $total_results = mysql_num_rows($all_results);
    }
    $max_pages = ceil($total_results / $results_per_page);
    if(isset($_GET['page_id']))
    {
        $page_id = (int) $_GET['page_id'];

        if($page_id > $max_pages || empty($page_id))
        {
            $page_id = 1;
        }
    }
    else
    {
        $page_id = 1;
    }
    $page_id_temp = ($page_id - 1) * $results_per_page;
    $sql_offset = $page_id_temp;
    $user_sql .= " limit $sql_offset, $results_per_page";
    $pg_result = mysql_query($user_sql);
    Create_Links();
}
else
{
    $pg_error = 'Error with the sql query you entered: '.mysql_error();
}
}
function Create_Links()
{
global $pagination_output, $max_pages, $page_id, $page_numbers_per_page, $pg_user_param;
$pg_page_name = htmlspecialchars($_SERVER['PHP_SELF'] );

if($max_pages > 1)
{
    if($page_id > 1)
    {
        $first_link = 'First ';
    }

    if($page_id < $max_pages)
    {
        $last_link = 'Last ';
    }
    $pre_id = $page_id - 1;
    if($pre_id != 0)
    {
        $pre_link = 'Previous ';
    }
    $next_id = $page_id + 1;
    if($next_id <= $max_pages)
    {
        $next_link = 'Next ';
    }

    if($page_id >= $page_numbers_per_page)
    {

        $start_point = ($page_id - $page_numbers_per_page) + 2;
    }
    else
    {
        $start_point = 1;
    }

    $loop_num = ($start_point + $page_numbers_per_page) - 1;
    if($loop_num > $max_pages)
    {
        $loop_num = $max_pages;
    }
    $pagination_output = '
 ';
    $pagination_output .= $first_link;
    $pagination_output .= $pre_link;
    for($i = $start_point; $i <= $loop_num; $i++)
    {
        if($i == $page_id)
        {
            $pagination_output .= ''.$i.' ';
        }
        else
        {
            $pagination_output .= ''.$i.' ';
        }
    }
    $pagination_output .= $next_link;
    $pagination_output .= $last_link;
    $pagination_output .= '

';
}
}
?>

A: If pagination is working for "$today" then it must be the POST input value - are you making sure you're getting a proper date that mysql can understand?
the format should basically match what's in "$today".

A: I'd imagine that the second click is not POSTing myDate to the next page. The next page then sees nothing in POST and uses today.
To avoid this you could also check for GETs of the datepicker and then pass myDate using GET.
Edit: Clarification on updating the code to use GET
The check on mydate should be changed to something like:
if ($_REQUEST!="") {
    $mydate = mysql_real_escape_string($_REQUEST['datepicker']);
    if ($mydate != "") {
        $sql = "SELECT * FROM table WHERE date = '$mydate'";
    }
}

Which means that if the datepicker is from a GET request we still grab it.
Create_Links() should be changed to add "&datepicker=$mydate" (note that you will need to pass in $myDate to ths function.


text:
Q: How to delete contact number permantely from contact list? I want to delete contact permanently from my contact list.
I am using following code.
public boolean deleteContact(String phone, String name) {
    System.out.println("name :: "+name +"  "+phone);
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
            Uri.encode(phone));
    Cursor cur = context.getContentResolver().query(contactUri, null, null,
            null, null);
    try {
        if (cur.moveToFirst()) {
            do {
                if (cur.getString(
                        cur.getColumnIndex(PhoneLookup.DISPLAY_NAME))
                        .equalsIgnoreCase(name)) {
                    String lookupKey = cur
                            .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
                    Uri uri = Uri.withAppendedPath(
                            ContactsContract.Contacts.CONTENT_LOOKUP_URI,
                            lookupKey);
                    int i = context.getContentResolver().delete(uri, null, null);
                    System.out.println("i :::: "+i);
                    return true;
                }

            } while (cur.moveToNext());
        }

    } catch (Exception e) {
        System.out.println(e.getStackTrace());
    }
    return false;
}

In my mobile contact I have a contact named "SIRI" with two mobile numbers. The above code deletes both numbers. I want to remove only selected number not both numbers.

A: If you only one want to delete the selected phone number, try this:
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
resolver.delete(uri, null, null);

Simpler to do all in one go:
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

String selections =  ContactsContract.CommonDataKinds.Phone.NUMBER + " = ' + phone + ' AND " +  ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME.toLowerCase() + " = ' + name.toLowerCase() + '";

int res = contentResolver.delete(uri, selections, null);


text:
Q: How to convert dtype of numpy subarray? I am trying to read data from a csv file into a numpy array. Since the csv file contains empty fields, I read all of the data into an array of dtype=str, and plan to convert rows/columns into appropriate numerical types. The example below is my unsuccessful at converting these array dtypes.
import numpy as np

x = np.array([
['name', 'property', 'value t0', 'value t1', 'value t2'],
['a', 0.5, 1, 2, 3],
['b', 0.2, 5, 10, 100],
['c', 0.7, 3, 6, 9],
], dtype=str)

First, let's view the original array.
# print("\n .. x (shape={}, dtype={}):\n{}\n".format(x.shape, x.dtype, x))

[['name' 'property' 'value t0' 'value t1' 'value t2']
 ['a' '0.5' '1' '2' '3']
 ['b' '0.2' '5' '10' '100']
 ['c' '0.7' '3' '6' '9']]

Then, let's make sure the numerical entries (taken from the first row down and second column right) can be converted into type <int>.
# print(x[1:, 2:].astype(int))

[[  1   2   3]
 [  5  10 100]
 [  3   6   9]]

So, I tried to put these concepts together.
# # x[1:, 2:] = x[1:, 2:].astype(int)
# x[1:, 2:] = np.array(x[1:, 2:], dtype=int)

print(x)

[['name' 'property' 'value t0' 'value t1' 'value t2']
 ['a' '0.5' '1' '2' '3']
 ['b' '0.2' '5' '10' '100']
 ['c' '0.7' '3' '6' '9']]

Why are the selected entries remaining strings? I saw similar questions posted, for which the accepted solution appears to be using named-fields. But, I prefer numerical indexing to named-fields for my use-case.

A: In [83]: alist = [
    ...: ['name', 'property', 'value t0', 'value t1', 'value t2'],
    ...: ['a', 0.5, 1, 2, 3],
    ...: ['b', 0.2, 5, 10, 100],
    ...: ['c', 0.7, 3, 6, 9],
    ...: ]
In [84]: alist
Out[84]:
[['name', 'property', 'value t0', 'value t1', 'value t2'],
 ['a', 0.5, 1, 2, 3],
 ['b', 0.2, 5, 10, 100],
 ['c', 0.7, 3, 6, 9]]
In [85]: np.array(alist)
Out[85]:
array([['name', 'property', 'value t0', 'value t1', 'value t2'],
       ['a', '0.5', '1', '2', '3'],
       ['b', '0.2', '5', '10', '100'],
       ['c', '0.7', '3', '6', '9']], dtype='<U8')

object array:
In [87]: np.array(alist, dtype=object)
Out[87]:
array([['name', 'property', 'value t0', 'value t1', 'value t2'],
       ['a', 0.5, 1, 2, 3],
       ['b', 0.2, 5, 10, 100],
       ['c', 0.7, 3, 6, 9]], dtype=object)

structured array:
In [88]: np.array([tuple(row) for row in alist[1:]], dtype='U1,f,i,i,i')
Out[88]:
array([('a', 0.5, 1,  2,   3), ('b', 0.2, 5, 10, 100),
       ('c', 0.7, 3,  6,   9)],
      dtype=[('f0', '<U1'), ('f1', '<f4'), ('f2', '<i4'), ('f3', '<i4'), ('f4', '<i4')])

pandas:
In [90]: import pandas as pd
In [91]: pd.DataFrame(alist[1:], columns=alist[0])
Out[91]:
  name  property  value t0  value t1  value t2
0    a       0.5         1         2         3
1    b       0.2         5        10       100
2    c       0.7         3         6         9


text:
Q: Right angle triangle simple problem The number of degrees in one acute angle of a right-angled triangle is equal to the number of grades in the other; express both the angles in degrees.
So I have found the following answers :
810/17=47,05... degrees and 810/17=47,05... grades which gives 42,35... degrees
Now, the real answer is the following :
900/19=47,3... degrees and 900/19=47,3... grades which gives 42,63... degrees
The only problem with my answer is the following :
810/17degrees=900/17grades
so : 900/17 grades+ 810/17 grades = 100,5.. grades (but for the rest, everything is fine, I get get 90 degrees perfectly and respect all conditions.)
Would you count this as an error ???
Here's what I did : (Help me see the error)
x degrees= (x+x/9) grades
x grades= (x-x/9) degrees
so..
x degrees+(x-x/9)degrees=90 degrees
17x/9 degrees=90 degrees
17x=810
x=810/17 degrees
By the formulaiton of the problem, we also have 810/17 grades
Conversion
810/17 degrees=(810/17+(810/17)/9) grades=900/17 grades
and
810/17 grades=(810/17-(810/17)/9) degrees= 720/17 degrees
Can somebody tell me where I went wrong ??? (By the way, I see how to obtain the "real" answer, but I don't see why mine would be wrong ...)
Thank you !

A: The angles of a triangle add up to $180$ degrees, or $200$ grades.
So $0.9 G = D$, where $D$ and $G$ are the measures of an angle in degrees and grades, respectively.
One angle is a right angle, so the other two add up to $90$ degrees, or $100$ grades.  Further, the measure of one in degrees (expressed by $D_i$) is the measure of the other in grades (expressed by $G_i$).
So $G_1 + G_2 = 100$, and $G_1 = D_2 = 0.9 G_2,$ so $1.9 G_2 = 100$ or $G_2 \approx 52.63$ grades.  Then $G_1 \approx 47.37$ grades.
Multiply both by $0.9$ to get $(D_1, D_2) \approx (47.37, 42.63).$
(Where you went off a bit was in your definition of the conversion from degrees to grades.  You have $D = (10/9) G$ and $G = (8/9) D$, neither of which is right.  It should be $0.9 G = D$ or $(0.9)^{-1} D = G$.)

A: I don't understand all the reasoning of your solution, but you made an error when you changed from $x$ degrees = $x+\frac x9$ grades, which is correct, to $x$ grades = $x - \frac x9$ degrees.  The first says the number of degrees is $\frac 9{10}$ the number of grades.  The second says the number of grades is $\frac 98$ the number of degrees instead of $\frac {10}9$
And yes, if the number of grades adds up to $100.5$ instead of $100$ that is an error.  It should add to exactly $100$.


text:
Q: Cannot connect to h2 database in Intellij I´m trying to follow this tutorial tutorial in Intellij IDEA but when i try to connect to h2 database the console trowns me an error:
 Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost:9092"
        java.net.ConnectException: Connection refused: connect.

What i need to do to make the connection?
Thanks in advance

A: The problem is with the url, it needs to path to your app:
jdbc:h2:file:C:\Users\romul\IdeaProjects\raspberryAwards;MV_STORE=false;AUTO_SERVER=TRUE

A: Change connection type from "Remote" to "In-memory"


text:
Q: How to architect a website's presentation layer? I have been going back and forth in different approaches for designing the presentation layer for websites.
Many people swear by one of the different CMS packages which is too constraining and inflexible.  Many people suggest writing the HTML by hand which seems not to scale in the case of many pages.
I have a new web application I am designing and I really want to have a "correct" and "elegant" and practical approach in how I architect it.
Has anyone done this in a way in which they are happy with and can plug in various modules and libraries with no problems?
Any tips or pitfalls I should watch for?

A: I've written HTML by hand, written JSP, used WYSIWYG editors and I've been on teams that used packages (JSF).  I've actually liked any and all of them... although I frequently end up tossing WYSIWYG editors to the curb and just started editing by hand when doing straight HTML.
I think it's a factor of what you want to do:

*

*JSF - and presumably other comprehensive libraries - was great for very complex web data structures.  After using it, I would not want to write dynamic trees, complex tables with nested form controls, pop-up menus or other high end HTML by hand.  It fit nicely into my JEE MVC architecture with its myriad types of injection, and I think it saved me a lot of time in user interface widgets.  The fact that we could crack the code, too, and go in and customize some things was an absolute life saver.  The major drawback - when you need to speed up your server you will end up cracking the cover quite a lot and wondering how much you saved.  We had a really data-heavy system, complex connections, lots of data, and a strong need for pagination and sorting.  That worked in JSF, but we ended up overwriting quite a few things to make the system work efficiently.

*JSP - and presumably other dynamic presentation mechanisms (like ASP) - really great when you need a simpler dynamic presentation form.  Fast and easy to code with and able to do a nice collection of dynamic things.  The challenge - building in the connection between HTML display and dynamic processing is a learning curve that is different from writing in a OO language and different from straight HTML.  It can get exhausting to mentally switch between HTML/CSS thinking, JSP, and Java - and you have to.  JSF will let you be fairly blind to HTML and CSS unless you're doing something tricky. JSP will not.  Also, it puts the burden for session continuity on you, unless you've hunted down some open source to do it for you.

*HTML/CSS - great for just getting stuff done.  Obviously straight HTML will not let you get dynamic.  You need something additional - even if it's just a little JavaScript.  But I still write straight HTML for pages that I don't need to update very often.
I disagree that a simplistic dynamic HTML rendering solution (like JSP) can't scale.  I think you need to be clever - building pages for specialized areas (like a menu JSP for navigation), using div tags for layout, etc.  And I think you need to commit yourself to becoming good at refactoring.
From JSP to something more complex that does more construction for you - I think the key to happiness is finding a library that has what you need for display.  Start with some screen shots and see what libraries come close to your purposes.  Also, look for libraries that will play well with other mechanisms and you'll have the best of both worlds.  I don't think that's beyond reach.

A: If you want to ensure standards compliance, simplicity and consistency (i.e. correctness and elegance), writing your HTML and CSS by hand is the way to go. Every competent designer I have worked with does so. That level of control is necessary to get the results you want. I don't find the economy of scale to be at all limiting. Like any other scalability problem, it can be managed with the correct tools (reuse and so forth).

A: Never ever forget scalability when building web sites which has the potential for  massive amounts of traffic! I have seen too many examples of sites based on some flashy CMS which may be easy to use, but eventually turns out to have serious problems with memory and performance. It ends in disaster.
So my advice is to question how well your CMS actually manages load before you jump into bed with it. Also make sure it works with whatever memory caches, load balancers, database replication and front-ends you are planning to use. In many cases, you may be better of writing your own stuff with a simple html template engine (custom made even) and carefully crafted infrastructure.


text:
Q: Javascript form submit POSTs no data This is the form I'm using to post the data to gamelobby.php
<form id="game_form" method="POST" action="/gamelobby.php">
    <input type="text" id="plr_name"></input>
    <input type="hidden" value="" id="table_name"></input>
</form>
    <button id="codefight_create">Create a Fight</button>

This is the function that submits the form
    function codefight_create(){
            // blah blah, some ajax
            table_name = xmlhttp.responseText;
            document.getElementById("table_name").value = table_name;
            document.getElementById("game_form").submit();
            // console.log(table_name);
        }
    document.getElementById("codefight_create").addEventListener("click", function(){
        codefight_create();
    });

The problem is that when I var_dump($_POST) on the gamelobby.php page, there is no data stored in the $_POST superglobal on the page.

A: You forgot the name for the input:
<input type="text" id="plr_name"></input>

to
<input type="text" id="plr_name" name="plr_name"></input>

(same for the table_name input, the id is only on the client-side, it doesnt get sent to the server)

A: <form id="game_form" method="POST" action="/gamelobby.php">
...
</form>
<button id="codefight_create">Create a Fight</button>

to
<form id="game_form" method="POST" action="gamelobby.php">
...
<input type="submit" value="Create a flight"/>
</form>

Add on click event by onclick="codefight_create();" on the button input.
You can use listener event but you need to add it into the the JQUERY when the document gets ready..


text:
Q: Nested joins and aliases with (Flask-)SQLAlchemy I'm trying to switch from using raw SQL to SQLAlchemy/Flask-SQLAlchemy. As far as I learned simple queries, I can't understand how to use subqueries, nested joins and aliases.
Right now I have my SQL query:
SELECT device.*, wifi.name as room FROM
(SELECT * FROM devices WHERE mac="{0}") as device
LEFT JOIN
    (SELECT w2.*, wifi_map.name as name FROM
        (SELECT * FROM (SELECT * FROM wifi ORDER BY signal_pow DESC) as w1 GROUP BY device_id) as w2
        INNER JOIN wifi_map
        ON w2.bssid=wifi_map.bssid)
    as wifi
ON device.id=wifi.device_id

I managed to convert the LEFT JOIN part to SQLAlchemy (the one that's aliased as wifi). It looks like this:
sorted_wifi = db.session.query(WiFi).order_by(WiFi.signal_pow.desc())\
    .join(WiFi.map).subquery()
wifi_with_room = db.session.query().add_entity(WiFi, alias=sorted_wifi)\
    .group_by('device_id')

So here wifi_with_room is list of rows with model Wifi and WiFi.map as list of models WiFiMap that match (based on WiFi.bssid == WiFiMap.bssid). But I don't know how I'm supposed to join wifi_with_room together with Device. I tried
db.session.query(Device).outerjoin(wifi_with_room)

But that gives me error

Every derived table must have its own alias

So then I tried
db.session.query(Device).outerjoin(wifi_with_room.alias('wifi'))

But it returned

AttributeError: 'Query' object has no attribute 'alias'

What I want to achieve is list of rows that have:

*

*model Device (and all it's elements)

*in Device.room name of the room that's returned from WiFiMap.name by matching WiFi.device_id == Device.id and then WiFiMap.bssid == WiFi.bssid

Here are my models:
class Device(db.Model):
    __tablename__ = 'devices'

    id = db.Column(db.Integer, primary_key=True)
    mac = db.Column(db.Text)
    vendor = db.Column(db.Text)
    model = db.Column(db.Text)
    name = db.Column(db.Text)
    resolution_h = db.Column(db.Integer)
    resolution_w = db.Column(db.Integer)
    system_version = db.Column(db.Text)
    cpu_model = db.Column(db.Text)
    gpu = db.Column(db.Text)
    gpu_clock = db.Column(db.Integer)
    ram = db.Column(db.Integer)
    layouts = db.Column(db.Text)
    screen_size = db.Column(db.Float)
    screen_density = db.Column(db.Integer)
    imei = db.Column(db.Integer)
    density_cat = db.Column(db.Text)
    graphics_cat = db.Column(db.Text)
    type = db.Column(db.Text)
    last_active = db.Column(db.DateTime, onupdate=datetime.datetime.now)
    unavailable = db.Column(db.Integer)

class WiFi(db.Model):
    __tablename__ = 'wifi'

    id = db.Column(db.Integer, primary_key=True)
    device_id = db.Column(db.Integer, db.ForeignKey('devices.id', onupdate="CASCADE", ondelete="CASCADE"), index=True)
    bssid = db.Column(db.String(17), index=True)
    ssid = db.Column(db.Text)
    signal_pow = db.Column(db.Integer)

class WiFiMap(db.Model):
    __tablename__ = 'wifi_map'

    room = db.Column(db.Integer)
    x = db.Column(db.Integer)
    y = db.Column(db.Integer)
    bssid = db.Column(db.String(17), db.ForeignKey('wifi.bssid'), primary_key=True)
    ssid = db.Column(db.Text)
    name = db.Column(db.Text)
    wifi = db.relationship('WiFi', backref='map', lazy='immediate')


text:
Q: SQLite database directory in intellij idea I am trying some simple android codes in intellij IDEA.
I have an .db SQLite DataBase of words.
But I Dont know witch Directory of project I have to Paste the DB file
 I Opened this DB like this :
 try {
            db=openOrCreateDatabase("data.db", 1,null);
        }
        catch (SQLException e)
        {
            Toast.makeText(getApplicationContext(),"ERR:"+e.getMessage(),Toast.LENGTH_LONG).show();
        }

and used like this :
try
                {
                Cursor c;
                c = db.rawQuery("SELECT * FROM words WHERE en='"+ed.getText()+"'",null);
                v.append(c.getString(1));

            }
            catch (SQLException e)
            {
                Toast.makeText(getApplicationContext(),"ERR:"+e.getMessage(),Toast.LENGTH_LONG).show();
            }

cheers,

A: Usually you leave it to a Framework to do... but in your case it's pretty simple
You /assets/
Create it like so...
As for DB_NAME = "yourfilename.db"
As for DB_NAME = "/data/data/" + context.getPackageName() + "/databases/";

    private void copyDataBase() throws IOException {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream mOutput = new FileOutputStream(outFileName);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0) {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
   }


text:
Q: Show that block matrix has full row rank ii and only if $A$ has full row rank. I've read a text, and they say the following lemma,

Lemma: For given matrices $A,B$ , the matrix
$$
\begin{pmatrix}
 A & B\\
 0^T & v^T\\
\end{pmatrix}
$$
has full row rank for all nonzero $v$ iif $A$ has full row rank.

where the matrix, not needed to be squared. can give me som hint, thanks!

A: If $A$ does not have full row rank, then there exists a nonzero $u$ such that $u^\top A = 0$. Try to come up with a nonzero vector $v$ and scalar $c$ such that
$$\begin{pmatrix} u^\top & c \end{pmatrix} \begin{pmatrix} A & B \\ 0^\top & v^\top \end{pmatrix} = 0.$$
(It will depend on what $u^\top B$ is.)

If there exists nonzero $v$ such that $M := \begin{pmatrix} A & B \\ 0^\top & v^\top \end{pmatrix}$ does not have full row rank, then there exists a vector $u$ and scalar $c$ such that $\begin{pmatrix}u \\ c \end{pmatrix}$ is nonzero and
$$\begin{pmatrix} u^\top & c \end{pmatrix} \begin{pmatrix} A & B \\ 0^\top & v^\top \end{pmatrix} = 0.$$
Show that the above conditions imply that $u$ is nonzero and that $u^\top A = 0$.

A: call your overall matrix $C$ which has $m$ rows  .
1.) $A \text{ is full row rank }\implies C \text{ is full row rank}$
since $A$ has full row rank, it is surjective and has a right inverse.  Thus there is some (block) matrix $W$ such that
$CW = \begin{pmatrix}
 A & B\\
 \mathbf 0^T & \mathbf v^T\\
\end{pmatrix}W = \begin{pmatrix}
 I_{m-1} & *\\
 \mathbf 0^T & \mathbf v^T\\
\end{pmatrix}$
$m = \text{rank}\big(CW\big)\leq \text{rank}\big(C\big)\leq m$
2.) $C \text{ is full row rank} \implies A\text{ is full row rank } $
$C$ is sujective so it has a right inverse $W'$
$CW' = I_m$
This implies that for all non-zero $\mathbf x':=\begin{pmatrix}\mathbf x \\  0 \end{pmatrix}$
$(\mathbf x')^TC \neq\mathbf 0^T\implies \mathbf x^TA\neq \mathbf 0^T$
and hence all rows of $A$ are linearly independent.


text:
Q: Change Layer's Label Property "Display coded value description" I created labels for layer in according with this example
They display coded value description from domain, but I need value itself. I can resolve it manually by unchecking this option

"Layer's Properties -> Labels -> Expression... -> Display coded value
  description"

How can I do that programmatically with ArcObjects 10+?

A: Below is some VBA code to show you how to do this, key Interface is ICodedValueAttributes
Public Sub TurnONOFFCodedDescription()
    ' Get Document
    Dim pMXD As IMxDocument
    Set pMXD = ThisDocument

    ' Get map
    Dim pMap As IMap
    Set pMap = pMXD.FocusMap

    ' Get first layer and cast into IGeoFeatureLayer
    Dim pLayer As ILayer
    Set pLayer = pMap.Layer(0)
    Dim pGeoFL As IGeoFeatureLayer
    Set pGeoFL = pLayer

    ' Get annotation layer properties for this layer
    Dim pAnnotationPropertiesColl As IAnnotateLayerPropertiesCollection
    Set pAnnotationPropertiesColl = pGeoFL.AnnotationProperties
    Dim unplacedEle As IElementCollection
    Set unplacedEle = New ElementCollection
    Dim placedEle As IElementCollection
    Set placedEle = New ElementCollection
    Dim pAnnotateLayerProperties As IAnnotateLayerProperties
    pAnnotationPropertiesColl.QueryItem 0, pAnnotateLayerProperties, placedEle, unplacedEle

    ' Get label engine
    Dim pLabelEngineLayerProperties As ILabelEngineLayerProperties2
    Set pLabelEngineLayerProperties = pAnnotateLayerProperties
    Dim pAnnotationExpressionEngine As IAnnotationExpressionEngine
    Set pAnnotationExpressionEngine = pLabelEngineLayerProperties.ExpressionParser

    ' Set Coded value to be false (same as unchecking on GUI)
    Dim pCodedValueAttributes As ICodedValueAttributes
    Set pCodedValueAttributes = pAnnotationExpressionEngine
    pCodedValueAttributes.UseCodedValue = False
End Sub


text:
Q: Running OpenCV from a Python virtualenv I'm trying to install OpenCV within a virtualenv on my Ubuntu Server 12.04. I found a thread discussing this but managed to extract no information from it.
I tried using pip install pyopencv but it failed.
...
package/extras/core/ndarray.cpp:598:1:   instantiated from here

package/extras/core/ndarray.cpp:546:9: warning: format '%d' expects argument of type 'int', but argument 4 has type 'Py_intptr_t {aka long int}' [-Wformat]

package/extras/core/ndarray.cpp: In function 'boost::python::api::object sdcpp::from_ndarray_impl(const sdcpp::ndarray&) [with T = cv::Scalar_<double>]':

package/extras/core/ndarray.cpp:601:1:   instantiated from here

package/extras/core/ndarray.cpp:546:9: warning: format '%d' expects argument of type 'int', but argument 4 has type 'Py_intptr_t {aka long int}' [-Wformat]

package/extras/core/ndarray.cpp: In function 'boost::python::api::object sdcpp::from_ndarray_impl(const sdcpp::ndarray&) [with T = cv::Range]':

package/extras/core/ndarray.cpp:604:1:   instantiated from here

package/extras/core/ndarray.cpp:546:9: warning: format '%d' expects argument of type 'int', but argument 4 has type 'Py_intptr_t {aka long int}' [-Wformat]

error: command 'gcc' failed with exit status 1

This error only occurs the second time I run pip install. If I delete the remainging build/ folder I get this error.
-- Configuring incomplete, errors occurred!

Configuring PyOpenCV via CMake...

Error: error occurred while running CMake to configure PyOpenCV.

You may want to manually configure PyOpenCV by running cmake's tools:

    mkdir build

    cd build

    cmake-gui ..    OR    cmake ..

    cd ..

----------------------------------------
Command python setup.py egg_info failed with error code 255

I have at least the following apt packages installed.
build-essential
uuid-dev
python-dev
python-pip
libpq-dev
cmake
libboost-dev
libcv-dev
libcvaux-dev
libboost-python-dev
libboost1.48-dev

How can I install OpenCV within my virtualenv?

A: Here is the cleanest way, using pyenv and the virtualenv plug-in.
Install Python with shared library support (so we get a libpython2.7.dylib on Mac OS X or libpython2.7.so on Linux).
env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install -v 2.7.6

Create the virtualenv, based on the version of python we just installed.
pyenv virtualenv 2.7.6 myvirtualenv

Activate the virtualenv.
pyenv shell myvirtualenv
pyenv rehash

Install numpy. Otherwise opencv will fail to link itself to Python correctly.
pip install numpy

Set the prefix of the python install.
PREFIX_MAIN=`pyenv virtualenv-prefix`

Set the prefix of the environment. (sic! The name of these pyenv commands are a bit deceptive!)
PREFIX=`pyenv prefix`

Now configure and install opencv. Notice that the opencv binaries and packages will be installed in our virtualenv while the dynamic library and includes of the Python install is used.
cd openCV2.4
mkdir release
cd release
cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX="$PREFIX" -DPYTHON_EXECUTABLE="$PREFIX"/bin/python2.7 -DPYTHON_LIBRARY="$PREFIX_MAIN"/lib/libpython2.7.so -DPYTHON_INCLUDE_DIR="$PREFIX_MAIN"/include/python2.7 -DPYTHON_PACKAGES_PATH="$PREFIX"/lib/python2.7/site-packages/ ..
make install

(On OSX, replace libpython2.7.so with libpython2.7.dylib.)

A: Fired up a virtualenv and followed this guide: http://www.samontab.com/web/2011/06/installing-opencv-2-2-in-ubuntu-11-04/ , up until manipulating and copying the cv shared objects.  Instead, I copied cv.so (from my OpenCV-2.2.0/lib directory) to my virtualenv site-packages (eg. env/lib/python2.7/site-packages/).  Once cv.so was in my environment, I was able to import cv within python.

A: Did you already apt-get build-dep python-opencv? This will install all the required dependencies to build it from source; which you need if you are trying to install it in a virtual environment.


text:
Q: How to load record type id for lightning-record-edit-form? I'm trying to set the record-type-id of a <lightning-record-edit-form> in a Lightning Web Component. However, every time I add the code for the record type id, the page is blank. This is to create a new record, not edit one.
Controller:
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import MY_OBJECT from '@salesforce/schema/myObject__c';

export default class myClass extends LightningElement {

    @api recordTypeId;
    @api objectInfo;

    @wire(getObjectInfo, { objectApiName: MY_OBJECT })
    objectInfo;

    get recordTypeId() {
        console.log('get recordtypeid');
        // Returns a map of record type Ids
        const rtis = this.objectInfo.data.recordTypeInfos;
        return Object.keys(rtis).find(rti => rtis[rti].name === 'record type 1');
    }
}

Component:
    <lightning-record-edit-form
            object-api-name={myObject}
            record-type-id={recordTypeId}
            onsubmit={handleSubmit}
            onsuccess={handleSuccess}
            onerror={handleError}>

A: There's no tracking of your recordTypeId and no dependency linkage between getting the object info back from the server and this LWC property usage in the template. Try updating the code like:
@track
recordTypeId;

@wire(getObjectInfo, { objectApiName: MY_OBJECT })
handleObjectInfo({error, data}) {
    if (data) {
        const rtis = data.recordTypeInfos;
        this.recordTypeId = Object.keys(rtis).find(rti => rtis[rti].name === 'record type 1');
    }
}

That way when the recordTypeId changes the form markup in the template is re-processed. And the record type ID is only updated when the object info wire is actually invoked to successfully return data.


text:
Q: Is there a way to cache nightly and stable builds separately in Rust? I am developing a Rust project and frequently do the following commands in series:
# runs clippy on latest nightly
rustup run nightly cargo clippy
# run tests on stable
cargo test

This causes my project to rebuild the full set of dependencies every time I build each. Is there a way to cache the builds separately?


text:
Q: Creating multiple hubs dynamically using SignalR I am currently using SignalR for chat. I have a form and the user will load a specific order into the form. The scenario is that other staff members may search that order number and therefore i want only those people to be in the chat. Currently if you load the site everyone is in a single hub called ChatHub.
ChatHub.cs:
public class ChatHub: Hub {
 public void Send(string name, string message) {
  // Call the addNewMessageToPage method to update clients.
  Clients.All.addNewMessageToPage(name, message);
 }
}
}

Chat.cshtml:
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
            var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append(htmlEncode(name)
                    + ':' + htmlEncode(message) + '\n');
            };
            // Get the user name and store it to prepend to messages.

            //$('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
<script>

I have tried to add the following:
<script>
$(function () {
    var chat = jQuery.connection.chat;

    chat.addMessage = function (message, room) {

        if ($('#currentRoom').val() == room) {
            $('#messagesList').append(message);
        }
    };

        chat.send($('#textboxMessage').val(), $('#currentRoom').val());
        $('#textboxMessage').val("");

    $.connection.hub.start();
});
</script>

I am trying to work out a way of getting multiple hubs or chat rooms based on a user loading an order.

A: You have to put the users into groups according to the opened order id, change the hub and add a method as below:
public class ChatHub: Hub {
 public void Send(string name, string message,string orderId) {
  // Call the addNewMessageToPage method to update clients.
  Clients.Group(orderId).addNewMessageToPage(name, message);
 }

public void JoinOrderGroup(string name,string orderId)
 {
     Groups.Add(Context.ConnectionId, orderId);
 }
}

Then modify your JavaScript to call the `JoinOrderGroup' when the user opens the page.
@section scripts {
    <!--Script references. -->
    <!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
    <!--Reference the SignalR library. -->
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <!--Reference the autogenerated SignalR hub script. -->
    <script src="~/signalr/hubs"></script>
    <!--SignalR script to update the chat page and send messages.-->
    <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.
             var orderId = '@Model.Id' //You can change this line to get the orderId from the correct place
             var chat = $.connection.chatHub;
            // Create a function that the hub can call back to display messages.
            chat.client.addNewMessageToPage = function (name, message) {
                // Add the message to the page.
                $('#discussion').append(htmlEncode(name)
                    + ':' + htmlEncode(message) + '\n');
            };
            // Get the user name and store it to prepend to messages.

            //$('#displayname').val(prompt('Enter your name:', ''));
            // Set initial focus to message input box.
            $('#message').focus();
            // Start the connection.
            $.connection.hub.start().done(function () {
                $('#sendmessage').click(function () {
                    // Call the Send method on the hub.
                    chat.server.send($('#displayname').val(), $('#message').val());
                    // Clear text box and reset focus for next comment.
                    $('#message').val('').focus();
                  chat.server.joinOrderGroup($('#displayname').val(),orderId);
                });
            });
        });
        // This optional function html-encodes messages for display in the page.
        function htmlEncode(value) {
            var encodedValue = $('<div />').text(value).html();
            return encodedValue;
        }
    </script>
}
<script>

This way, when the page starts and the hub connects, it will send a message to join the group related to the order in the form, and all successive calls to teh send message method will include the order id and it will be propagated to the users in this order only.

A: You have to work with groups:
https://www.asp.net/signalr/overview/guide-to-the-api/working-with-groups


text:
Q: Javascript variable scope inside for loop How do I maintain access to the i variable inside my for loop below? I'm trying to learn, not just get the answer, so a bit of explanation would be very helpful. Thank you!
var el,
    len = statesPolyStrings.length;

for (var i = 0; i < len; i++) {
    el = document.getElementById(statesPolyStrings[i]);

    google.maps.event.addDomListener(el, 'mouseover', function() {
        $("#"+statesPolyStrings[i]).addClass("highlight");
        statesPolyObjects[i].setOptions({ strokeWeight: '2' });
    });
}

A: All of your callbacks share the same i variable.
When the event handler actually runs, i is after the end of the array.
You need to wrap the loop body in a self-invoking function that takes i as a parameter.
This way, each iteration will get its own, unchanging, i variable.
For example:
for (var i = 0; i < statesPolyStrings.length; i++) {
    (function(i) {
        ...
    })(i);
}

A: for (var i = 0; i < statesPolyStrings.length; i++) {
    (function(i){
        google.maps.event.addDomListener(document.getElementById(statesPolyStrings[i]), 'mouseover', function() {
        $("#"+statesPolyStrings[i]).addClass("highlight");
        statesPolyObjects[i].setOptions({ strokeWeight: '2' });
        });
    })(i)
}

A: The trick with self-invoking functions works fine: it creates a new scope (maybe google for 'scope in functions javascript') and therefore handles i as a different variable and delivers the right value to your event listener callback function.
But you actually don't need to find your element again with jQuery as you already assigned an event listener to it and inside your function you have a reference to your element with this.
And as you're using jQuery anyhow, it's then easy to find the correct index (your i) of statesPolyObjects with $.inArray() passing the id of your element and the statesPolyStrings array (assuming you're dealing with unique IDs. If not, $("#"+statesPolyStrings[i]) would also fail, as it takes the first it finds).
var el;

for (var i = 0, len = statesPolyStrings.length; i < len; i++) {
    el = document.getElementById(statesPolyStrings[i]);

    google.maps.event.addDomListener(el, 'mouseover', function(event) {
        $(this).addClass("highlight");
        statesPolyObjects[$.inArray(this.id, statesPolyStrings)].
            setOptions({ strokeWeight: '2' });
    });
}

If you still want to stick with the self-invoking function you should anyhow change the following line:
("#"+statesPolyStrings[i]).addClass("highlight");

to
$(this).addClass("highlight");

If you're not familiar enough with this and events you might want to read this article:
http://www.sitepoint.com/javascript-this-event-handlers/
You might have noticed that I also wrote the argument event inside the anonymous callback function. Try to console.log this event you get delivered for free with any event listener callback function and explore all the other things you have access to. For example, you can find the actual element you clicked on with event.target (as the actual mouseover might have happened to a child of your element). So:
google.maps.event.addDomListener(el, 'mouseover', function(event) {
    console.log(event);
    ...

and open the console of your browser to see what event delivers...
Be aware though that google.maps.event.addDomListener passes something different then document.body.addEventListener and there is also a difference between browsers. jQuery.on() for example also delivers some different things in the event object, but there you can at least count on the same data in all browsers.


text:
Q: Android Studio Generated TODO comments In Eclipse when I generated a new activity or override a method, I would get an automatically generated TODO comment.  Would like to have that in AS also, but can't figure out how to enable that feature.  Can anyone give me a clue on how to enable this?

A: Click on the top menu item named Android Studio in Mac and then on the Preferences option. Now, look for the Editor and then on File and Code Templates in the side menu.
[Preferences Path: Preferences | Editor | File and Code Templates]
Select the code tab and edit the Overridden Method Body template as shown below.
// TODO Implement the method $METHOD_NAME
$CALL_SUPER;

Click Ok and whenever you try to generate an overridden method it generates with the added TODO.
@Override
public void onResume() {
    // TODO Implement the method onResume
    super.onResume();
}

Similarly, you can edit the Activity or Fragment template in the Other tab.


text:
Q: RadRotator not resizing on browser resize I'm currently trying to resize this control on browser resize.
I tried to look on the forums before asking. I found a Javascript function ( which is not working unfortunately).

Error : RadResize Null or undefined.
Thanks in advance for your help

A: Check out this Knowledge Base article. It contains information about resizing the RadRotator according to the browser window, which includes an example of the described approach.

A: Hey Arnaud Add this script in your aspx page and your problem would be solved:
script type="text/javascript">
window.onresize = function()
{
    var rotatorElement = document.getElementById("<%= RadRotator1.ClientID %>" + "_Div");
    rotatorElement.RadResize();
}
</script>

A: Hey Arnaud You can easily achieve your goal by specifying fixed layout for the table.
Here is the sample code:
<form id="form1" runat="server">

                <radR:RadRotator ID="RadRotator1" runat="server" TransitionType="Scroll" ContentFile="http://rss.msnbc.msn.com/id/3033655/device/rss/rss.xml" DataMember="item" Height="130px" Width="100%">
                    <FrameTemplate>

                                <a href="<%# DataBinder.Eval(Container.DataItem,"link") %>" target="_blank">
                                    <%# DataBinder.Eval(Container.DataItem,"title") %>

                                <%# DataBinder.Eval(Container.DataItem,"pubDate") %>

                                <%# DataBinder.Eval(Container.DataItem,"description") %>

                    </FrameTemplate>
                </radR:RadRotator>

</form>


text:
Q: Is the Autolayout best approach for building the iOS Application? I have built an app which supports only for iPhone (portrait),but as we know autolayout are very powerful layout tool and these are excellent, and those would be the best places to learn more.
But as per my experience ,recently in my  app using autoresizing ,I am been abled  to finishing up every screen 5 times faster than if I use autolayout for the same and it fits to all iPhone devices (3.5 inches,4 inches,4.7 inches,5.5inches).So it really saves my time.So should we  go for autoresizing instead of autolayout if our application deals with only for  iphone(portrait ) or iPad (portrait) ?

A: You should move to Auto-layout ASAP.
Since you said it took you less than 5 times as compare to Auto-resizing. The reason is you have not figured out the Power of it yet.
With the introduction of Size-class and now Stack Views, the power has increased much. So it is not just Auto-layout. Its a combination of 3 super tools. Learning takes some time, and is purely based upon trial and error method.


text:
Q: CSS to stop page break inside of table row I am trying to avoid having page breaks inside of rows for my HTML tables that may go past one page. I am using Internet Explorer Print Preview and also BCL EasyPDFSDK to convert to PDF to test this. I applied the following CSS styling in various combinations to the <td> elements but for each one I was getting an undesired result:
td {
    page-break-inside: avoid !important;
    white-space: nowrap;
    overflow: hidden;
    margin: 4px 0 4px 0;
}

I believe the page-break-inside: avoid !important is working, but only on the <td> level. For example, I will see a <tr> that has one <td> on the end of the first page with all of the text intact, but the following <td> tags would be on the next page with all of their text intact.
I didn't think you were supposed to apply formatting to <tr> so I'm unsure how to go about fixing this.
Should I apply the CSS to the <tr> or is there another way to achieve this?
Thanks for the help!

A: Turns out I needed to collapse borders on the table element and reduce my padding to only 1px using
table { border-collapse: collapse; }
td {
    page-break-inside: avoid !important;
    white-space: nowrap;
    overflow: hidden;
    padding: 1px;
    font-size: xx-small;
}

I also set the font-size to xx-small just in case that was causing an issue. The issue seemed to primarily be resolved when I collapsed borders, so it makes me wonder if the table was having issues splitting the rows because of that.
Cheers!
EDIT:
Since dealing with this issue, I have found out that the row splitting is handled much better in newer web browsers. I highly recommend updating IE to at least 11 if you are experiencing this issue.

A: I just added the below css to my @media print and it worked!!!
None of the solutions applied to td, th, tr worked

table {
  page-break-inside: avoid !important;
}


text:
Q: ¿Como crear un boton de cerrar en una activity? Hola quiero crear un botón de cerrar en una toolbar de una activity para que al pulsarlo me devuelva al fragment anterior, pero no me funciona. Este es el codigo de la activity:
class EditProfileActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_profile)

        //Establecer Menu de Arriba
        EPToolbar.inflateMenu(R.menu.edit_profile_menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.closeEP -> {
                finish()
            }
        }

        return super.onOptionsItemSelected(item)
    }

}

A: Prueba así:
//método que crea el menú
public boolean onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}
//método que registra el item pulsado del menú
public boolean onOptionsItemSelected(MenuItem item)
{
    //se declara vairable entera para la posición del item
    int id = item.getItemId();
    int pos;
    //en función del item del menú pulsado
    switch (item.getItemId())
    {
        //si escoge la primera opción del menú
        case R.id.opcion1:
            //espacio para programar lo que ocurre con ésta pulsación
            break;
        case R.id.opcion2:
            //espacio reservado para programar lo que secede tras ésta eleción
            break;
        case R.id.opcion3:
            //si elegimos ésta opción cerramos la activity
            finish();
            break;
    }
    //se retorna el item seleccionado
    return super.onOptionsItemSelected(item);
}

el xml del menú
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- primera opción del menú -->
    <item android:id="@+id/opcion1"
        android:icon="@android:drawable/ic_menu_add"
        android:title="Parte 1"
        android:orderInCategory="1"
        app:showAsAction="never"/>
    <!-- segunda opción del menú -->
    <item android:id="@+id/opcion2"
        android:title="Parte 2"
        android:orderInCategory="2"
        app:showAsAction="never"/>
    <!-- tercera opción del menú -->
    <item android:id="@+id/opcion3"
        android:title="Cerrar"
        android:orderInCategory="3"
        app:showAsAction="never"/>

</menu>


text:
Q: scrollbars of datagridview are blackened by backgroundWorker I have c# WinForms application, it has some search parameters (TextBox and ComboBox) and a search Button, below this GroupBox are two DataGridView controls placed side by side. Then I have a PictureBox placed on top of the DataGridView controls whose Visible property I have set to False. Then I also have a BackgroundWorker. On button1_Click event, I am setting PictureBox's Visible property to Trueand calling backgroundWorker1.RunWorkerAsync();. On backgroundWorker1_DoWork(object sender, DoWorkEventArgs e), I am doing fetching records and populating DataGridView controls. On backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e), I am calling pictureBox3.Hide(); However, ever since I have added this loader functionality, the form remains unresponsive for some more seconds unlike the previous behavior and also the ScrollBars of the DataGridView controls are blackened. Like, literally blackened. Though, DataGridView controls are still scrollable. The form itself has DoubleBuffered set to True. Also, I have made the DataGridView controls DoubleBuffered via Reflection like this,
public static void DoubleBuffered(this DataGridView dgv, bool setting)
        {
            Type dgvType = dgv.GetType();
            PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
                BindingFlags.Instance | BindingFlags.NonPublic);
            pi.SetValue(dgv, setting, null);
        }

Please help me with the problematic (bold) part. Thank you.

EDIT - DoWork Code

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            dataGridView1.DataSource = null;
            dataGridView2.DataSource = null;
            if (btn2d.Checked && btn3d.Checked)
            {
                searchdata1();
                searchdata2();
            }
            if (!btn2d.Checked && !btn3d.Checked)
            {
                searchdata1();
                searchdata2();
            }
            if (btn2d.Checked && !btn3d.Checked)
            {
                searchdata1();
            }
            if (!btn2d.Checked && btn3d.Checked)
            {
                searchdata2();
            }
        }


text:
Q: Using Alamofire with .publishDecodable I need to use .publishDecodable together with Result, I followed the instructions, but I ran into this error: "generic parameter 't' could not be inferred closure"

@Published var loginModel: [LoginModel] = [LoginModel]()

var cancellation: AnyCancellable?

func request<T: Codable>(_ url: String, method: HTTPMethod = .get, headers: HTTPHeaders? = nil, parameters: Codable? = nil) -> AnyPublisher<Result<T, AFError>, Never> {
    let publisher = AF.request(url, method: method, headers: headers)
        .validate()
        .publishDecodable(type: T.self)
    return publisher.result()
}

 func login(email: String, password: String) {
    let parameters = LoginParameters(
        email: email,
        password: password
    )

    cancellation = request(serverURL + "login", method: .post, parameters: parameters)
        .sink { [self] response in
            switch response {
            case .success:
                loginModel = response.value()
            case .failure(error):
                print(error)
            }
        }
}

A: You should help the compiler to infer the T type be providing the type of the response that you expect. For example your call to request(_:method:headers:parameters:) function might look like this:
cancellation = request(serverURL + "login", method: .post, parameters: parameters)
    .sink { [self] (response: Result<[LoginModel], AFError>) in
        switch response {
        case .success(let value):
            self.loginModel = value
        case .failure(let error):
            print(error)
        }
    }

Or if you prefer you can specify the return type of the request(_:method:headers:parameters:) function like this:
let publisher: AnyPublisher<Result<[LoginModel], AFError>, Never>
publisher = request(serverURL + "login", method: .post, parameters: parameters)
cancellation = publisher.sink { [self] response in
    switch response {
    case .success(let value):
        self.loginModel = value
    case .failure(let error):
        print(error)
    }
}