text:
Q: Absolute path to currently-running zsh? Sometimes the output of ps -p $$ shows the absolute path to the currently-running zsh,
% ps -p $$
  PID TTY           TIME CMD
 1027 ttys005    0:00.11 /usr/local/bin/zsh

but not always:
% ps -p $$
  PID TTY           TIME CMD
 1507 ttys003    0:00.07 zsh -fl

What is a consistent way to get the path to the currently-running zsh?
EDIT (clarification): I'm interested in how to do this primarily in Darwin and Linux, but also in NetBSD.

A: The CMD output by ps is either the process name or the arguments passed to the command (including the first argument argv[0]). Though it bears some relation with the path of the executable, there's no guarantee for them to be linked.
On Linux:
print -r -- /proc/self/exe(:A)

On Darwin and Linux and possibly others:
lsof -ap"$$" -dtxt  -Fn | sed '2!d;s/.//;q'

But I don't know how reliable it is.
Another heuristic:
print -r -- ${${0#-}:c:A}

$0, like you see in the ps output contains the first argument that zsh received (argv[0]), or when passed a script as argument, that argument.
In the first case, typically, (by convention, there's no guarantee) that argv[0] would be either a path including a / (relative or absolute), or zsh (something without /) in which case the caller will have looked up zsh in his $PATH or his command hash table... If the path is relative, the above method will only work if the current directory has not changed since zsh was invoked. If there's no /, the method will only work if zsh is looking up the executable the same way as the caller did.
In the case of a script, it's the path of the script that will be returned instead of that of the interpreter (contrary to the first two solutions).

A: You can use this command to get the absolute path of any program:
which cmd
For example:
which zsh


text:
Q: Place an image on right side of div while other on middle I have the following code:
CSS
.producttype {

  height:16%;
  width:16%;
}

HTML

Following is how it looks:

I want it to be this way:

The outer should be DIV1,
I0 = Image 1 which is left aligned
I1,I2,I3 = three different images which should be combined at the center of DIV1
I tried div layer but then the I0 was not clickable.

A: here you are:
http://jsfiddle.net/8u2Bp/1/
you have to set a parent div with
position:relative;
text-align:center;

then on the image you want ot stay on the left
position:absolute;
left: 10px [distance you want it from the left border]

A: you could just create a simple table with 1 row and 2 or 3 columns
and then place I0 in the left cell or wherever you want and align them
as you wish :)

(you could set the table's width to adjust better the orientation of your img)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blank left and right delimiters produce an unknown symbol I recently compiled one of my files after updating my TeX distribution (including the unicode-math package, as I use the MinionMath font set) and noticed a strange error. In my file I used a cases environment, and for some reason an unknown symbol was printed at the end of the environment. Here is a minimal example. When I input
\begin{equation*}
        f(x) \colonequals
         \begin{cases}
            1, & x ≤ 1  \\
            x, & x ≥ 1
        \end{cases}
\end{equation*}

it produces the following:

The same problem occurs when using the \left. and \right. blank delimiters, so I think that it's ultimately a problem with the delimiters. I was wondering if there's a way to make this unknown symbol go away.
I'm using the TeXLive distribution and compiling with XeLaTeX. Here's how I've loaded the fonts (which hasn't been a problem in the past 6 months).
\usepackage[math-style=ISO]{unicode-math}
\setmainfont[Numbers={OldStyle}, Ligatures={Common}, ItalicFont={Minion Pro Italic}, BoldFont={Minion Pro Semibold}, BoldItalicFont={Minion Pro Semibold Italic}]{Minion Pro}
\setmonofont{Exemplar Pro}
\setmathfont[
    Extension = .otf,
    Scale = 1,
    Script = Math,
    SizeFeatures = {
        {Size = -6, Font = MinionMath-Tiny,
            Style = MathScriptScript},
        {Size = 6-8.4, Font = MinionMath-Capt,
            Style = MathScript},
        {Size = 8.4-13, Font = MinionMath-Regular,
            Style = MathScript},
        {Size = 13-19.9, Font = MinionMath-Subh,
            Style = MathScript},
        {Size = 19.9-72, Font = MinionMath-Disp},
        {Size = 72-, Font = MinionMath-Disp,
            Style = MathScript},
            },
        ]{MinionMath-Regular}
\setmathfont[range={\mathfrak}]{xits-math.otf}
\setmathfont[range={\mathcal}]{xits-math.otf}
\setmathfont[range={\mathit}]{MinionMath-Regular.otf}

I'm using the amsart documentclass.

A: The following example with up-to-date TeXLive works well:
\documentclass{amsart}
\usepackage{colonequals}
\usepackage[math-style=ISO]{unicode-math}
\setmainfont[Numbers=OldStyle]{Minion Pro}
\setmathfont{MinionMath-Regular}
\setmathfont[range={\mathfrak,\mathcal}]{XITS Math}
\begin{document}

foo \textit{bar} \textbf{baz}

\begin{equation*}
    f(x) \colonequals
    \begin{cases}
    1, & x ≤ 1  \\
    x, & x ≥ 1
    \end{cases}
\end{equation*}

\end{document}


text:
Q: Storybook integration with Expo React Native not working I am trying to get Storybook running on a react native app build by Expo. I generated my project with:
expo init storybook-test

I entered the folder and ran:
npx -p @storybook/cli sb init --type react_native

...which I got from this tutorial and it added multiple files and folders such as:
- Root
- - storybook
- - - stories
- - - addons.js
- - - index.js
- - - rn-addons.js

It then told me to:

add the following to your entrypoint (usually App.js or index.js).

export {default} from "./storybook";

I wasn't sure what that means as storybook>index.js already has a default export:
export default StorybookUIRoot;

I then edited my root/storybook/index.js as there is no main.js in my project to the following:
// if you use expo remove this line
// import { AppRegistry } from 'react-native';

import { getStorybookUI, configure, addDecorator } from '@storybook/react-native';
// import { withKnobs } from '@storybook/addon-knobs';

import './rn-addons';

// enables knobs for all stories
// addDecorator(withKnobs);

// import stories
configure(() => {
  require('./stories');
}, module);

// Refer to https://github.com/storybookjs/react-native/tree/master/app/react-native#getstorybookui-options
// To find allowed options for getStorybookUI
const StorybookUIRoot = getStorybookUI({});

// If you are using React Native vanilla and after installation you don't see your app name here, write it manually.
// If you use Expo you should remove this line.
// AppRegistry.registerComponent('%APP_NAME%', () => StorybookUIRoot);

export default StorybookUIRoot;

After all this, I ran yarn storybook and it opened the webpage but the stories never load.
What am I doing wrong?!


text:
Q: Click add to insert another input field in php I need to add another input field of type select if someone clicks add location as seen in my code
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

 location

<select name="location">
    <option value="location1">location1</option>
    <option value="location2">location2</option>
    <option value="location3">location3</option>
    <option value="location4">location4</option>
</select>
Add location

</form>

I have a few more selects in the form tag but here is where i have a problem. i need to just add the field and not refresh any of the the data the person has added.Thankinging you for your replies.

A: You can use clone:
$('#newField').click(function(){
    $('select[name=location]:first').clone().insertAfter('select:last')
})

Fiddle
Note that you should not use # in your id attributes.
Add location
         //-----^


text:
Q: If I pass an array of multiple stylesheet objects to a react native view, will it deprive me of stylesheet optimizations provided by React-native? As per https://facebook.github.io/react-native/docs/stylesheet,
React-native provides, some optimizations if we create styles form stylesheet.
It also says that if we flatten stylesheet, we wont get those benefits.
But what if we do not flatten the stylesheet and instead use multiple styles ? will we get those optimizations ?
const styles = StyleSheet.create({
  bigBlue: {
    color: 'blue',
    fontWeight: 'bold',
    fontSize: 30
  },
  red: {
    color: 'red',
  },
});

<Text style={[styles.red, styles.bigBlue]}>{"red, then bigBlue"}</Text>

A: If you search react-native core code itself, you'd find more than 50 usages of the array usage.

Also you can find that usage as first-class citizen, with no notes or warnings whatsoever.
https://reactnative.dev/docs/stylesheet


text:
Q: Custom endpoint to get all custom taxonomy terms I'm trying to build a custom endpoint to get all terms from custom taxonomy

the taxonomy name is cats

I'm using this code
   function wl_cats() {
        $args = [
            'numberposts' => 99999,
            'taxonomy' => 'cats'
        ];
        $cats = get_terms('cats');
        $data = [];
        $i = 0;
        foreach($cats as $cat) {
            $data[$i]['id'] = $cat->ID;
            $data[$i]['title'] = $cat->the_title();
            $i++;
        }
        return $data;
    }
add_action('rest_api_init', function() {
    register_rest_route('wl/v1', 'cats', [
        'methods' => 'GET',
        'callback' => 'wl_cats',
    ]);

});

Is their any way better than that? because I got data null


text:
Q: How to initialize glut with fake parameters? I'm using opengl, using the GLUT and GLEW libraries to create a plugin for a certain application.
This plugin doesn't start with a simple int main(argc, argv). So i can't pass these values to glutInit().
I tried something like this:
glutInit(0, NULL); <--- Crash
GLenum err = glewInit();

But i crashed when it tried to call the glutInit() function. Can i reconstruct those params some how, so that it won't crash and still be able to use the Glut library..??

A: You can do it like this :
#include <GL/freeglut.h>

int main()
{
  char fakeParam[] = "fake";
  char *fakeargv[] = { fakeParam, NULL };
  int fakeargc = 1;

  glutInit( &fakeargc, fakeargv );

  //...
}

but take a note that it is an ugly hack.

A: You might have to call glutInit with a valid argv parameter, even if you don't have any:
char *my_argv[] = { "myprogram", NULL };
int   my_argc = 1;
glutInit(&my_argc, my_argv);

Edit
It might also be that the first parameter is a pointer to an int, and it can't be NULL? Then it might be enough to only pass a valid argc parameter:
int my_argc = 0;
glutInit(&my_argc, NULL);

A: Note the following code from the source (freeglut_init.c:677):
void FGAPIENTRY glutInit( int* pargc, char** argv )
{
    char* displayName = NULL;
    char* geometry = NULL;
    int i, j, argc = *pargc;
    ...

(Note the dereferencing.)
It seems that glutInit() does require a minimum of the process name, although the man page doesn't shed any light on this.

A: I propose this as a de-facto standard for initializing glut applications.
static inline void glutInstall()
{
    char *glut_argv[] = {
        "",
        (char *)0
    };
    int glut_argc = 0;

    glutInit(&my_argc, my_argv);
}

This function can be modified on per-application basis to provide glut with the arguments it needs(if any), while permanently solving the issue of everyone asking why you are passing command line arguments to a 3rd party library.


text:
Q: list.get().method generate cast exception I have written a code like this to fetch data from database using HQL:
Query qr=sess.createQuery("select i.contract_Vcode,i.installment_date from Installment i where i.vcode=:instalVcode").setParameter("instalVcode", installVcode);
        qr.getNamedParameters();
List<Installment> li=null;
        li=qr.list();
int coVcode=li.get(0).getContract_Vcode();

As I know the contract_Vcode is an integer. But when I want to run it, the followed error happens:
Error invoking Action using Hibernate Core Session / Transaction injection
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to information.Installment

More over when I want to see the exact element like this,
System.out.println("contract installDate is: "+li.get(0).getContract_Vcode());

Same error happens. How can I fix this?

A: You're currently only querying two parts of an installment. If you want to fetch the whole thing, I'd expect something like:
Query qr = sess.createQuery(
                    "select from Installment as i where i.vcode=:instalVcode")
               .setParameter("instalVcode", installVcode);

If you fetch multiple properties (instead of whole entities), you just get back an Object[] for each row in the results.
So you could use your original query, but:
List<Object[]> li = qr.list();
int coVcode = (Integer) li.get(0)[0]; // 1st column of 1st row


text:
Q: Creating emission matrix for Hidden Markov Model I'm using a Hidden Markov Model for gesture recognition. I have already created the transition matrix using data from a set of training data. I can't seem to find any sources for creating the emission matrix.
Could I create it like so?
B_ij = (# of transitions from state j to observation i)/(# of states j)

Note that I created the transition matrix in a similar way:
A_qs = (# transitions from state q to state s)/(# transitions from state q)

A: Yes, you are absolutely correct. To train the model from existing data, the emission probabilities for state j are set as (# times state j emitted symbol s) / (# times state j occurred).
If however you have many potential symbols that could be emitted, and/or a limited amount of training data, it can often be a good idea to use pseudocounts so that no potentially valid emission probability is set to 0.


text:
Q: Xamarin Sqlite filter textfield I have decided to use Xamarin (Visual Studio element) and I want to have a large textfield (Say 5000 Characters) which when you click a button searches an Sqlite database for entries which contains some keywords in that textfield.
I have done a little bit of experimenting but I have so far only been able to do a direct match: I.E: Database has an entry called "green tree" and only if I enter the term "Green Tree" will it start matching
 I would want to be able to enter: "It was a cold day and the green tree shook in the wind" and for the database entry "Green Tree" to appear.
Thanks in advance!!


text:
Q: Is it possible to get a callback on a parent function from an inner promise? Play with my JSfiddle
Is it possible to use $timeout promise to make scrollTo chainable like I've shown below? If not, how can I write scrollTo, as a promise, so that I may callback using then?
html:

click me

js:
app.controller('MainCtrl', function($scope, $timeout) {
    $scope.toTop = function() {
        var bodyEl = angular.element(document.querySelector('#body'));
        scrollTo_(bodyEl[0], 0, 500);

    };

    function scrollTo_(element, to, duration) {
        if (duration <= 0) {
                        $timeout.cancel(forward);
            console.log('yoyo');
            return forward;
        }
        var difference = to - element.scrollTop;
        var perTick = difference / duration * 10;
        var forward = $timeout(function() {
            element.scrollTop = element.scrollTop + perTick;
            scrollTo_(element, to, duration - 10);
        }, 10, false);
    }
});

A: this is how I would done the recursive promise:
function scrollTo_(element, to, duration) {
    if(duration<=0) return Promise.resolve();
    var difference = to - element.scrollTop,
        perTick = difference / duration * 10;
    return $timeout(function() {
        element.scrollTop = element.scrollTop + perTick;
    }, 10, false).then(function(){
      duration -= 10;
      return scrollTo_(element, to, duration)
    });
}

EDIT:
if you want to stop the timeout inbetween, I guess you could do something like:
var scrollTopTimeoutFlag = true, scrollTopTimeout;
function scrollTo_(element, to, duration) {
    if(duration<=0 || !scrollTopTimeoutFlag){
      if(scrollTopTimeout)  return $timeout.cancel(scrollTopTimeout);
      return $q.when();   // $q.when == Promise.resolve
    }
    var difference = to - element.scrollTop,
        perTick = difference / duration * 10;
    scrollTopTimeout = $timeout(function() {
        element.scrollTop = element.scrollTop + perTick;
    }, 10, false);
    return scrollTopTimeout.then(function(){
      duration -= 10;
      return scrollTo_(element, to, duration)
    });
}

A: It's difficult to interpret "use $timeout promise to make scrollTo chainable like I've shown below", since scrollTo isn't chainable.  So let's assume scrollTo is to be made "thenable", by having it return a $q promise.
With that assumption in place, it seems reasonable that the returned promise should be resolved on completion of the scroll, or rejected if the scroll is stopped before completion (by another scrollTo_() call).
Here goes :
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $q) {
    var stopSignal = false;
    $scope.toTop = function() {
        var element = angular.element(document.querySelector('#body'))[0];
        stopSignal = true; // stop previous.
        scrollTo_(0, 500).then(function() { // Yay, scrollTo_() is thenable!
            console.log('scroll complete');
        }, function() {
            console.log('scroll stopped');
        });
        function scrollTo_(to, duration) {
            var startTime = null,
                startPos = element.scrollTop,
                dfrd = $q.defer();
            function step(timestamp) {
                if(stopSignal) {
                    // This block kills an animation that's in progress.
                    // It doesn't affect freshly initiated animations.
                    stopSignal = false; // reset the `stopSignal` flag.
                    dfrd.reject(); // reject the deferred, to indicate non-completion
                    return; // prevent further animation by returning early and killing the recursion.
                }
                if (!startTime) {
                    stopSignal = false;
                    startTime = timestamp;
                }
                var progress = timestamp - startTime;
                if (progress < duration) {
                    element.scrollTop = startPos + (to - startPos) * progress / duration; // linear movement w.r.t. time, though not necessarily at regular intervals.
                    window.requestAnimationFrame(step); // recurse
                } else {
                    element.scrollTop = to; // ensure final position is accurate
                    dfrd.resolve();
                }
            }
            // This is horribly messy but necessary(?) for the stop signal to take effect.
            window.requestAnimationFrame(function() {
                stopSignal = false;
                window.requestAnimationFrame(step);
            });
            return dfrd.promise;
        }
    };
});

DEMO Double-click to see a scroll effect stopped before another starts.
As you can see, the 10ms timout-induced interval is avoided by dropping $timeout and :

*

*exploiting window.requestAnimationFrame(), which is the modern way to orchestrate animations (though browser compatibility is currently an issue, esp IE < 10) guaranteeing that each user gets the best possible update rate that his/her browser can manage under prevailing processor load.

*working at each step, from an established base-time, giving better guaranteed linearity of movement.

Before long everyone should be writing browser animations this way.


text:
Q: How to setup a WPF App with various features I want to create a WPF App in VS which should have various features (no serperate applications!).
The MainWindow should containt several Icon's (like App Icon's on Smartphone) which represents each of my features. So the MainWindow should be as an overview of my features. How do I need to realize it?

*

*Which toolbar object represents an Icon? (Button?)

*If I click on the Icon (Button?) the new feature should be showed as fullscreen (like on a Smartphone by clicking/starting an App). Which feature of WPF should I use to show the Page/Window of the Feature? If I close the feature the MainWindow should be showed again. I would be glad about a code example

Thanks

A: This question is likely too broad to get you the answers you are looking for, but a good place to start is with the Window class.
Once you create your buttons, you can spawn a new Window for your distinct feature. The Window.ShowDialog method will allow the new feature to remain active until it is closed. Setting the Window.Owner property will allow the new feature to return control to MainWindow.
I'd recommend trying some of these features out then coming back with specific questions you might have.
MainWindow.xaml
<Window x:class="MainWindow">
    <!-- ... -->
    <Button Click="Feature1_Click" Content="Open Feature 1"/>
    <Button Click="Feature2_Click" Content="Open Feature 2"/>
    <!-- ... -->
</Window>

MainWindow.xaml.cs
public class MainWindow : Window
{
    //...
    private void Feature1_Click(object sender, RoutedEventArgs e)
    {
        new Feature1Window
        {
            Owner = this
        }.ShowDialog();
    }

    private void Feature2_Click(object sender, RoutedEventArgs e)
    {
        new Feature2Window
        {
            Owner = this
        }.ShowDialog();
    }
    // ...
}


text:
Q: Change placeholders in Subject I'm trying to create a template where I can have VBA prompt me to change items in the subject. I've a template email with the subject line that should be Project / GC/Client, and in the template I've written that as #0# / #1#.
I'm at the below, but it's erroring.
Private Sub m_Inspector_Activate()

    Dim Item As MailItem
    Dim Value As String
    If TypeOf m_Inspector.CurrentItem Is MailItem Then
        Set mail = m_Inspector.CurrentItem
        If mail.Subject = "subject" Then
            Value = InputBox("Project")
            mail.Subject = Replace(mail.Subject, "#0#", Value)

            Value = InputBox("GC/Client")
            mail.Subject = Replace(mail.Subject, "#1#", Value)
        End If
    End If

End Sub

This code is used on a template button in Outlook. i.e. the template file it is launching contains the subject line of #0# / #1#. Ideally, after the template launches, the macro prompts the user to update those two fields with the proper subjects.
Sub CommandButton1_Click()
    Set MyItem = Application.CreateItemFromTemplate _
      ("V:\All Folders\Templates\Freebie.oft")
    MyItem.Display
End Sub

A: If all that you really want to do is open a template and replace text in the subject line, this may work for you:
Sub CommandButton1_Click()
    Call OpenTemplate
End Sub

Sub OpenTemplate()

    Dim OutMail As Outlook.MailItem
    Set OutMail = Application.CreateItemFromTemplate("V:\All Folders\Templates\Freebie.oft")

    On Error Resume Next
    With OutMail
        .To = ""
        .CC = ""
        .BCC = ""

        .Subject = Replace(.Subject, "#0#", InputBox("Project"))
        .Subject = Replace(.Subject, "#1#", InputBox("GC/Client"))

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing

End Sub

If we can avoid using the Inspector then this is much simpler


text:
Q: Want to print next biggest number So Here is the question:
Consider a class named Job that has deadline as a data member and relevant getter/setter
method(s). Assume you have to schedule two most earliest jobs on the basis of their deadlines. That is,
if there are three jobs in the system with deadlines (deadline1, deadline2, and deadline3, respectively)
then the system should report the top two earliest jobs (with smallest deadline value). You might need
to find the deadline with smallest and second most smallest value.
Here is my code:
#include<iostream>
using namespace std;
class job
{
private:
    int Deadline;
public:
    static int i;
    void setDeadline(int a);
    int getDeadline();
};

void job::setDeadline(int a)
{
    Deadline = a;
    cout << "Job " << i << " Has Deadline " << Deadline << endl;
}

int job::getDeadline()
{
    return Deadline;
}
int job::i = 1;

int main()
{
    job job1, job2, job3, job4, job5, job6, job7, job8, job9, job10, count;

    job1.setDeadline(5);
    count.i++;
    job2.setDeadline(3);
    count.i++;
    job3.setDeadline(6);
    count.i++;
    job4.setDeadline(12);
    count.i++;
    job5.setDeadline(31);
    count.i++;
    job6.setDeadline(20);
    count.i++;
    job7.setDeadline(19);
    count.i++;
    job8.setDeadline(2);
    count.i++;
    job9.setDeadline(8);
    count.i++;
    job10.setDeadline(7);

    int array[10] = { job1.getDeadline(), job2.getDeadline(),job3.getDeadline(),job4.getDeadline(),job5.getDeadline(),job6.getDeadline(),job7.getDeadline(),job8.getDeadline(),job9.getDeadline(),job10.getDeadline() };
    int temp = array[0], store = 0, first = 0, second = 0;

    for (int i = 0; i <= 9; i++)
    {
        if (temp > array[i])
        {
            temp = array[i];
        }
    }
    for (int i = 0; i <= 9; i++)
    {
        if (temp == array[i])
        {
            first = i + 1;
            break;
        }
    }
    temp = array[0];
    for (int i = 0; i <= 9; i++)
    {
        if (temp > array[i])
        {
            temp = array[i];
        }
    }
    for (int i = 0; i <= 9; i++)
    {
        if (temp == array[i])
        {
            second = i + 1;
        }
    }
    cout << "\nJob " << first << " and Job " << second << " are earliest";
    return 0;
}

the problem I am facing is that both times it print the first smallest value. I want to print first 2 smallest value. How can I do that?

A: When you look for the first value, you go through the array and find the job with the lowest deadline and fill "first" with the job id (by the way, if you want to relate the "job id" to the index, personally I would make the variables zero-based, so job0, job1 and so on up to job9)
When you look for the second value, you do the exact same operations so the job you find is again the job with the lowest deadline and use that info to fill "second".
So, as you do the exact same thing both times, you are getting the exact same value for both. When you search for the second value you should take "first" into account so that you ignore the job that has already been used for "first" and not update "temp" in that case (this is a little bit easier if you name the jobs starting with zero because you don't have to constantly add one to the index).

A:
the problem I am facing is that both times it print the first smallest value. I want to print first 2 smallest value. How can I do that?

With your solution: By creating another temp array with the first element removed you already discovered.
I wrote you as a minimal executable example using a vector of pairs since you didn't mention restrictions or anything - that is the most elegant solution I am able to come up with:
#include <iostream>
#include <vector>
#include <string>

bool sortVecBySec(const std::pair<std::string, int> &a,
                    const std::pair<std::string, int> &b)
 {
   return (a.second < b.second);
 }

int main()
{

  //Driver function to sort the vector elements by
  //the second element of pairs
  std::vector<std::pair <std::string,int>> v;
  std::string job[10];
  int deadline[10] = {5,3,6,12,31,20,19,2,8,7};
  int n = sizeof(job)/sizeof(job[0]);

  //Propagate string array
  for(int i{}; i < 10;++i){
    job[i] = "Job " + (std::to_string(i+1));
  }

  //Enter values in vector of pairs
  for(int i{}; i<n; ++i){
    v.push_back(make_pair(job[i],deadline[i]));
  }

  //Printing the vector of pairs
  std::cout << "Vector of pairs as it is before\n";
  for(int i{}; i< n; i++){
    std::cout << v[i].first << " = " <<v[i].second << '\n';
  }

  //Using sort() function to sort by 2nd element of pairs
  sort(v.begin(), v.end(),sortVecBySec);

  //Printing the vector of pairs
  std::cout << "\nVector of pairs from shortest to longest\n";
  for(int i{}; i< 2; i++){
    std::cout << v[i].first << " = " <<v[i].second << '\n';
  }

  std::cin.get();
  return 0;
}

If you want to print all jobs, just use the n variable in the last print section instead of 2.
I think that should help you and shouldn't be to hard to parse it in a class.

A: First, you can save an extra round by saving the index right there, when you locate the earliest deadline
for (int i = 0; i <= 9; i++)
{
    if (temp > array[i])
    {
        temp = array[i];
        first = i + 1;
    }
}

When searching for the next higher deadline value, you must take first into account. Both for the start value, and later when comparing with other values
temp = first > 1 ? array[0] : array[1];
for (int i = 0; i <= 9; i++)
{
    if (temp > array[i] && array[i] > array[first])
    {
        temp = array[i];
        second = i + 1;
    }
}

Be aware, that this does not work properly, when you have multiple equal values.
For this case, compare the index values instead, e.g.
    if (temp > array[i] && i != first)
    {
        temp = array[i];
        second = i + 1;
    }


text:
Q: Php cannot redeclare a function twice Why is php not able to declare a function more than one time? I am using while loop with mySQL that contains list of IDs and I am trying to parse the ID to this function. But I get Fatal error: Cannot redeclare GetValue() (previously declared.... How do I fix this?
<?php
session_start();
ob_start();

$id = "";
$db = new PDO("mysql:host=localhost; dbname="DB";charset=utf8",'uid','');

$sqlID = "SELECT ID FROM Zip";
$stmtID = $db->query($sqlID);

$pdfArray = array();

while($dataID = $stmtID->fetch(PDO::FETCH_OBJ)){

    $id = $dataID->ID;

    $sql = "SELECT * FROM Datas WHERE ID = '$id'";
    $stmt = $db->query($sql);
    GetValue($id);
}

function GetValue($x){

//
}

?>

A: instead of:
GetValue($x){

//
}

try:
function GetValue($x){

//
}


text:
Q: orderBy() Specific Order Defined by Array I have 4 types of phones that are defined in an array by ID. ['1. Primary', '2. Home', '3. Mobile', '4. Work']. Users must have one filled out at minimum but could be multiple. We don't know which one(s) they decided to enter.
In this specific case I want to setup a scopeFunction that pulls the Mobile Phone. If the user doesn't have a mobile phone, I want to setup a fallback to Primary, if no Primary, Home, etc..
public function scopeMobile($query, $uuid) {
    return $query->phone()
        ->where('uuid', $uuid)
        ->whereIn('phone_type_id', [3,1,2,4]);
}

Function Calling that Scope
public static function mobile_phone($uuid) {
    return self::mobile($uuid)->get();
}

I'm looking for a way to achieve this type of scenario where the order will fallback matching the ->whereIn([3,1,2,4]).  I know this isn't valid but something similar to this ->orderBy([3,1,2,4]).
If I do an ->orderBy('phone_type_id', 'desc') it will pull in order of 4,3,2,1 and ->orderBy('phone_type_id', 'asc') will pull an order of 1,2,3,4.
Is it possible or how can I get this to order as [3,1,2,4] within the scopeFunction?


text:
Q: Tabular: continue to the next line if too long horizontally I have written a python program that reads in columns from a spreadsheet and produces a feedback sheet in LaTeX for students like so:

The issue I have is that the number of columns is variable, and depends on the task I have chosen.
Sometimes, there are too many columns and the latex table produced therefore goes off the edge of the page:

Ideally, I would like latex to recognise that the table has exceeded the edge of the page and just continue it beneath.
Is there any way of doing this? Otherwise, I will need to write some code that will have to chop it up before hand, which is not ideal.
EDIT: the width of the table is unknown before hand: it depends on the number of questions and the description of the questions, hence a dynamic continuation automatically determined by LaTeX is better.

A: Don't use one but many tabulars. Add \hspace{0pt} between the tabulars to get a break point, and use \raggedright:
\documentclass{article}
\textwidth=10cm
\begin{document}
\raggedright
\begin{tabular}{l}
\hline
Q1\\
Beta Decay Equation\\
\hline
yes\\\hline
\end{tabular}\hspace{0pt}%
\begin{tabular}{l}
\hline
Q1\\
Beta Decay Equation\\
\hline
yes\\\hline
\end{tabular}\hspace{0pt}%
\begin{tabular}{l}
\hline
Q1\\
Beta Decay Equation\\
\hline
yes\\\hline
\end{tabular}\hspace{0pt}%
\end{document}

A: If the form is always with 3 rows, you could as well change to vertical and use longtable:
\documentclass[]{article}

\usepackage{amssymb,longtable}

\begin{document}
\begin{longtable}{l|lc}
    Q1 & Beta Decay Equations & \checkmark\\
    Q2 & Alpha Decay Equations & \checkmark\\
    Q3 & Changes to the Nucleus & \checkmark
\end{longtable}
\end{document}


text:
Q: String Manipulation: Spliting Delimitted Data I need to split some info from a asterisk delimitted data.
Data Format:
NAME*ADRESS LINE1*ADDRESS LINE2

Rules:
1. Name should be always present
2. Address Line 1 and 2 might not be
3. There should be always three asterisks.

Samples:
MR JONES A ORTEGA*ADDRESS 1*ADDRESS2*

Name: MR JONES A ORTEGA
Address Line1: ADDRESS 1
Address Line2: ADDRESS 2

A PAUL*ADDR1**
Name: A PAUL
Address Line1: ADDR1
Address Line2: Not Given

My algo is:
1. Iterate through the characters in the line
2. Store all chars in a temp variables until first * is found. Reject the data if no char is found before first occurence of asterisk. If some chars found, use it as the name.
3. Same as step 2 for finding address line 1 and 2 except that this won't reject the data if no char is found

My algo looks ugly. The code looks uglier. Spliting using //* doesn't work either since name can be replaced with address line 1 if the data was *Address 1*Address2. Any suggestion?
EDIT:
Try using the data excluding quotes "-MS DEBBIE GREEN*1036 PINEWOOD CRES**"

A: You can use the String[] split(String regex, int limit) as follows:
    String[] tests = {
        "NAME*ADRESS LINE1*ADDRESS LINE2*",
        "NAME*ADRESS LINE1**",
        "NAME**ADDRESS LINE2*",
        "NAME***",
        "*ADDRESS LINE1*ADDRESS LINE2*",
        "*ADDRESS LINE1**",
        "**ADDRESS LINE2*",
        "***",
        "-MS DEBBIE GREEN*1036 PINEWOOD CRES**",
    };
    for (String test : tests) {
        test = test.substring(0, test.length() - 1);
        String[] parts = test.split("\\*", 3);
        System.out.printf(
            "%s%n  Name: %s%n  Address Line1: %s%n  Address Line2: %s%n%n",
            test, parts[0], parts[1], parts[2]
        );
    }

This prints (as seen on ideone.com):
NAME*ADRESS LINE1*ADDRESS LINE2*
  Name: NAME
  Address Line1: ADRESS LINE1
  Address Line2: ADDRESS LINE2

NAME*ADRESS LINE1**
  Name: NAME
  Address Line1: ADRESS LINE1
  Address Line2:

NAME**ADDRESS LINE2*
  Name: NAME
  Address Line1:
  Address Line2: ADDRESS LINE2

NAME***
  Name: NAME
  Address Line1:
  Address Line2:

*ADDRESS LINE1*ADDRESS LINE2*
  Name:
  Address Line1: ADDRESS LINE1
  Address Line2: ADDRESS LINE2

*ADDRESS LINE1**
  Name:
  Address Line1: ADDRESS LINE1
  Address Line2:

**ADDRESS LINE2*
  Name:
  Address Line1:
  Address Line2: ADDRESS LINE2

***
  Name:
  Address Line1:
  Address Line2:

-MS DEBBIE GREEN*1036 PINEWOOD CRES**
  Name: -MS DEBBIE GREEN
  Address Line1: 1036 PINEWOOD CRES
  Address Line2:

The reason for the "\\*" is because split takes a regular expression, and * is a regex metacharacter, and since you want it to mean literally, it needs to be escaped with a \. Since \ itself is a Java string escape character, to get a \ in a string, you need to double it.
The reason for the limit of 3 is because you want the array to have 3 parts, including trailing empty strings. A limit-less split discards trailing empty strings by default.
The last * is discarded manually before the split is performed.

A: String myLine = "name*addr1*addr2*"
String[] parts = myLine.split('\\*',4);
for (String s : parts) {
    System.out.println(s);
}

Output:
name
addr1
addr2
(empty string)

If you do split on "**addr2*" - you will get array with "","","addr2". So I don't get it why you can't use split.
Also, if you split "***" - you will get a 4 element array with 4 empty strings.
Here you get an example, try running this code:
public void testStrings() {
    String line = "part0***part3*part4****part8*";
    String[] parts = line.split("\\*");
    for (int i=0;i<parts.length;i++) {
        System.out.println(String.format("parts[%d]: '%s'",i, parts[i]));
    }
}

Result will be:
parts[0]: 'part0'
parts[1]: ''
parts[2]: ''
parts[3]: 'part3'
parts[4]: 'part4'
parts[5]: ''
parts[6]: ''
parts[7]: ''
parts[8]: 'part8'

A: You can use regex to do this. For example:
String myInput="MR JONES A ORTEGA*ADDRESS 1*ADDRESS2*";

Pattern pattern =  Pattern.compile("([^*]+)\\*([^*]*)\\*([^*]*)\\*");
Matcher matcher = pattern.matcher(myInput);

if (matcher.matches()) {
    String myName = matcher.group(1);
    String myAddress1 = matcher.group(2);
    String myAddress2 = matcher.group(3);
    // ...
} else {
    // input does not match the pre-requisites
}

A: A complete solution, reading from file using scanner and regular expressions:
import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner s = new Scanner(new File("data.txt"));
        Pattern p = Pattern.compile("([^\\*]+)\\*([^\\*]*)\\*([^\\*]*)\\*");

        while (s.hasNextLine()) {
            if (s.findInLine(p) == null) {
                s.nextLine();
                continue;
            }

            System.out.println("Name: " + s.match().group(1));
            System.out.println("Addr1: " + s.match().group(2));
            System.out.println("Addr2: " + s.match().group(3));
            System.out.println();
        }
    }
}

Input file:
MR JONES A ORTEGA*ADDRESS 1*ADDRESS2*
A PAUL*ADDR1**
*No name*Addr 2*
My Name*Some Addr*Some more addr*

Output:
Name: MR JONES A ORTEGA
Addr1: ADDRESS 1
Addr2: ADDRESS2

Name: A PAUL
Addr1: ADDR1
Addr2:

Name: My Name
Addr1: Some Addr
Addr2: Some more addr

Note that the line with no name is not matched (as according to Rule 1: Name should be always present). If you still want to process these lines, simply change the + in the regular expressions, to a *.
The regular expressions ([^\\*]*)\\* can be read out as: "Anything except an asterisk, zero or more times, followed by an asterisk."

A: yourString.split("\\*"); should give you an array with name, address1 and address2, where as adress1 and address2 can be empty Srings. More information: here


text:
Q: Reading a JSON reply from WeatherUnderground package test;

import java.net.*;
import java.io.*;
import com.google.gson.*;
import com.google.gson.stream.JsonReader;

public class TestGson {

    URL callToApi;
//------------------------------------------------------------------------------
    public static void main(String[] args) {
        new TestGson();
    }
//------------------------------------------------------------------------------
    public TestGson(){
        try{
            sendCallToApi();
            readJson();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
//------------------------------------------------------------------------------
    public void sendCallToApi(){
        try{
            callToApi = new URL("http://api.wunderground.com/api" +
                    "/[insert key here]" +
                    "/geolookup/conditions/forecast/q/" +
                    "Australia/" +
                    "Sydney.json");
        }catch(MalformedURLException e){
            e.printStackTrace();
        }
    }
//------------------------------------------------------------------------------
    public void readJson() throws IOException{
    Gson g = new Gson();
    InputStreamReader in = new InputStreamReader(callToApi.openStream());
    BufferedReader reader = new BufferedReader(in);
    String message = "hello";
    StringBuffer buf = new StringBuffer();

    while(message!=null){
        message = reader.readLine();
        buf.append(message);
    }
    message = buf.toString();
    String wdf = g.fromJson(message, String.class);
    System.out.println(wdf);
}
//------------------------------------------------------------------------------
}

This is my first attempt at parsing JSON using GSON. I am simply making a call to the Weather Underground site asking them to send me the weather of Sydney, Australia.
However, I get multiple errors:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
    at com.google.gson.Gson.fromJson(Gson.java:806)
    at com.google.gson.Gson.fromJson(Gson.java:761)
    at com.google.gson.Gson.fromJson(Gson.java:710)
    at com.google.gson.Gson.fromJson(Gson.java:682)
    at test.TestGson.readJson(TestGson.java:49)
    at test.TestGson.<init>(TestGson.java:19)
    at test.TestGson.main(TestGson.java:13)
Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
    at com.google.gson.stream.JsonReader.nextString(JsonReader.java:464)
    at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:349)
    at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:337)
    at com.google.gson.Gson.fromJson(Gson.java:795)
    ... 6 more

What is causing those errors? How do I properly make the call to the Weather Underground API to receive the weather info?
I tried this by modifying the example given on Mykong.com.
 JSON Reply from Weather Underground
{   "response": {       "version": "0.1"        ,"termsofService": "http://www.wunderground.com/weather/api/d/terms.html"       ,"features": {      "geolookup": 1      ,       "conditions": 1     ,       "forecast": 1       }   }       ,   "location": {       "type":"INTLCITY",      "country":"SD",     "country_iso3166":"SA",     "country_name":"Saudi Arabia",      "state":"",     "city":"Jeddah",        "tz_short":"AST",       "tz_long":"Asia/Riyadh",        "lat":"21.67000008",        "lon":"39.15000153",        "zip":"00000",      "magic":"1",        "wmo":"41024",      "l":"/q/zmw:00000.1.41024",     "requesturl":"global/stations/41024.html",      "wuiurl":"http://www.wunderground.com/global/stations/41024.html",      "nearby_weather_stations": {        "airport": {        "station": [        { "city":"Jeddah King Abdul Aziz International Airport", "state":"", "country":"Saudi Arabia", "icao":"OEJN", "lat":"21.70000076", "lon":"39.18333435" },       { "city":"Jeddah", "state":"", "country":"SD", "icao":"OEJN", "lat":"21.67000008", "lon":"39.15000153" },       { "city":"Makkah", "state":"", "country":"SD", "icao":"OEMK", "lat":"21.43000031", "lon":"39.77000046" }        ]       }       ,       "pws": {        "station": [        ]       }       }   }       ,   "current_observation": {        "image": {      "url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",      "title":"Weather Underground",      "link":"http://www.wunderground.com"        },      "display_location": {       "full":"Jeddah, Saudi Arabia",      "city":"Jeddah",        "state":"",     "state_name":"Saudi Arabia",        "country":"SD",     "country_iso3166":"SA",     "zip":"00000",      "latitude":"21.67000008",       "longitude":"39.15000153",      "elevation":"12.00000000"       },      "observation_location": {       "full":"Jeddah, ",      "city":"Jeddah",        "state":"",     "country":"SD",     "country_iso3166":"SA",     "latitude":"21.67000008",       "longitude":"39.15000153",      "elevation":"39 ft"     },      "estimated": {      },      "station_id":"OEJN",        "observation_time":"Last Updated on February 12, 9:00 AM AST",      "observation_time_rfc822":"Tue, 12 Feb 2013 09:00:00 +0300",        "observation_epoch":"1360648800",       "local_time_rfc822":"Tue, 12 Feb 2013 09:08:53 +0300",      "local_epoch":"1360649333",     "local_tz_short":"AST",     "local_tz_long":"Asia/Riyadh",      "local_tz_offset":"+0300",      "weather":"Clear",      "temperature_string":"77 F (25 C)",     "temp_f":77,        "temp_c":25,        "relative_humidity":"57%",      "wind_string":"From the North at 10 MPH",       "wind_dir":"North",     "wind_degrees":10,      "wind_mph":10,      "wind_gust_mph":0,      "wind_kph":17,      "wind_gust_kph":0,      "pressure_mb":"1011",       "pressure_in":"29.86",      "pressure_trend":"0",       "dewpoint_string":"61 F (16 C)",        "dewpoint_f":61,        "dewpoint_c":16,        "heat_index_string":"NA",       "heat_index_f":"NA",        "heat_index_c":"NA",        "windchill_string":"NA",        "windchill_f":"NA",     "windchill_c":"NA",     "feelslike_string":"77 F (25 C)",       "feelslike_f":"77",     "feelslike_c":"25",     "visibility_mi":"N/A",      "visibility_km":"N/A",      "solarradiation":"",        "UV":"-1",      "precip_1hr_string":"-9999.00 in (-9999.00 mm)",        "precip_1hr_in":"-9999.00",     "precip_1hr_metric":"-9999.00",     "precip_today_string":"0.00 in (0.0 mm)",       "precip_today_in":"0.00",       "precip_today_metric":"0.0",        "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "forecast_url":"http://www.wunderground.com/global/stations/41024.html",        "history_url":"http://www.wunderground.com/history/airport/OEJN/2013/2/12/DailyHistory.html",       "ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=21.67000008,39.15000153"    }       ,   "forecast":{        "txt_forecast": {       "date":"3:00 AM AST",       "forecastday": [        {       "period":0,     "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "title":"Tuesday",      "fcttext":"Clear in the morning, then partly cloudy. High of 84F. Breezy. Winds from the NNW at 10 to 20 mph.",     "fcttext_metric":"Clear in the morning, then partly cloudy. High of 29C. Breezy. Winds from the NNW at 15 to 30 km/h.",     "pop":"0"       }       ,       {       "period":1,     "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "title":"Tuesday Night",        "fcttext":"Clear. Low of 70F. Winds from the NNW at 10 to 15 mph.",     "fcttext_metric":"Clear. Low of 21C. Breezy. Winds from the NNW at 15 to 25 km/h.",     "pop":"0"       }       ,       {       "period":2,     "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "title":"Wednesday",        "fcttext":"Clear in the morning, then partly cloudy. High of 88F. Winds from the NNW at 5 to 15 mph.",      "fcttext_metric":"Clear in the morning, then partly cloudy. High of 31C. Breezy. Winds from the NNW at 10 to 25 km/h.",     "pop":"0"       }       ,       {       "period":3,     "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "title":"Wednesday Night",      "fcttext":"Clear in the evening, then partly cloudy. Low of 70F. Winds from the NW at 5 to 15 mph.",        "fcttext_metric":"Clear in the evening, then partly cloudy. Low of 21C. Breezy. Winds from the NW at 10 to 25 km/h.",       "pop":"0"       }       ,       {       "period":4,     "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "title":"Thursday",     "fcttext":"Clear in the morning, then partly cloudy. High of 88F. Winds from the North at 5 to 10 mph shifting to the WSW in the afternoon.",       "fcttext_metric":"Clear in the morning, then partly cloudy. High of 31C. Winds from the North at 5 to 15 km/h shifting to the WSW in the afternoon.",       "pop":"0"       }       ,       {       "period":5,     "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "title":"Thursday Night",       "fcttext":"Clear. Low of 73F. Winds from the WNW at 5 to 10 mph.",      "fcttext_metric":"Clear. Low of 23C. Winds from the WNW at 5 to 15 km/h.",      "pop":"0"       }       ,       {       "period":6,     "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "title":"Friday",       "fcttext":"Clear. High of 88F. Winds from the NNE at 5 to 10 mph shifting to the WSW in the afternoon.",        "fcttext_metric":"Clear. High of 31C. Winds from the NNE at 5 to 20 km/h shifting to the WSW in the afternoon.",        "pop":"0"       }       ,       {       "period":7,     "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "title":"Friday Night",     "fcttext":"Clear. Low of 72F. Winds from the NW at 5 to 10 mph.",       "fcttext_metric":"Clear. Low of 22C. Winds from the NW at 5 to 15 km/h.",       "pop":"0"       }       ]       },      "simpleforecast": {     "forecastday": [        {"date":{   "epoch":"1360692000",   "pretty":"9:00 PM AST on February 12, 2013",    "day":12,   "month":2,  "year":2013,    "yday":42,  "hour":21,  "min":"00", "sec":0,    "isdst":"0",    "monthname":"February", "weekday_short":"Tue",  "weekday":"Tuesday",    "ampm":"PM",    "tz_short":"AST",   "tz_long":"Asia/Riyadh"},       "period":1,     "high": {       "fahrenheit":"84",      "celsius":"29"      },      "low": {        "fahrenheit":"70",      "celsius":"21"      },      "conditions":"Partly Cloudy",       "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "skyicon":"mostlysunny",        "pop":0,        "qpf_allday": {     "in": 0.00,     "mm": 0.0       },      "qpf_day": {        "in": 0.00,     "mm": 0.0       },      "qpf_night": {      "in": 0.00,     "mm": 0.0       },      "snow_allday": {        "in": 0,        "cm": 0     },      "snow_day": {       "in": 0,        "cm": 0     },      "snow_night": {     "in": 0,        "cm": 0     },      "maxwind": {        "mph": 17,      "kph": 27,      "dir": "NW",        "degrees": 317      },      "avewind": {        "mph": 14,      "kph": 22,      "dir": "NW",        "degrees": 324      },      "avehumidity": 52,      "maxhumidity": 74,      "minhumidity": 43       }       ,       {"date":{   "epoch":"1360778400",   "pretty":"9:00 PM AST on February 13, 2013",    "day":13,   "month":2,  "year":2013,    "yday":43,  "hour":21,  "min":"00", "sec":0,    "isdst":"0",    "monthname":"February", "weekday_short":"Wed",  "weekday":"Wednesday",  "ampm":"PM",    "tz_short":"AST",   "tz_long":"Asia/Riyadh"},       "period":2,     "high": {       "fahrenheit":"88",      "celsius":"31"      },      "low": {        "fahrenheit":"70",      "celsius":"21"      },      "conditions":"Partly Cloudy",       "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "skyicon":"partlycloudy",       "pop":0,        "qpf_allday": {     "in": 0.00,     "mm": 0.0       },      "qpf_day": {        "in": 0.00,     "mm": 0.0       },      "qpf_night": {      "in": 0.00,     "mm": 0.0       },      "snow_allday": {        "in": 0,        "cm": 0     },      "snow_day": {       "in": 0,        "cm": 0     },      "snow_night": {     "in": 0,        "cm": 0     },      "maxwind": {        "mph": 14,      "kph": 22,      "dir": "NW",        "degrees": 308      },      "avewind": {        "mph": 12,      "kph": 19,      "dir": "NW",        "degrees": 315      },      "avehumidity": 51,      "maxhumidity": 75,      "minhumidity": 39       }       ,       {"date":{   "epoch":"1360864800",   "pretty":"9:00 PM AST on February 14, 2013",    "day":14,   "month":2,  "year":2013,    "yday":44,  "hour":21,  "min":"00", "sec":0,    "isdst":"0",    "monthname":"February", "weekday_short":"Thu",  "weekday":"Thursday",   "ampm":"PM",    "tz_short":"AST",   "tz_long":"Asia/Riyadh"},       "period":3,     "high": {       "fahrenheit":"88",      "celsius":"31"      },      "low": {        "fahrenheit":"73",      "celsius":"23"      },      "conditions":"Partly Cloudy",       "icon":"partlycloudy",      "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",       "skyicon":"mostlysunny",        "pop":0,        "qpf_allday": {     "in": 0.00,     "mm": 0.0       },      "qpf_day": {        "in": 0.00,     "mm": 0.0       },      "qpf_night": {      "in": 0.00,     "mm": 0.0       },      "snow_allday": {        "in": 0,        "cm": 0     },      "snow_day": {       "in": 0,        "cm": 0     },      "snow_night": {     "in": 0,        "cm": 0     },      "maxwind": {        "mph": 9,       "kph": 14,      "dir": "West",      "degrees": 259      },      "avewind": {        "mph": 7,       "kph": 11,      "dir": "WSW",       "degrees": 250      },      "avehumidity": 51,      "maxhumidity": 69,      "minhumidity": 37       }       ,       {"date":{   "epoch":"1360951200",   "pretty":"9:00 PM AST on February 15, 2013",    "day":15,   "month":2,  "year":2013,    "yday":45,  "hour":21,  "min":"00", "sec":0,    "isdst":"0",    "monthname":"February", "weekday_short":"Fri",  "weekday":"Friday", "ampm":"PM",    "tz_short":"AST",   "tz_long":"Asia/Riyadh"},       "period":4,     "high": {       "fahrenheit":"88",      "celsius":"31"      },      "low": {        "fahrenheit":"72",      "celsius":"22"      },      "conditions":"Clear",       "icon":"clear",     "icon_url":"http://icons-ak.wxug.com/i/c/k/clear.gif",      "skyicon":"mostlysunny",        "pop":0,        "qpf_allday": {     "in": 0.00,     "mm": 0.0       },      "qpf_day": {        "in": 0.00,     "mm": 0.0       },      "qpf_night": {      "in": 0.00,     "mm": 0.0       },      "snow_allday": {        "in": 0,        "cm": 0     },      "snow_day": {       "in": 0,        "cm": 0     },      "snow_night": {     "in": 0,        "cm": 0     },      "maxwind": {        "mph": 10,      "kph": 16,      "dir": "WSW",       "degrees": 248      },      "avewind": {        "mph": 7,       "kph": 11,      "dir": "WSW",       "degrees": 248      },      "avehumidity": 53,      "maxhumidity": 60,      "minhumidity": 38       }       ]       }   }}null

A: You don't seem to understand what Gson does. It's a JSON parser, specifically one that will deserialize JSON to a Java POJO.
In your code you have:
String wdf = g.fromJson(message, String.class);

You're telling Gson to deserialize the JSON to a Java String object. It can't do that; your JSON isn't a String object - it's a big JSON object returned from Weather Underground. You already have a Java String (message) that contains the JSON text itself.
You either need to create a POJO that the JSON can be deserialized to, or pick the parts out of the JSON you want using Gson's parser and associated objects/methods.
Here's the start of what a POJO would look like (all fields public with no getters/setters just to make this example small):
class MyWUPojo {
    public Response response;
    // more after this that match the JSON
}

class Response {
    public String version;
    public String termsofservice;
    public Map<String, Integer> features;
}

You'd then deserialize the JSON into an instance of MyWUPojo with:
MyWUPojo wup = new Gson().fromJson(message,MyWUPojo.class);

If you didn't want to go the POJO route you could parse the JSON then get what you want from it:
JsonObject o = (JsonObject) new JsonParser().parse(message);

Now you' can use the various methods of JsonObject to access the parsed JSON. (See: http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonObject.html )
The GSON User's Guide is pretty well written and explains this and more in great detail.
Edit to add: That null at the end of your JSON is caused by this:
while(message!=null){
    message = reader.readLine();
    buf.append(message);
}

You append null then the loop exits. It needs to be:
while ((message = reader.readline()) != null) {
    buf.append(message);
}


text:
Q: Payment method token is invalid when I create subscription in Braintree I want to create a subscription using Braintree using Python and JS.
But I get an error:
'errors': <braintree.errors.Errors object at 0xb0d157cc>, 'transaction': None, 'subscription': None, 'message': 'Payment method token is invalid.', 'credit_card_verification': None, 'merchant_account': None

The way how I create token and subscription
    token = braintree.ClientToken.generate({
        "customer_id": self.braintree_customer.id
    })

    create_subscriptions = braintree.Subscription.create({
        "payment_method_token": token,
        "plan_id": self.plan_id
    })

A: The Subscription needs a Payment Method Token, not a Client Token:
https://developers.braintreepayments.com/javascript+php/reference/request/client-token/generate
https://developers.braintreepayments.com/javascript+php/reference/request/subscription/create#payment_method_token


text:
Q: Jhipster fails with: "[HPM] Error occurred while trying to proxy request /management/info from localhost:9000 to http://localhost:8080 (ECONNREFUSED)" I am trying to create a simple project skeleton using jhipster.
# Ubuntu 18.04
node -v
# v10.15.1
npm -v
# 6.4.1
jhipster --version
# 6.0.0
jhipster
# (I only press enter, so that the defaults are selected)
npm start

Now I access the application on port 9000, but when I try to login with admin/admin as prompted, it fails
[HPM] Error occurred while trying to proxy request /management/info from localhost:9000 to http://localhost:8080 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /api/account from localhost:9000 to http://localhost:8080 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] Error occurred while trying to proxy request /api/authenticate from localhost:9000 to http://localhost:8080 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

The same when I try to register a new user from the app.
Is this a bug of the application, or am I doing something wrong?

A: You are only running the frontend, you also need to start backend as @Jon Ruddell comments. On the application directory you have to run:
./mvnw (or mvnw if you are on Windows).

Running the Java server
As a "main" Java class
From your IDE,
right-click on the "Application" class at the root of your Java
package hierarchy, and run it directly. You should also be able to
debug it as easily.
The application will be available on http://localhost:8080.
This application will have "hot reload" enabled by default, so if you
compile a class, the Spring application context should refresh itself
automatically, without the need to restart the server.
As a Maven project
You can launch the Java server with Maven. JHipster
provides a Maven wrapper, so you don't need to install Maven, and you
have the guarantee that all project users have the same Maven version:
./mvnw (on Mac OS X/Linux) of mvnw (on Windows)
(this will run our default Maven task, spring-boot:run)
The application will be available on http://localhost:8080.
Alternatively, if you have installed Maven, you can launch the Java
server with Maven:
mvn
If you want more information on using Maven, please go to
http://maven.apache.org
(Optional) As a Gradle project
If you selected the Gradle option,
JHipster provides a Gradle wrapper, so you don't need to install
Gradle, and you have the guarantee that all project users have the
same Gradle version:
./gradlew (on Mac OS X/Linux) of gradlew (on Windows)
(this will run our default Gradle task, bootRun)
Alternatively, if you have installed Gradle, you can launch the Java
server with Gradle:
gradle
The application will be available on http://localhost:8080.
If you want more information on using Gradle, please go to
https://gradle.org

source: https://www.jhipster.tech/development/


text:
Q: How to check parameter value which match with which record in mysql I have a problem to check parameter value with records value. I try to show the latest Rom Core update based on parameter. The Rom Core version sometimes have revision. There are two records to be check. Detail as below :
Parameter:
Model = DPX5000BTITA9N
Serial = 063X1200

Record Value:
Model           Startserial     Romcore
DPX5000BTITA9N  063X0001        SYS17-127
DPX5000BTITA9N  063X1001        SYS17-130`

How to check serial 063X1200 whether include in Startserial : 063X0001 or 063X1001 cause there is nothing Endserial?
Select Romcore From Version WHERE model LIKE 'DPX5000BTITA9N' AND serial <= '063X1200'(check the serial match with which Startserial)

I expect the output SYS17-130 cause :
If serial >= 063X0001 will get SYS17-127
If serial >= 063X1001 will get SYS17-130

But the actual output is both SYS17-127 & SYS17-130.

A: Maybe you want to order the results and get the latest one?
Select Romcore From Version
WHERE model LIKE 'DPX5000BTITA9N'
AND serial <= '063X1200'
order by serial desc
limit 1


text:
Q: What do the numbers in Youtube Suggestion API mean? Here is a portion of the response from Youtube Suggestion API for the URL (https://clients1.google.com/complete/search?client=youtube&q=b%20walmart&gl=&jsonp=jsonpCB&_=1600401501454)
[
  "b walmart",
  [
    [
      "walmart b complex",
      0,
      [
        22,
        30
      ]
    ],
    [
      "b walmart",
      0
    ],
    [
      "walmart b&m",
      0,
      [
        22,
        30
      ]
    ]
  ],
  {
    "k": 1,
    "q": "295XbO_S8qtvvBAI-FdfMCmHaHk"
  }
]

Could someone help me understand the significance of the numbers?
Thanks.


text:
Q: Search a string with strstr in a part of an char * currently I search a char * with strstr but I dont want to search in the complete one, only from the 42. char to the end.
How can I achieve this?

A: Just provide strstr() with a pointer to the first character to include in the seach:
if(strstr(the_haystack + 42, "the needle") != NULL)
  printf("found needle at end of haystack!\n");

Of course, this assumes that the_haystack really is at least 42 characters long.

A: Add 42 to the original str pointer (beware that original string length is greater than 42 though):
first_occurence = strstr(str + 42, substr);


text:
Q: With meteor and iron router how can the same controller and publish function be used to publish different parts of a collection How can a Controller.extend({}) set a variable to be sent though Meteor.subscribe(); used in mongodb query. This can be done by creating whole new controller and putting a static variable in the subscribe function. ex Meteor.subscribe('collection', this.findOptions(),static variable); The problem is that creates a lot of redundant code. Where as setting the variable in the Controller.extend({}) would not.

A: If you define a waitOn function that gathers the subscription(s) then you could do it there. I have some patterns like that in my app. For example a route used for a campaign landing page:
Router.route('/c/:token',{ // This route takes a token parameter
  name: 'campaign',
  controller: 'anonymousController',
  layoutTemplate: 'layout',
  waitOn: function(){
    return Meteor.subscribe('campaign', this.params.token);
  }
});


text:
Q: Angular Dart external JS I am building an Angular-Dart site based on a commercial Bootstrap template.
The correct rendering should be like this:

I used IntelliJ to scaffold a Dart/Angular app and started to modify from there.
I have put related files (CSS/JS/images) of that template into web/css, web/js, respectively.
HTML used is verbatim copied from the template but I have taken out the CSS, JS reference from btqun_component.html and moved into index.html.
The output is like this:

Obviously, the CSS is working, and the header/footer are showing correctly. But the masonry effect is not showing, so I doubt that is related to JS reference.
Can anyone give any hints on this?

A: Do you have a documentation for the bootstrap template ? I guess you need to execute the javascript they provide to you so you need to add it to your index.html, and you probably need to import bootstrap and jquery too.
If you need to call a javascript function you can do it directly in the index.html inside a script tag or build a dart wrapper using package:js
EDIT: answer to call jQuery function from Dart


text:
Q: How to lock map labels for inset map in Print Composer? OK, so I am making a print layout which has two maps, one an inset map with just a skeleton of a line layer and the other is the detail map at higher resolution. In the detail map, I want to show the labels for each arm of the skeleton. For the inset map, I want the labels to be off.
Even when I 'lock layers for map item', the labels still update in the inset map when the map is exported to PDF.
The update preview is set to Cache for both, but I don't think this has an impact of what gets exported.

A: "Lock layers for map item" controls whether enabling/disabling layers in the map view is synced with the print layout. Symbology and labels are always synced.
For your use case, I'd recommend adding a scale range to the labels. When zoomed out, labels will disappear.


text:
Q: DJANGO: many-to-many relationship with additional fields New to programming and this is very confusing for me... I have 2 models. Department and Crossfunctionalproject. The relationship between the two models creates a join table called Department_Crossfunctionalproject.
I have another model called employee. I want to add employees to the Department_Crossfunctionalproject table. How can I do this?
I've been following this tutorial: https://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships. Can I not do this on the automatically created department_crossfunctionalproject join table that DJANGO creates?
I keep getting the following error:
CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
companydatabase.membership:"Department_crossfunctionalproject" has a relationship with model <class 'companydatabase.models.Department_crossfunctionalproject'>,
which has either not been installed or is abstract.

MODELS:
class Crossfunctionalproject(models.Model):
    nameofproject = models.CharField(max_length=50)
    def __unicode__(self):
        return self.nameofproject

class Department(models.Model):
    name = models.CharField(max_length=100)
    project = models.ManyToManyField(Crossfunctionalproject, null=True, blank=True)

class Employee(models.Model):
    employeenumber = models.CharField(max_length=50)
    fname = models.CharField(max_length=50, verbose_name='First Name')
    mname = models.CharField(max_length=50, null=True, blank=True, verbose_name='Middle Name')
    lname = models.CharField(max_length=50, verbose_name='Last Name')
    email = models.EmailField(null=True, blank=True, verbose_name='Email')
    phone = models.CharField(max_length=50, null=True, blank=True, verbose_name='Phone')
    title = models.CharField(max_length=50, null=True, blank=True, verbose_name='Position')

# db table created by DJANGO, I wrote out the model, trying to add extra columns*
class Department_crossfunctionalproject(models.Model):
    department = models.ForeignKey(Department)
    crossfunctionalproject = models.ForeignKey(Crossfunctonalproject)
    membership = models.ManyToManyField(Employee, through="Membership")

class Membership(models.Model):
    employee = models.ForeignKey(Employee)
    department_crossfunctionalproject = models.ForeignKey(Department_crossfunctionalproject)
    whytheyjoined = models.CharField(max_length=100)

A: The problem is that you define Department_Crossfunctionalproject before 'Employee'. Try with providing the name of Employee model as a string:
membership = models.ManyToManyField('Employee', through="Membership")

A: Syncdb command creates the database tables for all apps in INSTALLED_APPS whose tables have not already been created.  It will never issue ALTER TABLE statements to match changes made to a model class after installation.
If you changed the Department_Crossfunctionalproject model by hand you have to drop the table and run syncdb again.
syncdb in django manual

A: I like to manage changes to my models using South: http://south.aeracode.org/
Django doesn't handle dropping columns so I started using it for that.

A: I got similar error message, but the cause of my problem was different and hence the fix was different too. My problem was that files that contained definitions of each class did not "import" the other class.
I got the following error:

Unhandled exception in thread started by bound method Command.inner_run of django.contrib.staticfiles.management.commands.runserver.Command object at 0x010E2170
File "C:\ ...\lib\site-packages\django\core\management\base.py", line 284, in validate
raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
  app_name.studio: 'instructors' has an m2m relation with model Instructor, which has either not been installed or is abstract.

I have a ManyToMany relationship defined between Studio and Instructor classes. Each class is defined in a separate file in models directory (not in the same models.py file)
In app_name/models/studio.py :
class Studio(models.Model):
    instructors = models.ManyToManyField("Instructor", blank=True, null=True, db_table="app_name_instructor_studios")

In app_name/models/instructor.py :
class Instructor(models.Model):
    studios = models.ManyToManyField("Studio", blank=True, null=True, db_table="app_name_instructor_studios")

SOLUTION:
I added missing import statement to app_name/models/__init.py__ file as described in this post
from instructor import *

Another way that I was able to solve it is to explicitly import Instructor class in app_name/models/studio.py file (However I prefer the firsts solution):
from app_name.models.instructor import Instructor


text:
Q: Can you get a line-in port on a MBA via an external device? I have a macbook air and I really want to plug in my guitar to garage band, but unfortunately the air doesn't have a line-in port. My question is, is there an external device that can provide you a line-in port? Just like the way you can plug in headphones and use the headset's mic, instead of the built in one.

A: The Griffin iMic is a great device for sound input and output via USB.


text:
Q: ListView in TabHost scroll/click problems I have a strange problem that recently appeared. At first I was loading all items in my ListView. It was scrolling all fine. Items were clickable and all was working fine.
Then in the getView of my adapter I added that:
if(pos == getCount() - 1){
    Log.i("Load", "Load database");
    load_database(getCount(), 5);
}

and here is load_database()
private void load_database(long offset, long count) {
    ArrayList<VKContent> objs = BaseApplication.db.get_all(Message.class, MessageHandler.COLUMN_MAILBOX + " = " + mailbox, count, offset);
    for(VKContent obj: objs){
        adp.add((Message)obj);
    }
}

The problem appeared right after that. On load it calls load_database once and everything is nice. ListView works fine. Clicks are handled. But once I reach "pos == getCount() - 1". It loads new data but it is now impossible to click items. When I scroll and do a flinch, a touch on the screen won't stop the flinch. When I try to scroll during a flinch it doesn't have any effect until the flinch stopped.
If I switch to a different Tab the listview behavior is restored. If I try use my scroll ball to focus items, the normal behavior come back too.
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:id="@android:id/tabhost">

     <LinearLayout
  android:orientation="vertical"
  android:layout_height="match_parent"
  android:layout_width="match_parent">

         <TabWidget android:id="@android:id/tabs"
             android:layout_height="wrap_content"
             android:layout_width="fill_parent" />

         <FrameLayout android:id="@android:id/tabcontent"
             android:layout_height="fill_parent"
             android:layout_width="fill_parent"
             android:layout_weight="1">
            <LinearLayout android:id="@+id/tab2"
                android:orientation="vertical"
                android:layout_height="fill_parent"
                android:layout_width="fill_parent">
                <ListView android:id="@+id/lv"
                    android:layout_height="fill_parent"
                    android:layout_width="fill_parent"
                    android:clickable="true" />
            </LinearLayout>
         </FrameLayout>
     </LinearLayout>
</TabHost>

Edit
I did try to invalidate(), forceLayout(), requestLayout(), isFocusable()... bringToFront... and others after load_database. But nothing helped.
Edit2
Almost forgot that piece of code.
    tabHost.setCurrentTab(1);
    tabHost.setCurrentTab(0);

For some reasons, there is a problem with TabHost. My ListView is shared by all tabs. When the view is first loaded it didn't display anything. So I had to switch from second to first tab.

A: So I fixed my problem, after looking if it worked without the tabHost, I realized it still didn't work. So looking at old code, I realized that my lazy load function was in fact calling a download thread which was run in background then back on the uiThread after the download has been finished.
The difference with the above code is that load_database isn't runned in a different thread. It's runned from the getView function which is a function of my adapter. In other word, it apparently break the listview to update the adapter in getView.
my current fix isn't the best one but for now it does the job. In the futur.
if(pos == getCount() - 1){
    MessagesActivity.this.load_more = true;
}

and
@Override
public void onUserInteraction() {
    super.onUserInteraction();

    if(load_more == true || adp.getCount() == 0){
        load_more = false;
        load_database(adp.getCount(), 5);
    }
}

that way, the load_database is never runned from getView. And my adapter update the listview without problem.


text:
Q: Python Selenium How to locate and fill up this 3 inputs i'm trying to fill up that form (you have to be logged into facebook) :
https://m.facebook.com/marketplace/selling/item/ . I've already done 3 inputs ( what u selling - price - description ) but i didn't know how to fill up the 3 others ( Category - Photos - Location )
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

#OpenBrowser
driver = webdriver.Chrome()
driver.get("https://facebook.com/")

#Logging
email = driver.find_element_by_id('email')
password = driver.find_element_by_id('pass')
#facebook username input
email.send_keys('email')
#facebook password input
password.send_keys('pass')

time.sleep(5)
driver.find_element_by_id('loginbutton').click()
#Redicret to fb marketplace
time.sleep(2)
driver.get("https://m.facebook.com/marketplace/selling/item/"

#Filling up form
time.sleep(5)
title = driver.find_element_by_name('title').send_keys('title teste')

time.sleep(2)
price = driver.find_element_by_name('price').send_keys('50')

time.sleep(2)
description = driver.find_element_by_name('description').send_keys('description teste')

Form that i'm trying to fill up


text:
Q: Display the category names for the current post, but exclude one ID Im trying to display the current post category name for a custom post types' taxonomy, but exclude one of the categories. I see different solutions in StackOverflow, but I can't seem to get any of them to work for me. Below is the code I am using, which works great, but I don't know how to exclude one ID using it.
<?php $terms = get_the_terms( $post->ID , 'press_category' );
                    foreach ( $terms as $term ) {
                        $term_link = get_term_link( $term, 'press_category' );
                        if( is_wp_error( $term_link ) )
                        continue;
                    echo  $term->name ;
                    }
                ?>

A: Try this
<?php $terms = get_the_terms($post->ID, 'press_category');
foreach ($terms as $term)
{
    $term_link = get_term_link($term, 'press_category');
    if (is_wp_error($term_link)) continue;
    if ($term->term_id != 222)
    {
        echo $term->name;
    }
}
?>

Change 222 in this line to your taxonomy id for exclude

$term->term_id != 222


text:
Q: Who named the episodes in TNG? Each TNG episode has a specific name, normally quite a clever one that summarizes the main point of the episode.  I was just wondering actually who the person was that gave TNG episodes their names?

A: The shows were named either by the showrunner, writing staff or (in the case of speculative scripts) the original writer or writers. There will often be input from the studio and other cast and crew.
The show may also go through multiple names before a final decision is made. "House of Quark" was originally "Fight to the Death" and "Unnamed Ferengi Episode", for example.
Although I've been unable to find a canon quote regarding Star Trek, this quote from Josh Malozzi, Senior showrunner for the Stargate series gives a pretty good overview of the normal decision-making process;

INTERVIEWER: How are episode titles chosen?
JOE: The hardest part of writing a script is coming up with the episode title. Either we'll come up with them individually or we'll
  say something in the room and someone will say, "Hey, that's a good
  title!" (i.e. "Going to Other Planets").


text:
Q: Which rings are rings of continuous functions? Now at MO.
This is a question for which I've found a number of "near-miss" results online, which may actually be answers but whose direct relevance I haven't been able to see.
Say that a ring $A$ is spatial iff there is some topological space $\mathcal{X}$ such that $A\cong C(\mathcal{X})$, where $C(\mathcal{X})$ is the ring of continuous functions $\mathcal{X}\rightarrow\mathbb{R}$.

Is there a purely algebraic characterization of spatiality?

I've been told that Gelfand representations are relevant here, but I don't immediately see how they answer the question; maybe I'm missing something, though. (Note however that I do mean to ask about rings, rather than more intricate structures like Banach algebras. Also note that I'm not assuming any tameness properties on the spaces which are candidates for witnessing spatiality.)

EDIT: "purely algebraic characterization" is of course some serious weasel-wordery. Here's one way to make that precise (and so make possible a rigorous negative answer):

Is there an $\mathcal{L}^2_{\infty,\infty}$-sentence characterizing the spatial rings?

Here $\mathcal{L}^2_{\infty,\infty}$ is the fully-infinitary version of second-order logic: we allow arbitrary-cardinality Boolean combinations and quantifications (over both first- and second-order objects). Of course, any specific $\mathcal{L}^2_{\infty,\infty}$-sentence can only "reach up" to a particular cardinal, so this isn't actually as overkill as it may appear.

A: I do not know the answer to your precise formulation but here are some things you can say about characterizing spatial rings.
First, rings of bounded continuous functions can be characterized algebraically using Gelfand duality.  Namely, a commutative ring $A$ is isomorphic to the ring $C_b(X)$ of bounded continuous functions $X\to\mathbb{R}$ for some topological space $X$ iff $A$ satisfies the following properties.  First, $A$ is a $\mathbb{Q}$-algebra, and is partially ordered by the relation $x\leq y$ iff $y-x$ is a square.  Moreover, for each $r\in\mathbb{R}$, there is a unique element of $A$ which defines the same Dedekind cut in $\mathbb{Q}$ with respect to this ordering as $r$, and this makes $A$ an $\mathbb{R}$-algebra.  Finally, if you form the complexification $\mathbb{C}\otimes_\mathbb{R} A$, the spectral radius defines a norm on $\mathbb{C}\otimes_\mathbb{R} A$ which makes it a $C^*$-algebra.  (Alternatively, you can directly characterize real bounded continuous functions without going through the complexification.  For instance, for $x\in A$ you can define $\|x\|$ to be the least $r\in\mathbb{R}_{\geq 0}$ such that $-r\leq x\leq r$ and then it suffices to assume that this is a complete norm on $A$.  See IV.4.4-10 in Peter Johnstone's Stone spaces.)
Now, there is an analogue of Gelfand duality for rings of unbounded functions.  Recall that Gelfand duality says that for any topological space $X$, $C_b(X)$ is isomorphic to $C_b(Y)$ for a compact Hausdorff space $Y$ which is unique up to unique compatible homeomorphism (namely, the Stone-Cech compactification $\beta X$ of $X$), and that this gives a contravariant equivalence of categories between the category of rings of the form $C_b(X)$ and the category of compact Hausdorff spaces.  Similarly, for any topological space $X$, $C(X)$ is isomorphic $C(Y)$ for a unique realcompact space $Y$ which is unique up to unique compatible homeomorphism and this gives a contravariant equivalence of categories between the category of rings of the form $C(X)$ and the category of realcompact spaces.  This space $Y$ is called the Hewitt realcompactification $\nu X$ of $X$, and can be described as the subset of $\beta X$ to which all elements of $C(X)$ extend continuously.
Now, given a spatial ring $A\cong C(X)$, you can recover $\nu X$ and the canonical map $A\to C(\nu X)$ algebraically as follows.  First, as above, $A$ is partially ordered using squares and this gives $A$ an $\mathbb{R}$-algebra structure.  You can then define the subring $A_0$ of elements of $A$ that are bounded above and below by elements of $\mathbb{R}$ (this will be $C_b(X)$).  This subring is a ring of bounded continuous functions, as characterized above.  Now let $Y$ be the set of maximal ideals of $C_b(X)$ (this will be $\beta X$).  For every $m\in Y$, the quotient $A_0/m$ is isomorphic to $\mathbb{R}$, and in this way we can map $A_0$ to the set of functions $Y\to\mathbb{R}$.  Give $Y$ the coarsest topology that makes every element of $A_0$ continuous.
Now, we can also evaluate elements of $A$ at points of $Y$ as follows.  Given $x\in A$ and $n\in\mathbb{N}$, let $x_n=(x\wedge n)\vee -n$ with respect to our ordering on $A$.  Then $x_n\in A_0$, and we can consider $x_n$ as a function $Y\to\mathbb{R}$.  This sequence of functions $(x_n)$ then converges pointwise to a function $Y\to [-\infty,\infty]$ (this is the unique extension of $x:X\to\mathbb{R}$ to a function $\beta X\to[-\infty,\infty]$).  Let $Z\subseteq Y$ be the set of points at which every element of $A$ takes a finite value (this is $\nu X$).  We then can map $A$ to the set of functions $Z\to\mathbb{R}$.  This gives a characterization of spatial rings: a ring $A$ is spatial iff it satisfies all the above properties and this last map is a bijection from $A$ to $C(Z)$.
Unfortunately, this characterization does not appear to be "algebraic" in your sense.  Almost everything can be done in $\mathcal{L}^2_{\infty,\infty}$, but there is a problem with the very last step.  To say that our map $A\to C(Z)$ is surjective, we need to quantify over functions $Z\to\mathbb{R}$.  Elements of $Z$ are second-order over $A$ (they are maximal ideals in $A_0$), and so functions $Z\to\mathbb{R}$ are third-order over $A$.  (There are various ways you could try to get around this, but I haven't found one that works.  For instance, if you could algebraically state that $Y$ is the Stone-Cech compactification of $Z$, then instead of quantifying over arbitrary functions $Z\to\mathbb{R}$, you can just quantify over functions $Z\to\mathbb{R}$ that are a pointwise limit of a sequence of elements of $A_0$, since you know that every continuous function $Z\to\mathbb{R}$ extends to a continuous function $Y\to[-\infty,\infty]$ which is then the pointwise limit of a sequence of bounded continuous functions $Y\to\mathbb{R}$.  Alternatively, imitating the approach for bounded continuous functions above, you might try to find some more basic algebraic characterization of when a subalgebra of $C(Z)$ is all of $C(Z)$, analogous to the Stone-Weierstrass theorem which is a crucial tool in the proof of Gelfand duality.  I don't know of any such characterization, though.)
Let me finally mention the paper

Anderson, Frank W.; Blair, Robert L., Characterizations of the algebra of all real-valued continuous functions on a completely regular space, Ill. J. Math. 3, 121-133 (1959). ZBL0083.17403.

which is the only reference I have been able to find on the topic of characterizing spatial rings.  They give two characterizations (Theorem 5.6 and 5.8), but again, these are not "algebraic".  I have not read through all the details of the paper but their approach seems to be basically the same idea as mine.  They characterize the map $A\to C(Z)$ being surjective by characterizing when an extension of $A$ would consist of just adding more continuous functions on $Z$ to the ring, and require that $A$ has no nontrivial extensions of this type.


text:
Q: Does evaporation do work on the surroundings? Suppose it is a dry (effectively no water vapor in the ambient air ) and hot day ($T_{ambient}\approx 40\ C$). My body temperature on this day is $T_{body}\approx 37C$. As a cooling mechanism, my body begins to sweat releasing pure water (to a good approximation at least) onto the surface of my skin. This water (I will refer to sweat as water from now on) is at the same temperature as my body initially. The molecules in this water roughly obey a Maxwell-Boltzmann distribution and hence a sizable fraction of the water molecules have enough energy to escape and enter the vapor phase. When these high energy molecules escape into the vapor phase, the water on my skin cools to some temperature $T_{reduced}$ which is lower than my body temperature ($T_{reduced}<T_{body}$). Now because of this temperature gradient between my body and the water, heat flows from my body which is at the higher temperature to the water which is at the reduced temperature, heating the water whilst cooling my body at the same time.
Now my question can be stated as follows: If we take the water molecules (both those in the liquid and vapour phase) as a system, does this system do work on the surroundings when evaporation occurs? That is, when the most energetic of liquid phase molecules break free into the gaseous phase, do they push against the atmosphere and as a result do work on it? Secondly, if the answer to the first question is yes, can this be assumed to be the reason the water cools during evaporation? That is, the system (initially only liquid water) partly evaporates and hence expands against the atmosphere doing work on it. This work reduces the energy of the system and hence its temperature. After this reduction in temperature, heat flows from the human body to the cooled system heating it up and causing the cycle to repeat.
I ask these two questions because if there is no expansion work or if the expansion work is not the cause of the temperature reduction, then the evaporation of sweat on a body at a temperature lower than that of the surroundings (as in this case where $T_{body} = 37C < T_{ambient} =40C$) appears to be an example of a system colder than its surroundings spontaneously cooling without doing work on the surroundings. This would be a violation of the second law. So am I correct in thinking that the evaporation of sweat leads to the system (all sweat molecules, both vapour and liquid) doing work on the surroundings as it expands against the atmosphere and it is this work which reduces the internal energy of the system which reduces its temperature?

A:
Does evaporation do work on the surroundings?

Actually, apparently it does, at least according to the Hyperphysics website: http://hyperphysics.phy-astr.gsu.edu/hbase/thermo/phase.html#hvap. To quote from the site:
"In the process of vaporization of water, a large amount of energy must be added to overcome the remaining cohesive forces between the molecules and an additional amount of energy goes into PdV work to expand the gas from its very small liquid volume to the volume occupied by the resulting vapor".
It goes on to deduce that the $PdV$ work required to expand water (perspiration) into its gaseous form at 37°C is 34.2 calories/gm, 6.8 calories/gm less than at 100°C.
The analysis is rather lengthy, so I leave it to you to dig further.
Hope this helps.

A:
If we take the water molecules (both those in the liquid and vapour phase) as a system, does this system do work on the surroundings when evaporation occurs? That is, when the most energetic of liquid phase molecules break free into the gaseous phase, do they push against the atmosphere and as a result do work on it?

Indeed there is work done on the atmosphere (the part without the newly added water), because this body as a whole expands a little in the gravity field when adding new particles. This is somewhat non-intuitive because the newly added water molecule is much smaller than the empty volume it has around it in the air, so one tends to imagine the water molecules just diffuse into empty space between the air molecules and the air molecules aren't affected.
But this is not so; adding new particles actually causes the air to expand. There are two ways to understand this.
First, if the water is boiling in the atmosphere, this work is done when bubble of vapor is still expanding in the liquid. Since it is expanding against atmospheric pressure + hydrostatic pressure of water above it, it does some work on the atmosphere (since liquid water is almost incompressible). Then when the bubble gets out in in the atmosphere, it starts cooling down from 100 Celsius to lower temperature and the vapor also diffuses into the atmosphere. This means some work goes back from atmosphere to the vapor, but not as much as was initially put during boiling, so net result is that positive work is done on the atmosphere.
Second, if evaporation happens at temperature of the atmosphere (so the change of temperature of the water is zero), there is no boiling, only diffusion from the water surface. There is still work done on the atmosphere. This is because atmosphere is quite a rare gas that obeys law of ideal gas. For an imaginary pocket of air that contains $N$ particles, volume of this pocket is:
$$
V = \frac{NkT}{p}.
$$
This means volume of a gas pocket is determined by pressure $p$, temperature $T$ and total number of particles $N$ in it. If the air in the pocket changes from state $T,p,N_1$ to state $T,p,N_2$ where $N_2 > N_1$, its volume has to increase. This happens when the water molecules push the air molecules away during collisions/scattering events and eventually mix with them.

if the answer to the first question is yes, can this be assumed to be the reason the water cools during evaporation? That is, the system (initially only liquid water) partly evaporates and hence expands against the atmosphere doing work on it. This work reduces the energy of the system and hence its temperature. After this reduction in temperature, heat flows from the human body to the cooled system heating it up and causing the cycle to repeat.

Yes, evaporation means gas expansion into open atmosphere. Any gas expansion into open atmosphere is associated with that expanding gas getting colder (possibly even colder than the atmosphere) and the rest of the atmosphere getting hotter(however because of its size, this is not easily observed with open atmosphere, but can be observed when expanding into closed vessel).
However, this cooling effect acts directly only on the vapour, not on the remaining liquid. This liquid does not expand and does not cool down by doing work. However, the remaining liquid still cools down, because

*

*by losing particles it is losing energy at a higher rate than the rate that would keep the temperature constant; this is because evaporated molecule carries away more than average energy per molecule in the remaining liquid;

*the colder vapour-rich air may cool down the liquid by heat conduction and accelerating evaporation.


text:
Q: In a multiple MatSelect, a re-enabled checkbox shows as disabled Using Angular Material, I want to disable the checkboxes within a multiple <MatSelect> for a period of time (as data is retrieved from an API). I can successfully do this, however the CSS class for the checkbox does not change back. In other words, the checkbox is functionally enabled, but the CSS displays as disabled. Is this a Material defect or something I can fix?
Example: https://stackblitz.com/edit/angular-jqzx99
Component:
export class AppComponent  {
  @ViewChildren(MatOption) matSelectOptions: QueryList<MatOption>;

  public isPaused = false;
  public optionData = ['Foo', 'Bar', 'Baz'];

  /**
   * Disable MatSelect checkboxes for 2 seconds
   */
  public disableCheckboxes(): void {
    this.isPaused = true;
    this.matSelectOptions.forEach(option => option.disabled = true);

    setTimeout(() => {
      this.isPaused = false;
      this.matSelectOptions.forEach(option => option.disabled = false);
    }, 2000);
  }
}

Template:
<mat-form-field>
    <mat-select multiple
                [disabled]="isPaused"
                (selectionChange)="disableCheckboxes()">
        <mat-option *ngFor="let option of optionData">
            {{option}}
        </mat-option>
    </mat-select>
    <mat-placeholder>Example</mat-placeholder>
</mat-form-field>

{{isPaused ? 'Pausing…' : ''}}

A: Seems that programatically disabling the MatOptions objects is not really a good idea.
So using just isPaused for select and options works fine
Component:
export class AppComponent  {
  @ViewChildren(MatOption) matSelectOptions: QueryList<MatOption>;

  public isPaused = false;
  public optionData = ['Foo', 'Bar', 'Baz'];

  /**
   * Disable MatSelect checkboxes for 2 seconds
   */
  public disableCheckboxes(): void {
    this.isPaused = true;

    setTimeout(() => {
      this.isPaused = false;
    }, 2000);
  }
}

Template:

Disabled MatSelect Checkbox Problem:

<mat-form-field>
    <mat-select multiple
                [disabled]="isPaused"
                (selectionChange)="disableCheckboxes()">
        <mat-option *ngFor="let option of optionData" [disabled]="isPaused">
            {{option}}
        </mat-option>
    </mat-select>
    <mat-placeholder>Example</mat-placeholder>
</mat-form-field>

{{isPaused ? 'Pausing…' : ''}}


text:
Q: how to align multiple div's next to each other? I am new to Html,I'm trying to align multiple div's next to each other horizontally. i tried float property and display inline property also, but nothing works correctly.can anyone suggest any methods for it?
my code:
#display2letter
{
width:150px;
height:50px;
background-color:grey;
box: 10px 10px 5px #888888;
}
#display3letter
{
width:150px;
height:50px;
background-color:blue;
box: 10px 10px 5px #888888;
}
#display4letter
{
width:150px;
height:50px;
background-color:grey;
box: 10px 10px 5px #888888;
}

#one
{
position:fixed;
left:23%;
}
#two
{
position:fixed;
left:23%;
}
#three
{
position:fixed;
left:23%;
}

here is the fiddle
http://jsfiddle.net/pGHS9/1/

A: I made JSFIDDLE, I am not sure if that is what you ment.
I added a box and changed position fixed to relative:
.box {
    float: left;
    width: 270px;
}
#one
{
position:relative;
left:23%;
}
#two
{
position:relative;
left:23%;
}
#three
{
position:relative;
left:23%;
}

JSFIDDLE

A: The more recommended solutions is place the container with display: inline-block and percent the blocks.
Something Like this:
html

other elements

other elements

css
.horizontal {
  display:inline-block;
  width: 33%;
}

This solutions is responsive design implementation.

A: try:

first

second

then
#first{
    float:left;
    width:200px;
    border:1px solid green;
}
#second{
    float:left;
    width:200px;
    border:1px solid red;
}

here's the JSFiddle
http://jsfiddle.net/PdXk5/

A: Try this....

first div

second div

third div

div{
    border:1px dashed #000;
    position:relative;
    float:left;
}
div.inner{
    border:1px solid black;
    width:100px;
    height:100px;
    margin:5px;
}


text:
Q: Indeterminate State of checkboxes not working in safari(Compatibility issue) Indeterminate state doesnt work in Safari browser but it works in all other browsers.
The problem is with checkboxes when the checkbox is checked the child checkboxes will be displayed by jquery.When i again check the checkbox of child the indeterminate state of parent is not working in safari
This code is written for second level checkboxes. Here, im calculating the number of checkboxes(checkBoxesCount) and the number of unchecked checkboxes(uncheckedCount) in the second level.If any one of them is unchecked, its parent(first level) checkbox should go to indeterminate state. This works fine in all the browsers but not in Safari(There is no change in the state of first level checkbox if any one of the second level checkbox is unchecked, it remains in selected state only).
if(uncheckedCount>0 && uncheckedLength!=(checkBoxesCount-1) ){
 $('.firstLevel').prop("indeterminate", true);

A: I have come across a bug similar before, could be the way you are checking to see if a checkbox is checked or not
See this previously answered question which may help, note how the answer involves doing 2 types of checking to see if the checkbox is checked, the 2nd of which was needed to make it work on safari
Hope this helps!
Custom checkbox not working in Chrome and Safari browser


text:
Q: Primitive value returned from constructor will be lost I created a function:
function CheckHidden(el){ return $(el).css('display')!='none' }

My IDE warns me that:

Primitive value returned from constructor will be lost when called with 'new'

Actually when I call it like this:
var all = $("#catalog-body > div").filter(function(){return  CheckHidden(this)})

it doesn't work and doesn't reduce set of elements to unhidden ones.
Please explain to me the issue. I have a giant lack of knowledge.

A: I ran into this warning myself and if you want to know the cause, it is because your IDE expect function names to start with a lowercase letter. Since your function is called CheckHidden with a capital C, it thinks it's a class declaration.
However, you should still use jQuery's :visible selector to fix your specific issue.

A: If you create an object using the keyword new (as mentioned in the warning), JS returns an new instance of the object rather than the return value from the constructor.
A function like
function CheckHidden() {
    return false;
}

would return two different values, depending on how it is executed.
// "a" is boolean value
var a = CheckHidden();

// "a" is an object of type "CheckHidden"
var a = new CheckHidden();

A: jQuery actually has something like this built in. You can use the :visible selector. You can just do:
var all=$("#catalog-body > div").filter(':visible')

to get the visible elements.

A: If you want to pull all elements which are visible, you can use jQuery's :visible selector:
var all = $("#catalog-body > div:visible")

Conversely, if you want to pull all elements which are hidden, you can combine this with jQuery's :not selector:
$("#catalog-body > div:not(:visible)")