text:
Q: He is coming on a bicycle
He is coming on a bicycle.

Why is this wrong?
Personally, I would prefer "by bike", as it just sounds more natural to me. But I fail to see any problem with the sentence.

A:
He is coming by bicycle.

Use by because it is a means of transportation from point A to point B.

He is riding on a bicycle.

is OK because on indicates your position related to the bicycle.

A: Why do you think

He is coming on a bicycle.

is incorrect?  It has the same meaning as

He is coming by bicycle.

usually meaning

He is riding a bicycle here.

Other examples are

He is coming on a plane.
  He is coming on a train.
  He is coming in a car.

are all correct.


text:
Q: "syntax error in INSERT INTO statement" I'm a beginner in vb.net
I've got the following Error upon executing the Insert-Statement
syntax error in INSERT INTO statement

Here is my code:
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
        Try
            Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(?,?,?)"

            Dim cmd As New OleDbCommand
            With cmd
                .Connection = con
                .CommandText = sql
                .Parameters.AddWithValue("?", txtid)
                .Parameters.AddWithValue("?", txtuser)
                .Parameters.AddWithValue("?", txtpass)
                .ExecuteNonQuery()
            End With
            MsgBox("The Data Has Been Added")

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

Could anyone help me?

A: Try to use sql parameter names
Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
    Try
        Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
" VALUES(@ID,@Username,@Password)"

        Dim cmd As New OleDbCommand
        With cmd
            .Connection = con
            .CommandText = sql
            .Parameters.AddWithValue("@ID", txtid)
            .Parameters.AddWithValue("@Username", txtuser)
            .Parameters.AddWithValue("@Password", txtpass)
            .Open()
            .ExecuteNonQuery()
            .Close()
        End With
        MsgBox("The Data Has Been Added")

    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Note that: You should properly close your connections after you use them. Therefore following code may be better.
Private Sub InsertLogin()
    Dim sql As String = " INSERT INTO [Login1] ([ID],[Username],[Password])" & _
        " VALUES(@ID,@Username,@Password)"

    Using con As New OleDbConnection(ConnectionStringHERE)
      Using cmd As New OleDbCommand
            Dim cmd As New OleDbCommand
            cmd.Connection = con
            cmd.CommandText = sql
            cmd.Parameters.AddWithValue("@ID", txtid)
            cmd.Parameters.AddWithValue("@Username", txtuser)
            cmd.Parameters.AddWithValue("@Password", txtpass)
            con.Open()
            cmd.ExecuteNonQuery()
        con.Close()
      End Using
    End Using

End Sub

    Private Sub cmdadd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdadd.Click
        Try
            InsertLogin()
            MsgBox("The Data Has Been Added")
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

Here, I used cmd. syntax, it is no different then using With.

A: You have to name the sql parameters.
Look at the examples in the documentation: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue%28v=vs.110%29.aspx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Laravel: keep the checkbox selection after a validation error? In my form I want the checkboxes to keep their states (checked or unchecked) after a validation error.
This is what I have so far:
<input type="checkbox" id="delete-user" class="form-check-input" data-data-section="users" name="permissions[]" value="delete-user" {{ (is_array(old('permissions')) && in_array(1, old('permissions'))) ? ' checked' : '' }}>

But it looks that the old() function doesn't work.
I also tried:
old('permissions.'.$key)

where $key is the checkbox array index but it doesn't work neither.
Any idea ?

A: I think you are an invalid value pass in the in_array function
Try this:
value="delete-user" {{ (is_array(old('permissions')) && in_array('delete-user', old('permissions'))) ? ' checked' : '' }}>


text:
Q: Post Rocket route is forwarded (Rust) Sorry to ask such a basic question, there's little info about this in Stack Overflow and GitHub. This must be something silly, but I'm not getting it.
I'm trying to send via JavaScript's fetch to a Rust post endpoint with Rocket 0.5 RC1. But I'm getting hit by:

No matching routes for POST /api/favorites application/json.

Here's the complete log:
    POST /api/favorites application/json:
    Matched: (post_favorites) POST /api/favorites
    `Form < FavoriteInput >` data guard is forwarding.
    Outcome: Forward
    No matching routes for POST /api/favorites application/json.
    No 404 catcher registered. Using Rocket default.
    Response succeeded.

Here's my main.rs file (Irrelevant parts omitted):
#[rocket::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let cors = CorsOptions::default()
        .allowed_origins(AllowedOrigins::all())
        .allowed_methods(
            vec![Method::Get, Method::Post, Method::Patch]
                .into_iter()
                .map(From::from)
                .collect(),
        )
        .allow_credentials(true)
        .to_cors()?;

    rocket::build()
        .mount("/api", routes![index, upload::upload, post_favorites])
        .attach(cors)
        .launch()
        .await?;

    Ok(())
}

#[post("/favorites", data = "<input>")]
async fn post_favorites(input: Form<FavoriteInput>) -> Json<Favorite> {
    let doc = input.into_inner();
    let fav = Favorite::new(doc.token_id, doc.name);
    let collection = db().await.unwrap().collection::<Favorite>("favorites");
    collection.insert_one(&fav, None).await.unwrap();
    Json(fav)
}

Here's my cargo.toml:

[dependencies]
rocket = {version ="0.5.0-rc.1", features=["json"]}
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
reqwest = {version = "0.11.6", features = ["json"] }
serde= {version = "1.0.117", features= ["derive"]}
mongodb = "2.1.0"
rand = "0.8.4"
uuid = {version = "0.8", features = ["serde", "v4"] }

Here are my structs:
#[path = "./paste.rs"]
mod paste;

#[derive(Serialize, Deserialize, Debug)]
pub struct Favorite {
    pub id: String,
    pub token_id: String,
    pub name: String,
}

impl Favorite {
    pub fn new(token_id: String, name: String) -> Favorite {
        let id = Uuid::new_v4().to_string();
        let fav = Favorite { token_id, name, id };

        fav
    }
}

#[derive(FromForm, Serialize, Deserialize, Debug)]
pub struct FavoriteInput {
    pub token_id: String,
    pub name: String,
}

Here's the token payload:

I've tried with parameter-less get requests and they were successful.
I thought the Form struct was reading and correctly parsing the FavoriteInput as it allows for missing/extra fields.
There must be something silly that I'm doing wrong. Any ideas?

A: You seem to be sending JSON from JavaScript but are expecting Form parameters on the server.
You need to change input: Form<FavoriteInput> with input: Json<FavoriteInput>.


text:
Q: Dos dir mask, want "*.xxx" and not "*.xxxzz" In my directories, I have file names like *.xxx and also *.xxxzz
When I do dir /s/b "*.xxx" I get *.xxxzz files in my list. I do NOT get these results in a "Take Command" console, but I do in a cmd console.
How do I get cmd to give me only *.xxx files?

A: With the DIR command, when you specify a mask containing an extension of exactly three characters, you will get matches of files that contain extensions with three or more characters, so long as the first three characters match the extension you originally specified.
I have no idea why it works this way, but at least the behavior is consistent nearly everywhere in the Windows API where you can specify a file search pattern. I can only assume it has something to do with support for long file extensions (i.e., file names that don't comply with the old DOS 8.3 rule).
But, you can get around the behavior in two ways:

*

*A mask that specifies a file extension with one, two, or more than three characters will return only files with extensions of exactly the specified length.
So, for example, dir /s/b "*.xx" will give you only files with the extension .xx, and dir /s/b "*.xxxzz" will give you only files with the extension .xxxzz.

*You can use the question mark wildcard character, instead of the asterisk. Asterisks mean "replaced by zero or more characters", while question marks mean an exact substitution of the question mark with a single character.

A: I suspect you're running into a problem because of the way Windows (older versions, at least) generated a short 8.3 filename to improve compatibility with old programs. You can probably confirm this by doing dir /x *.xxx in the directory where your *.xxxzz files exist.
I'm not sure if there's a way around it from the limited Windows command line tools. There should probably have been a switch on the dir command to force consideration only of long filenames, but I don't see one.
You may be able to solve your problem by disabling short filenames on that volume, if you're sure you don't need them for any ancient software you're running.
I haven't tried that myself, so maybe the short names already generated will continue to exist after you follow those instructions. If so, you might be able to fix it by copying the tree you're working with to a new location.

A: The fact is that unless the system has been set up to not generate 8.3 names, every file or directory with a long filename will also have an 8.3 alias. At least one - with some of the warped constructs in use in later editions, there many be many aliases.
Academically, since it's a matter of opinion (and hence outside of SO's bailiwick) it could be argued that your alternative command processor is not producing the correct results since it apparently ignores the short filename. Which is "correct" is debatable - what suits in one application may not in another. The easiest and most logical way of course is to have an option - but the chances of the major player in the debate incorporating such a facility at this stage amount to well,Buckley's
Here's a routine that may suit. It's not bullet-proof as it will have problems with some "poison characters" (those with special meaning for the standard command-processor cmd.exe(A windows application that emulates and enhances many of the facilities available in DOS, and normally, though technically-incorrectly, called "DOS" by the politically-incorrect for the sake of brevity.))
@ECHO Off
SETLOCAL
SET "mask=%~1"
IF "%mask:~-4,1%"=="." ECHO(%mask:~-3%|FINDSTR /L "* ." >NUL&IF ERRORLEVEL 1 (
 FOR /f %%a IN ('dir /s/b "%mask%"') DO IF /i "%%~xa"=="%%~sxa" ECHO(%%a
 GOTO :EOF
)
dir /s/b "%mask%"

GOTO :EOF


text:
Q: How do I add min and max value to my Vue count value The user can click on a + and - button to increment and decrement the value. How do I add a min and max value e.g. min = 1 and max = 10 for the [[ count ]]?
My Vue.js app:

    Add 1
    Remove 1

    [[ count ]]

Update:
Above code is working now.
1) How do I change my [[ count ]] into an <input type="number" min="0" max="10" />, controlled by this buttons?
2) How do I add a class e.g disabled when [[ count ]] === 1?
Update 2:
I changed it to an input field:
  <input type="number" name="lineItems[{{ product.id }}][quantity]" value="{{ quantity }}" v-model.number="quantity" min="{{ product.minPurchase }}" max="{{ product.calculatedMaxPurchase }}" class="custom-qty__qty-field">

And make the input value adjustable by the min and plus buttons:

E.g {{ product.minPurchase }} are twig variables which contains settings from the ShopWare backend.
Is this a clean way? And how do I add a CSS class when the count reaches 1, so I can disable the button?

A: Check if the count is already at the limits during increment and decrement and act accordingly.
increment() {
  this.count = this.count === 10 ? 10 : this.count + 1;
}

decrement() {
  this.count = this.count === 1 ? 1 : this.count - 1;
}

You could also make min and max data properties instead of hardcoding 1 and 10 if you wanted.
After your Edit:
If you use a number input instead, you could solve this without methods.  All that's needed is to bind your data to the input like this:
<input type="number" v-model="count" :min="min" :max="max" />

See the demo below:

new Vue({
  el: "#app",
  data() {
    return {
      min: 1,
      max: 10,
      count: 1
    }
  }
});

  <input type="number" v-model="count" :min="min" :max="max" />

  << Mouseover the input to change

Count: {{ count }}


text:
Q: Separating violinplots in seaborn with a line I'm trying to plot multi-hue distributions with Seaborn, but I find that the plots are difficult to be traced back to the tick they belong to. I have tried to add a grid, but the grid is only showing on the dimension of the distribution, so separating the distribution itself but not different distributions from each other. Is it possible to have Seaborn add a grid line between different violin plot groups/hues? To illustrate, take one of the plots from the docs. I've added what I'd like to see to this plot (I've made the width of these separators quite heavy for illustration purposes, in the solution I'd like them to be just as thick as the grid lines):

A: You could use matplotlib's axvline to draw vertical lines at positions 0.5, 1.5, ...
import numpy as np
import seaborn as sns
sns.set(style="whitegrid")

tips = sns.load_dataset("tips")
ax = sns.violinplot(x="day", y="total_bill", hue="smoker",
                    data=tips, palette="muted")
for i in range(len(np.unique(tips['day'])) - 1):
    ax.axvline(i + 0.5, color='grey', lw=1)
plt.show()

Alternatively, you could set minor ticks at these positions and turn the minor gridlines on for the x-axis.


text:
Q: Is it always possible to determine whether or not one is accelerating? Consider the following two situations:
A: You wake up in an elevator that is in free fall in a gravitational field.
B: You wake up in an elevator that is floating in a vacuum.
Is it possible to distinguish between these two situations?
It seems to me that Newton's second law formulated in a local coordinate system would look the same whether or not situation A or B is the truth: If P is an object in the elevator (which we denote by E), Newton's second law would be:
$$F_P = m_P\ddot{x}_P \Rightarrow$$
$$(-m_Pg + F'_P) = m_P(\ddot{x}_E+\ddot{x}_{P\backslash E})$$
where $F'_P$ is the force applied to the object in addition to whatever gravitational force is present, $x$ denotes position relative to an inertial frame, and $x_{P\backslash E}$ is the position of the object relative to the elevator.
Since the elevator is in free fall,
$$F_E = m_E\ddot{x}_E \Rightarrow -m_Eg = m_E\ddot{x}_E \Rightarrow \ddot{x}_E = -g$$
Thus, the equation of motion for the object P becomes
$$F'_P = m_P\ddot{x}_{P\backslash E}$$
But this would be true regardless of the value of $g$! Or am I missing something? If not, is there any other way of knowing whether or not situation A or B is the truth?

A: You might want to have a look at Accelerating Frame and Gravity as it is closely related though not an exact duplicate. The answer is that there is locally no way to tell the difference between your two cases $A$ and $B$. In fact this is enshrined in Einstein's equivalence principle.
Note the emphasis on the local equivalence. Gravitational fields are never completely uniform so for a freely falling observer there are always some tidal forces acting, and if your elevator is big enough you could tell the difference between the two cases. Suppose you place test particles near the walls of the elevator and initially at rest with respect to yourself. The tidal forces mean that in some directions those test particles would accelerate towards you and in other directions they would accelerate away from you. Measuring this acceleration would allow you to determine that you're falling in a gravitational field rather than floating in space.

A: Well, the conventional answer is that you cannot distinguish the two situations. Einstein's General Relativity is based upon not being able to distinguish between the two situations.
However - if you were falling towards a planet or star etc individual objects in free fall would appear to move towards each other because the gravitational field is not uniform - they are falling towards a central point - the centre of mass.


text:
Q: How to reset headers of a table with datatables I have a table that I filled with an array like this

        {{header}}

        {{a+1}}
        {{data.name}}

When I clear both arrays I called rerender datatable function and arrayData works fine bur headers not updating
  rerenderDatatable(): void {
       this.dtOption = {
          destroy: true,
          pagingType: 'full_numbers',
          pageLength: 5,
          lengthMenu: [5, 10, 15]
        };
       this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => {
          dtInstance.clear().draw(); // Add this  line to clear all rows..
          // Destroy the table first
          dtInstance.destroy();
          // Call the dtTrigger to rerender again
          this.dtTrigger.next(this.dtOption);
        });
    }


text:
Q: Error building gcc 4.8.3 from source: libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/lib/x86_64-linux-gnu/libicuuc.so.55) I 'm using gcc (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010 for the compile but I have also tried gcc 4.1.2 and I get the same error.
for gcc 5.2.1
strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6|grep CXXABI gives
CXXABI_1.3
CXXABI_1.3.1
CXXABI_1.3.2
CXXABI_1.3.3
CXXABI_1.3.4
CXXABI_1.3.5
CXXABI_1.3.6
CXXABI_1.3.7
CXXABI_1.3.8
CXXABI_1.3.9
CXXABI_TM_1
CXXABI_FLOAT128

For the compiler being compiled gcc 4.8.3
strings gcc-build/build/x86_64-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6|grep CXXABI

CXXABI_1.3
CXXABI_1.3.1
CXXABI_1.3.2
CXXABI_1.3.3
CXXABI_1.3.4
CXXABI_1.3.5
CXXABI_1.3.6
CXXABI_1.3.7
CXXABI_TM_1
CXXABI_1.3
CXXABI_1.3.2
CXXABI_1.3.6
CXXABI_1.3.1
CXXABI_1.3.5
CXXABI_1.3.4
CXXABI_TM_1
CXXABI_1.3.7
CXXABI_1.3.3

i.e no 1.3.8
prior to running configure and make I also tried:
export LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/:$LIBRARY_PATH
export LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu/:$LD_LIBRARY_PATH
../gcc-4.8.3/configure --build=x86_64-linux-gnu
make

Error message:
msgfmt -o fr.mo ../../../../gcc-4.8.3/libstdc++-v3/po/fr.po
msgfmt: gcc-build/build/x86_64-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/lib/x86_64-linux-gnu/libicuuc.so.55)
msgfmt: Makefile:460: recipe for target 'de.mo' failed

When compiling with gcc 4.1.2 I get the same error:
msgfmt -o fr.mo ../../../../libstdc++-v3/po/fr.po
gcc-build/gcc-4.8.3/build/x86_64-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/lib/x86_64-linux-gnu/libicuuc.so.55)
Makefile:460: recipe for target 'de.mo' failed

When compiling with gcc 4.1.2 i did the following prior to configure and make
#where libraries i have compiled with gcc 4.1.2 are located i.e
export LD_LIBRARY_PATH=/opt/devtools/gcc-4.1.2/lib
#where libstdc++.so.6 is
export LIBRARY_PATH=/opt/gcc-4.1.2/lib64

strings /opt/gcc-4.1.2/lib64/libstdc++.so.6|grep CXXABI
CXXABI_1.3
CXXABI_1.3.1
CXXABI_1.3.1
CXXABI_1.3

which makes me wonder where CXXABI_1.3.8 is coming from. I also did a 'make distclean' between changing compiler

A: I stumbled upon the same problem with a bit newer compiler combination, i.e. using gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 while building GCC 4.8.5. The solution worked out so far apparently did the job and gives valuable general explanation of the problem. I offer further details and an alternative solution below.
The error message in question comes from the msgfmt program - part of gettext, an internationalization and localization system:
$ which msgfmt
/usr/bin/msgfmt
$ dpkg -S /usr/bin/msgfmt
gettext: /usr/bin/msgfmt

msgfmt gets called by the GCC build system to compile messages emited by the C++ standard library (libstdc++) that is currently being built. msgfmt is a dynamically linked executable, linked (among others) against libicuuc.so.55 - a cross-platform Unicode based globalization library:
$ ldd /usr/bin/msgfmt
    libicuuc.so.55 => /usr/lib/x86_64-linux-gnu/libicuuc.so.55 (0x00007ff133f47000)

(other dependencies not shown for clarity)
The icuuc library is a dynamically linked shared object itself that depends on the stdc++ library:
$ ldd /usr/lib/x86_64-linux-gnu/libicuuc.so.55
    libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ff688a16000)

(other dependencies not shown for clarity)
The above listing was generated using my interactive shell environment, which resolves the dependency on libstdc++.so.6 to the system-wide version of the C++ library located in /usr/lib/x86_64-linux-gnu. However, the GCC build environment apparently resolves this dependency to the C++ library generated on the earlier stage of the current build process, i.e. to the one located in $TOP_BUILD_DIR/x86_64-linux-gnu/libstdc++-v3/src/.libs - recall the originally posted error message:
msgfmt: gcc-build/build/x86_64-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/lib/x86_64-linux-gnu/libicuuc.so.55)

I get a fairly similar output:
msgfmt: /opt/build/gcc/gcc-4.8.4/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by /usr/lib/x86_64-linux-gnu/libicuuc.so.55)

Now, answering the original question, the string 'CXXABI_1.3.8' comes from the libicuuc.so.55 library, which requires that the libstdc++.so.6 library it depends upon, provides a particular ABI version:
$ strings /usr/lib/x86_64-linux-gnu/libicuuc.so.55 | grep CXXABI
CXXABI_1.3.8
CXXABI_1.3

To summarize, the GCC build system creates a circular dependency, which mixes system-wide binaries with local libraries:
libstdc++ (currenlty built) > msgfmt > libicuuc.so.55 > libstdc++.so.6

by resolving libstdc++.so.6 to it's own library structure instead of the system-wide version.
The solution proposed by Mats Petersson, which involves rebuilding the libicuuc.so.55 library such that it depends on an older version of libstdc++.so.6, which is (hopefully) compatible with the GCC build system, is certainly valid. However, it seems a bit unnatural for my taste, as it requires playing around with dependencies of a system-wide binary, which is out of control of any non-root user.
My alternative solution involves building the custom version of the gettext package instead, such that the msgfmt binary is self-contained and its dependencies do not interfere with the GCC build system. It can be achieved by installing the custom version of gettext in /opt and adjusting the relevant paths using environment modules.

A: I had the same problem when I tried to build GCC 4.8.5 from source on Ubuntu 16.04.3 LTS with GCC 5.4.0.
As a workaround I just dropped LD_LIBRARY_PATH only for msgfmt command in makefiles. To be precise I give the exact commands I executed to get the build successful:
1 - extract the sources
tar zxfv gcc-4.8.5.tar.gz
cd gcc-4.8.5

2 - modify call of msgfmt (add LD_LIBRARY_PATH= ) and make sure it is correct
vi ./libstdc++-v3/po/Makefile.in
vi ./libstdc++-v3/po/Makefile.am
grep "MSGFMT =" ./libstdc++-v3/po/Makefile.in ./libstdc++-v3/po/Makefile.am
./libstdc++-v3/po/Makefile.in:MSGFMT = LD_LIBRARY_PATH= msgfmt
./libstdc++-v3/po/Makefile.am:MSGFMT = LD_LIBRARY_PATH= msgfmt

3 - configure (I restriced multilib to 64bit only, because I don't have libc6-dev-i386 installed on my 64bit host and don't want to do it only for this build), build and install
./configure --prefix=$HOME/gcc-4.8.5 --with-multilib-list=m64
make
make install

A: So, this problem occurs when a library that has been built with a newer compiler is linked with an older version of C++ library - or sometimes when a newer headerfile is used to compile something that then links to an older C++ library.
It is also possible come up with a similar problem when moving binary files from one system to another, if the shared libraries installed on the "new system" are older than the ones on which the code was built.
There are typically three plausible solutions:
 1. Recompile the offending library with an older compiler.
 2. Install a newever version of the C++ library.
 3. Rebuild the C++ library from sources (with a new enough compiler).

A: just copy libstdc++.so in system installed directory to your gcc source appropriate directory, remember to rename it properly.
attention: you may need to copy several times as during compiling, gcc will replace that library several times.


text:
Q: Check that matrix keys are in running order - python Given a matrix file and the first column is used as the key to a python dictionary (call it docid), how should I read the file such that it stops if the key is not in running order, i.e.

*

*if docid-1 > previous_docid or

*if docid < previd
I have been doing it as the code below but it looks a little verbose, is there any other way do producing the same output? (note: solution needs to handle matrix file that can go up to 20 GB. for the sake of a code snippet, i gave a small data set)
text = '''0 1 1
0 2 1
1 3 1
1 7 1
2 5 4
2 4 6
2 9 8
3 5 7
3 9 8
3 10 9
9 2 9
9 8 3
3 9 4'''

from collections import defaultdict
docs = defaultdict(list)
previd = -1
for line in text.split('\n'):
    docid, termid, val = map(int,line.split())
    if docid < previd or docid-1 > previd:
        print line
        break
    previd = docid
    docs[docid].append((termid,val))

for i in docs:
    print i, docs[i]

A: I can't see any simplifications, because the filtering condition depends on the previous element (making potential filtered iteration complex). I don't think your code is complicated but you can define a special traversal:
def read_text(text):
    for line in text.split('\n'):
        docid, termid, val = map(int,line.split())
        if docid < previd or docid-1 > previd:
            print line # I guess this is a debug feature
            return # or raise Exception("line not in running order", line)
        yield (docid, termid, val)

and in your main code:
for docid, termid, val in read_text(text):
    docs[docid].append((termid,val))

EDIT:
Instead of text.split('\n') maybe open('myfile','r') is more efficient.
for line in open('myfile','r'):
    do_something(line)


text:
Q: How to write a Ruby regexp for [A-Z0-9] repeat 3, or 4 times, no more? I want to detect 3P4, 4SC3, etc., but not 492-as. I tried  /[A-Z0-9]{3,4}/ but 492-as is still passing.
If anyone could help me with this regexp rule, I'd greatly appreciate it.

A: You need to use start and end of string anchors:
/\A[A-Z0-9]{3,4}\z/

See demo at Rubular
The \A forces the match at the beginning of a string, and \z matches the end of string.


text:
Q: culebra GUI not starting up I am new to culebra and i have run into some issues.
Firstly the document states that i should use
culebra -G to start the GUI. however, i am using python culebra -G else it will not recognize as a valid command.
Secondly upon starting the command, i get this exception after a while.
C:\Users\User\AppData\Local\Android\sdk\platform-tools>python culebra -G
C:\Python27\lib\site-packages\androidviewclient-10.5.1-py2.7.egg\com\dtmilano\an
droid\viewclient.py:2485: UserWarning: Running on emulator but no serial number
was specified then 'emulator-5554' is used
  warnings.warn("Running on emulator but no serial number was specified then 'em
ulator-5554' is used")
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2015-08-13 by Culebra v10.5.1
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

from com.dtmilano.android.viewclient import ViewClient

TAG = 'CULEBRA'

_s = 5
_v = '--verbose' in sys.argv

kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice':
False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'compresseddump': True, 'startviewserver': True, 'forceviewserveruse'
: False, 'autodump': False, 'ignoreuiautomatorkilled': True}
vc = ViewClient(device, serialno, **kwargs2)
#vc.dump(window='-1') # FIXME: seems not needed

Traceback (most recent call last):
  File "culebra", line 1080, in <module>
    runCulebron()
  File "culebra", line 786, in runCulebron
    culebron.takeScreenshotAndShowItOnWindow()
  File "C:\Python27\lib\site-packages\androidviewclient-10.5.1-py2.7.egg\com\dtm
ilano\android\culebron.py", line 249, in takeScreenshotAndShowItOnWindow
    self.unscaledScreenshot = self.device.takeSnapshot(reconnect=True)
  File "C:\Python27\lib\site-packages\androidviewclient-10.5.1-py2.7.egg\com\dtm
ilano\android\adb\adbclient.py", line 611, in takeSnapshot
    received = self.__receive(1 * 4 + 12 * 4)
  File "C:\Python27\lib\site-packages\androidviewclient-10.5.1-py2.7.egg\com\dtm
ilano\android\adb\adbclient.py", line 233, in __receive
    chunk = self.socket.recv(min((nob - nr), 4096))
socket.timeout: timed out

A: You can just supply a device ID to the culebra command.  Get your device/emulator id by doing this:
adb devices -l
Perhaps it will show 01a4968dd882b783.
Then, run culebra with something like this:
culebra -L -uUG --scale=0.2 -o myTestCase.py 01a4968dd882b783


text:
Q: Booking System. checking for existing data I want to check and compare the information on my input form with information that is stored in my database.
Basically. if trainer, sessionslot eventdate is the same dbtrainer, dbeventdate dbsessionslot ECHO "Booked";
                         Else insert into booking table
I know very little about programming, could really do with some help on this one.
This is snippet of the code i am using.
if(isset($_GET['add'])){
    $trainee = $_POST['txttrainer'];
    $trainer = $_POST['txttrainee'];
    $sessionSlot = $_POST['txtsession'];

    $eventdate = $month."/".$day."/".$year;
    $query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");

    $sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
    $resultinsert = mysql_query($sqlinsert);

            $numrows = mysql_num_rows($query);
            if($numrows == 1) {
                echo "this timeslot is booked"
                if($resultinsert){
                    echo "Booking Successful....";
                 }else{
                     echo "Booking Failed";
                 }
             }
}

A:     if(isset($_GET['add'])){
    $trainee = $_POST['txttrainer'];
    $trainer = $_POST['txttrainee'];
    $sessionSlot = $_POST['txtsession'];

    $eventdate = $month."/".$day."/".$year;
    $query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");

    $sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";

            $numrows = mysql_num_rows($query);
            if($numrows >0) {
                echo "this timeslot is booked"
             }else{
                 $resultinsert = mysql_query($sqlinsert);
                 if(mysql_error()==""){
                    echo 'time slot booked';
                 }else{
                    echo 'error';
                 }
             }
    }

Explanation:
if there are rows selected, the timeslot is booked, else execute the query. If there is no error with the query, then print out success.

A: If you call mysql_query, the query is executed. So you're executing the INSERT before you check whether the SELECT returned a row or not.
That means you should place the INSERT part inside an if($numrows != 1) condition.
Please be aware that using mysql_query is deprecated: http://ch1.php.net/manual/en/function.mysql-query.php and you should use MySQLi or PDO_MySQL. Your code is vulnerable to SQL injections.


text:
Q: passing "ref" between child components without click event Vue js I have two sibling components one has a form and the submit button is in the next component. I wanna pass ValidateObserver (from vee-validate) as a ref to other child component. And I use global Eventhub to communicate between sibling components.
// Component A
    <template>
        <ValidationObserver v-slot="{ handleSubmit }" ref="FullForm">
          <form @submit.prevent="handleSubmit(buildingForm)">
    </template>

methods:{

        buildingForm(){
            this.eventHub.$emit('building-form', data)

        },
},

And I'm catching it on component B
 //Component B

    methods(){

             buildingValidation(){
             this.$refs.FullForm.validate().then(success => {
                 if (!success) {
                     return this.step.id == this.currentstep;
                 }

             });

        },
             }

    created(){

            this.eventHub.$on('building-form', data => {

            //Here I'm calling the function buildingValidation()

            console.log(data);

            })

        },

What Am I missing? Thanks


text:
Q: make public website reconnect to local html or xampp Basically what I want to do is if I open this

http://steamcommunity.com/market

website on my pc I want to see a local website that is stored as html. I already tried to host the website with xampp which worked and trying to add

localhost/path http://steamcommunity.com/market

to my hosts file.
but instead of redirecting me to my local hosted html file it just loaded the steam market.

A: No idea why you'd wanna do this, but your hostsfile should be:
127.0.0.1  www.steamcommcunity.com
::1        www.steamcommcunity.com
127.0.0.1  steamcommunity.com
::1        steamcommunity.com

Just to be on the safe side I've used both with and without www, and both IPv4 and IPv6

A: This is a two step process: first, you have to redirect the web site name to your computer; next, you get Apache to redirect the web site address to your installed directory.
Locate your hosts file,
Add lines containing the domain name(s) and IP address to redirect to.
Each line must begin with the address 127.0.0.1 (this is the localhost address)
After the IP address, type the name of the domain you wish to redirect to this address. You may only enter 1 name per line.
Addresses like my-site.com and www.my-site.com are different and each need a separate line.
Save the changes.
Next,
Locate the httpd-vhosts.conf file. For most XAMPP 1.7.3 installs this will be C:\xampp\apache\conf\extra
Add the new host,
<VirtualHost *:80>
    ServerName www.joomla.16
    ServerAlias joomla.16
    DocumentRoot d:/xampp/htdocs/path/mysite
</VirtualHost>

Explanation of VirtualHost preparation,
ServerName: following this label, add the name of the domain you added in
ServerAlias: following this label, you may add as many alternate domains (separated by spaces) as you like that are supposed to resolve to this virtual host. Remember that www.my-domain.com is different from my-domain.com, but, typically, you would want them to resolve to the same server.
DocumentRoot: following this label, add the path where your website is located. You can use an absolute path (as in the example above), or a relative path (but relative paths can be trickier to set up, so I prefer to use an absolute path).
Restart Apache Web Server
You should now be able to type the domain name into your URL field and go directly to your locally hosted web site:
Please see this tutorial for more help.


text:
Q: SignalR objects are not being deleted from the heap even when the hub connection is disposed I have a web application that sends messages from the server to the front end (Javascript) client using SignalR. However, there is also a back end (.NET) client that creates a proxy to the hub. The back end client processes messages and sends them to the hub, and the hub then sends these messages to the front end client.
Here is a snippet of the back end client that creates the hub connection and proxy to send messages to the hub:
HubConnection hubConnection = new HubConnection(serverUrl);
IHubProxy hubProxy = hubConnection.CreateHubProxy(hubName);
Task t = Task.Run(() => hubConnection.Start(new LongPollingTransport()));
t.WaitAndUnwrap();
if (hubProxy != null && hubConnection.State == ConnectionState.Connected)
{
    await hubProxy.Invoke("MessageClients", messageArgs);
}

There is obviously more to the code, but that covers the essential part.
The key part is, every time a message is created, this code is called. That means there is a HubConnection object created for every message that needs to be sent to the hub, and then to the front end client.
After making a memory dump, I realized a lot of objects remain on the heap and is causing a memory leak. I figured it's because I'm not disposing the hub connection, since one of the main culprits is Microsoft.AspNet.SignalR.Transports.LongPollingTransport, with over a thousand objects on the heap after playing around with the website for about an hour (doing things that would create these SignalR messages).
So I thought disposing HubConnection would fix things:
using (HubConnection hubConnection = this.CreateHubConnection())
{
    if (hubConnection != null)
    {
        IHubProxy hubProxy = this.StartConnection(hubConnection);
        if (hubProxy != null && hubConnection.State == ConnectionState.Connected)
        {
            await hubProxy.Invoke("MessageClients", messageArgs);
        }
    }
}

private HubConnection CreateHubConnection()
{
    // do some basic auth set up
    HubConnection hubConnection = new HubConnection(this.serverUrl);
    hubConnection.Headers.Add('authToken', basicAuth);
    return hubConnection;
}

private IHubProxy StartConnection(HubConnection hubConnection)
{
    IHubProxy hubProxy = hubConnection.CreateHubProxy(this.hubName);
    Task t = Task.Run(() => hubConnection.Start(new LongPollingTransport())
    t.WaitAndUnwrap();
    return hubProxy;
}

But after running the process and attaching WinDbg to it, when I do -!dumpheap -stat -type Microsoft.AspNet.SignalR.Transports, again I see Microsoft.AspNet.SignalR.Transports.LongPollingTransport up there with similar high figures for objects on the heap + memory. Shouldn't the using statement cause HubConnection to be disposed and therefore removed from the heap? What should I be doing to fix this memory leak?

A: It turns out that disposing the hub connection does work. I was conflating two concepts: disposing unmanaged resources and deleting objects from the heap.
I thought that when the using statement for the HubConnection object finishes (i.e., when dispose is called on HubConnection), WinDbg would no longer show that object in the memory dump. But since the memory dump is based on what's on the heap, and since disposing an object doesn't delete the object from the heap (just allows it to be released and deleted by the garbage collector), it was still showing in WinDbg.
I played around with the application more until the garbage collector did its work, and found that the objects were deleted later.
I should also note that my original question emphasized the type Microsoft.AspNet.SignalR.Transports.LongPollingTransport, and that was because I was not disposing the LongPollingTransport object either (when I do hubConnection.Start(new LongPollingTransport()). So my code now looks like the following:
using (HubConnection hubConnection = this.CreateHubConnection())
{
    if (hubConnection != null)
    {
        using (LongPollingTransport lpTransport = newLongPollingTransport())
        {
            IHubProxy hubProxy = this.StartConnection(hubConnection, lpTransport);
            if (hubProxy != null && hubConnection.State == ConnectionState.Connected)
            {
                await hubProxy.Invoke("MessageClients", messageArgs);
            }
        }
    }
}

private HubConnection CreateHubConnection()
{
    // do some basic auth set up
    HubConnection hubConnection = new HubConnection(this.serverUrl);
    hubConnection.Headers.Add('authToken', basicAuth);
    return hubConnection;
}

private IHubProxy StartConnection(HubConnection hubConnection, HttpBasedTransport transport)
{
    IHubProxy hubProxy = hubConnection.CreateHubProxy(this.hubName);
    Task t = Task.Run(() => hubConnection.Start(transport));
    t.WaitAndUnwrap();
    return hubProxy;
}


text:
Q: How can I analyze multiple s3 inventories using athena? I want to analyze multiple s3 inventories using athena.
I have multiple s3 inventories for multiple buckets.
I want to load all inventories into one table.
Could you give any idea?

A: If your files have the same schemas I suggest to use table partitioning functionality. You can create partitioned table and then add each bucket as partition.
https://docs.aws.amazon.com/athena/latest/ug/partitions.html
You can use also Glue Crawler:
https://docs.aws.amazon.com/athena/latest/ug/glue-best-practices.html#schema-crawlers-data-sources


text:
Q: Python program erroring out with "maximum recursion depth exceeded while calling a python object" I have a python program that I am currently working on which is working pretty well except for the fact that I am running into "recursion depth" issues and I am not sure how to rework my program to avoid this.
my program is basically something like this in a nutshell:
def foo()
    x = 0 #

    while x != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         foo()
     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"
          foo()
#start
foo()

Ultimately my program works as it is but eventually will crash out with the recursion limit error so not ideal as I need this program to run endlessly but being a total newb to programming I am unsure how to fix it. I did try to split my program into two or three separate function rather than just the one but it was still exhibiting the recursion issue.
Thanks for any input. If anyone needs more code I can post it but thought the small piece should be sufficient to see where I am going. Any help would be appreciated.

A: I would try this since it repeatedly calls the function at the same recursion level:
def foo()
    x = 0 #
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:

     ''' it continues checking "bar" using some more if statement. Finally when the
         logic is satisfied the program outputs something but still restarts foo() as
         I need the program to run endlessly but I am not sure how to fix the recursive
         nature of the program'''
      if bar = 1234567890:
          print "yay you win"

#start
while 1:
    foo()

A: Inside of foo just use a loop such as:
while True:

    x = 0 #
    while arming != 1:
        x = (mydll.InPortB(base+1)) & 1 # this is a hardware input like a push button(on or off)
        time.sleep(0.5)

     bar = ser.readline() # input from serial source
     if len(bar) != 10:
         # do whatever you want but don't call foo

You don't need to call foo recursively for the program to keep running. The while True will take care of that.


text:
Q: Toggle between two div tags using javascript I'm facing problem with toggle using JQuery between two divs. I don't have much knowledge with JQuery.
I want to display div1(create) when clicking a create and should hide div2(insert). In the same way when I click insert it should display div2(insert) and hide div1(create). Can some one please help me with this?
This is the code for anchor tags
     #Start of div tag1

Array Operations

                   Creation

                   Insertion

 #End of div1

This the code for div tags

 #Start of div tag2

C++

#Creating an array in C++

#include < iostream >

    using namespace std;

    int a [10]

 #End of create div

C++

#Inserting an array in C++

#include < iostream >

      using namespace std;

      int a [10]

 #End of insert div

 #End of div tag2

This is css for first div tag

This is the jquery
$('.insert').hide();
 $('.create, .insert').on('click',
  function() {
  $('.create, .insert').toggle()
 }
);

A: I added a class for all of the page sections called .panel that hides the panels by default (display: none;), and gave the first panel a class of .active which will show a panel. Then when you click on one of the links at the top, use the href attribute to target the class of the panel, remove .active from any panel you didn't click on, and add .active to the one you clicked on.

var $panels = $('.panel'),
    $links = $('#first a');
$links.on('click',function(e) {
  e.preventDefault();
  var $target = $('.' + $(this).attr('href'));
  $panels.not($target).removeClass('active');
  $target.addClass('active');
})
.panel {
  display: none;
}
.active {
  display: block;
}

Array Operations

  Creation

  Insertion

C++

#Creating an array in C++

#include < iostream >
 using namespace std;
 int a [10]

C++

#Inserting an array in C++

#include < iostream >
 using namespace std;
 int a [10]

A: Here is some code using simple jQuery syntax to show/hide the divs you mentioned. You can test the code here --> https://jsfiddle.net/Lp8m2mry/

Array Operations

        Creation

        Insertion

C++

#Creating an array in C++

#include < iostream >

                using namespace std;

                int a [10]

C++

#Inserting an array in C++

#include < iostream >

                using namespace std;

                int a [10]


text:
Q: Push notification is not working when I transfer app to other account I have transfered the app after I released new version push notification is not working
Thanks in advance

A: Even though the problem description is very lacking I think that the solution is very obvious: the APNS certificate is strongly linked to the Apple Member account certificates/provisioning files. If they don't match, the push won't come through.
That means, you have to sign your app with the same provisioning file (with the same bundle id) you've signed the old app with.
If you don't have the access to the old provisioning file's certificates, you have to create a new APNS certificate.
StackOverflow question explaining setting up APNS certs
or
certs tutorial

A: Either the original account owner has invalidated the original push notification certificate, or you have an error in your server unrelated to the transfer process.
I advice you to

*

*Create a new push certificate.

*Test that it works by sending a notification from a desktop app like APNS Pusher.

*Update the push certificate in your server.


text:
Q: How to fix 'Expected an assignment or function call and instead saw an expression no-unused-expressions' error in jsx VS Code I have some code and it keeps giving me this error, and I can't find the reason why. Error: 'Expected an assignment or function call and instead saw an expression  no-unused-expressions'
I have tried to delete the return, but that doesn't work.
import React, { Fragment } from 'react';
import Search from '../users/Search';
import Users from '../users/Users';

const Home = () => {
  <Fragment>
    <Search />
    <Users />
  </Fragment>
};

export default Home

A: You are missing () around Fragments.
const Home = () => {
  return (<Fragment>
    <Search />
    <Users />
  </Fragment>)
};

OR -
const Home = () => (
  <Fragment>
    <Search />
    <Users />
  </Fragment>
);


text:
Q: Accessing methods with the same name I have three classes that all have a method with the same name. My Main class has the method (called automatically when the user clicks their mouse):
public void mouseDown()

My second class is called Bed and has the method:
public void mouseDown()

My third class is called CreateBedButton and has the method (which returns a Bed object):
public Bed mouseDown()

I am able to access the Bed class' mouseDown method fairly easily from the mouseDown method in Main, but I have no idea how to indicate that I want to call the CreateBedButton class' mouseDown method. They all have no parameters, but when I call the Bed class' mouseDown method I access it through a Bed object I created using:
bed.mouseDown();

When I try just calling:
mouseDown();

from Main, it calls the Main method's mouseDown method again. is there any way that I can access all three methods/make it apparent which method I actually want to access??

A: Call .mouseDown() to access the Main class' method. Call bed.mouseDown() to access the Bed class' method. Call createRedButton.mouseDown() to call the CreateRedButton class' method.
This assumes that you have the variables Bed bed = new Bed(); and CreateRedButton createRedButton = new CreateRedButton() declared.
An example is below.
class Main {

    public void main(String [] args) { // Starting point of program
        Bed bed = new Bed();
        CreateRedButton createRedButton = new CreateRedButton();
        mouseDown(); // Calls Main's mouseDown();
        bed.mouseDown(); // Calls Bed's mouseDown();
        Bed catchingBed = createRedButton.mouseDown(); // Calls CreateRedButton's mouseDown(); - Which returns a Bed

        // Or you can even do this..
        CreateRedButton redButton = new CreateRedButton();
        Bed bed = redButton.mouseDown();
        bed.mouseDown();
    }
    public void mouseDown() {
        // Some code
    }
}
class Bed {

    public void mouseDown() {
        // Some code
    }
}
class CreateRedButton {
    public Bed mouseDown() {
        // Some code to return a Bed
    }
}


text:
Q: git push is failing - Permission denied (publickey) I have a gerrit server with multiple repos.
in the manifest i am using  the https://url and it works fine for fetching.
i set a sshl pushurl="ssh://ssh-dns-name:29418" (note no username as part of this).
When i do the sync all the projects have remotes like -
origin  https://url/my_project  (fetch)
origin ssh://ssh-dns-name:2941/my_project (push)

now, when i do push, the git is complaining that Permission denied (publickey)!!!
i see that the user.name and user.email are setup properly.
user.name "Abhayadev S" (whic is setup in gerrit as user Full name)
and user.email "abhayadevs...@in.com" which is setup in gerrit as user email
also my client machine login name is "abhayadevs" which is the gerrit username.
if i use the username in the pushurl (ssh://abhayadevs@ssh-dns-name:29418), everything is working fine !
so i am confused, why git is not taking the username !!!!
i checked the git config --local --list, nothing is set locally !!!
only global git config has the user.name and user.email !!!

A: The user.name and user.email configurations have no effect on authentication in any way.  They affect only the personal name and email address you put in a commit or tag.
If it works for you to put the username in the push URL, then do that: that's the simplest, easiest way to make this work.  Every user using a site such as GitHub or GitLab must put the username (git) in the URL, so doing so shouldn't be a problem.  If you don't specify a username, the default is determined by OpenSSH and usually defaults to that of your local user, although it is case sensitive.  You can also override it explicitly in ~/.ssh/config if you need to, but it's probably just easier to specify it in the URL.


text:
Q: How to access the methods and html zones of one component from another in Angular 4+? Here is the scenario:
app.component.html got the main layout;
say you got a RED-STICKY-HEADER at the top,
and then you got a TOGGLING-ORANGE-SIDENAV on the left, and a STEADY- GREEN-SIDENAV on the right. ( the colors are only for reference purposes and make my question easier to follow. )
And to conclude, the app.component.html also has the <router-outlet></router-outlet> and that is to house the other components' html. Duh!
OK... I'm done with the scenario. So far, it's just an ordinary set up.
Here comes the complication in my mind and my question:
Say, you click on a link at the RED-STICKY-HEADER and this brings the component X's HTML in the middle.
Is it possible that you click on something on the component X's html, and this does an update on the GREEN SIDENAV contents? Please note that here, the URL does not change, no reloads takes place, and the only thing that happens is the fact that green sidenav content changes to something else. ( which could be an HTTP get request results being dumped in there, but this does not matter. )The jest of the question is is it possible to make a change in the areas that belong to app.component.html from another component?
If this is possible, then I will also ask whether it is also possible that I can trigger a component X method by clicking on a link at the RED STICKY HEADER.
In other words, is it possible to access and trigger the method of component X while you are on the app.component.html URL?

A: Yes it is possible.
You can write a common service for RED-STICKY-HEADER 's component and middle component then make the updating variable as observable one in your common service.
please refer the code to create a object / list as observable in service.
 @Injectable()
 export class CommonService {
     aListWhichIsSubscribedByRedStickyHeader: Array<YourObject>;
     private subject = new Subject<Array<YourObject>>();

     // this is the method used to get the observable property
     getSubscribedVariables() {
         return this.subject.asObservable();
     }

     aMethodCalledByAnotherComponent(){
       /*modyfying the aListWhichIsSubscribedByRedStickyHeader
       property . Just assume that your middle component is calling this
       method to save the object received from hhtp get request*/
     }

   this.subject.next(this.aListWhichIsSubscribedByRedStickyHeader); // so it will reflect in RedStickyHeader component's constructor.
 }

How you are going to subscribe it ? refer below code
  export class RedStickyComponent implements OnInit{

     aObjectList : Array<YourObject>;
     constructor(serviceCommon : CommonService){
        this.serviceCommon.getSubscribedVariables().subscribe(e => {
        let list = e;
        this.aObjectList = JSON.parse(JSON.stringify(list));
        })
     }

  }

so in this RedStickyHeader component wherever you are using the aObjectList there you will get changes. or by analyzing the object you can change anything inside this component or you can call another service from it.


text:
Q: Searching a column and evaluating adjacent cell in excel I'm trying to make a spreadsheet that can tell me when somebody is in doing two things at the same time.  say column A contains names, column B has the sign in time, and C has Sign out time.  I am trying to find a way to assess whether any other instances of the same name had overlap in the time in and time out.  I considered Vlookup, but that only gets me to the first instance.
Essentially I'm looking for if(A from this row exists anywhere else in column A and the adjacent B cell >= this row's B cell and the adjacent C cell >= this row's C cell, then true, otherwise do something else)
I work in a machine shop, and it's very common for people to work two machines at the same time. I understand my example a moment ago was only one of several possible ways the times could overlap, but if I could get help getting that far I would be ecstatic.  even pointing me in the broadest of directions like "not possible without learning to code" would be helpful.
My excel skills are limited essentially to what I can learn in the help file, and as of now I'm ok with ifs.  Any help would be appreciated.  Do I need to learn VBA for this?

A: I am not an Excel power user. I learnt VBA because of employers who provided me with Excel but would not allow me use of other programmable tools. I have never made serious use of the more advanced capabilities of Excel. There are a surprising number of questions that get the comment, "you could do this with a Pivot table" but never an explanation of how.  To be fair questions about Pivot Table belong on the SuperUser site but I find it a really unhelpful comment.
I do not know and do not care if your requirement can be met with a Pivot Table.  I wish to show how simple tasks can be solved with VBA even if they cannot be solved with advanced Excel functionality.  The macro below did not take long to write and I believe it meets your requirement.
Yes you should learn VBA. It does not take long to learn the basics and it can be used to solve many simple problems. I cannot imagine not being able to create macros or programs to solve day-to-day problems.
Search the web for "Excel VBA tutorial".  There are many to choose from.  Try a few and complete one that matches your learning style.  I prefer books to online tutorials.  I visited a large library and checked out their Excel VBA Primers.  I then bought the one that worked best for me.
I will admit there is a lot of practice behind the macro below but I believe the real skill is in breaking your requirement into steps that can be solved easily with Excel VBA.
I created a worksheet Log which I filled with data that matches my understanding of your data.  Perhaps your people do not run so many machines at the same time but I wanted to test my macro thoroughly.

The macro creates a copy of this worksheet (in case you do not want it sorted) and names it Temp.  It then sorts Temp by Name and Sign-on time to give:

The macro compares adjacent rows and copies overlaps to worksheet Overlap:

Finally it deletes worksheet Temp.
My objective was to fully explain what the code does but not how the macro does it. Once you know a statement exists, it is usually easy to look it up.  Come back with questions if necessary but the more you can decipher for yourself the faster you will develop your skills.
Option Explicit
Sub FindOverlap()

  Dim RowOverCrnt As Long
  Dim RowTempCrnt As Long
  Dim RowTempLast As Long
  Dim WithinOverlap As Boolean
  Dim WshtLog As Worksheet
  Dim WshtOver As Worksheet

  ' My principle reason for using worksheet objects is so the names appear in a single place.

  Set WshtLog = Worksheets("Log")       ' Change Log to your name for the source worksheet
  Set WshtOver = Worksheets("Overlap")  ' Change Log to your name for the destination worksheet

  ' Create temporary copy of worksheet "Log" in case sequence must be preserved.
  ' This is not necessary if you do not care if worksheet Log is sorted.
  WshtLog.Copy After:=Sheets(Worksheets.Count)
  Sheets(Worksheets.Count).Name = "Temp"

  ' Clear any existing data from destination worksheet and copy the headings from the
  ' source worksheet
  With WshtOver
    .Cells.EntireRow.Delete
    WshtLog.Rows(1).Copy Destination:=.Range("A1")
  End With
  RowOverCrnt = 2       ' First to which rows from worksheet Log will be copied

  ' Sort worksheet Temp by Name and Sign-in time
  With Worksheets("Temp")
    With .Cells
      .Sort Key1:=.Range("A2"), Order1:=xlAscending, _
            Key2:=.Range("B2"), Order2:=xlAscending, _
            Header:=xlYes, OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
            DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
    End With

    ' This is the VBA equivalent of selecting the cell at the bottom of column A
    ' and clicking Ctrl+Up.  With the keyboard, this move the cursor up to the first
    ' cell with a value and selects that cell.  That is, it selects the last cell from
    ' the top with a value.  This statement sets RowTempLadst to the row number of that
    ' cell.
    RowTempLast = .Cells(Rows.Count, "A").End(xlUp).Row

    WithinOverlap = False     ' Not currently within a set of rows that overlap.
    ' I assume row 2 is the first data row.  This loop checks a row for an overlap with
    ' the previous row.  This is why the start row is 3.
    For RowTempCrnt = 3 To RowTempLast
      If .Cells(RowTempCrnt, "A").Value = .Cells(RowTempCrnt - 1, "A").Value And _
         .Cells(RowTempCrnt, "B").Value < .Cells(RowTempCrnt - 1, "C").Value Then
        ' The current row and the previous row are for the same person and
        ' the start time of the current row is before the end time of the previous row
        If WithinOverlap Then
          ' Previous rows have overlapped and have been copied to worksheet Overlap.
          ' Add current row to end of current set of overlaps
          .Rows(RowTempCrnt).Copy Destination:=WshtOver.Cells(RowOverCrnt, "A")
          RowOverCrnt = RowOverCrnt + 1     ' Advance to next free row
        Else
          ' The current and previous rows overlap.  Copy both to worksheet Overlap.
          .Rows(RowTempCrnt - 1 & ":" & RowTempCrnt).Copy _
                                        Destination:=WshtOver.Cells(RowOverCrnt, "A")
          RowOverCrnt = RowOverCrnt + 2     ' Advance to next free row
          WithinOverlap = True   ' Record within overlap set
        End If
      Else
        ' Current row does not overlap with previous
        If WithinOverlap Then
          ' An overlap set has ended
          RowOverCrnt = RowOverCrnt + 1     ' Leave gap between overlap sets
          WithinOverlap = False             ' Record no longer within overlap set
        End If
      End If
    Next RowTempCrnt

  End With

  ' Delete worksheet Temp
  ' "Application.DisplayAlerts = False" suppresses the "Are you sure you want to delete
  ' this worksheet?" question.
  Application.DisplayAlerts = False
  Worksheets("Temp").Delete
  Application.DisplayAlerts = True

End Sub


text:
Q: Combining results into one object I'm looping through a set of inputs. I need to tally up the grouped totals. The inputs below to one of three categories.
How do I go about combining the values up relevant to three categories?
var compoundedArray = new Array();

    holder.find(".dataset input").each(function(index) {
        var val = $(this).val();
        var dataType = $(this).data("type");

        var localObj = {};

        localObj[dataType] = val;
        compoundedArray.push(localObj);
    });

I have an object like this
[
    {
    "growth":30
    },
    {
    "growth": 40
    },
    {
    "other": 20
    }
]

how do I loop through the object to produce something like
[
    {
        "growth": 70
    },
    {
        "other": 20
    }
]

if I looped over the initial array object
for (var i = 0; i < compoundedArray.length; i++) {
console.log(compoundedArray[i]);
}

how would I go about checking to ensure I don't have duplicates - and that I can tally up the results?
Ideally the resulting format may be the best
var array = [
    "matching": 50,
    "growth": 20
]

A: var array = [
    "matching": 50,
    "growth": 20
]

is not valid JS, but you can create an object of the form
var obj = {
    "matching": 50,
    "growth": 20
};

And that's pretty easy to do, just use an object from the very beginning:
var result = {};

holder.find(".dataset input").each(function(index) {
    var val = +$(this).val(); // use unary plus to convert to number
    var dataType = $(this).data("type");

    result[dataType] = (result[dataType] || 0) + val;
});

Further reading material:

*

*MDN - Working with Objects

*Eloquent JavaScript - Data structures: Objects and Arrays

A: You can just use an object (not array) with unique keys.
var compoundedObj = {};

$(".dataset input", holder).each(function() {
    var dataType = $(this).data("type");
    if(!compoundedObj.hasOwnProperty(dataType)) {
        compoundedObj[dataType] = 0;
    }
    compoundedObj[dataType] += parseInt($(this).val(), 10);
});

In this way you'll get an object like this:
{
    "growth": 70,
    "other": 20
}

Live demo

A: http://jsfiddle.net/GFwGU/
var original = [{"growth":30},{"growth": 40},{"other": 20}]

// object to sum all parts by key
var sums = {}
// loop through original object
for(var index in original){
    // get reference to array value (target object)
    var outer = original[index]
    // loop through keys of target object
    for(var key in outer){
        // get a reference to the value
        var value = outer[key]
        // set or add to the value on the sums object
        sums[key] = sums[key] ? sums[key] + value : value
    }
}

// create the output array
var updated = []
// loop through all the summed keys
for(var key in sums){
    // get reference to value
    var value = sums[key]
    // create empty object
    var dummy = {}
    // build object into desired format
    dummy[key] = value
    // push to output array
    updated.push(dummy)
}

// check the results
alert(JSON.stringify( updated ))

A: var add=function (a,b){ a=a||0; b=b||0; return a+b};
var input=[ {growth:30},{growth:40},{other:20} ],output=[],temp={};

$.each(input,function(i,o){
  var n;
  for(i in o)
     {n=i;break}
  temp[n]=add(temp[n],o[n]);
});

$.each(temp,function(i,o){
  var k={};
   k[i]=o;
  output.push(k)
});


text:
Q: Bibtex not giving the right numbers for the citations used I am going to try to just describe the problem and not post my code here to see if someone just knows the answer.
Basically I set up some references and I have something like [1] Author ... [2] Author etc. So the Author is the same but the years differ. When I say \cite{Author-2} (assuming this is the label for [2]) I keep getting [1].
In my file there are 5 citations under the same Author and the output PDF keeps putting the wrong citation like above: gives [1] if I label with [2]. Any ideas on why this could be? I can post my code, but it is long...


text:
Q: vDSP_ztoc producing odd results I'm trying to figure out the vDSP functions and the results I'm getting are very strange.
This is related to this question:
Using std::complex with iPhone's vDSP functions
Basically I am trying to make sense of vDSP_vdist as I start off with a vector of std::complex< float >.  Now AFAIK I should be able to calculate the magnitude by, simply, doing:
// std::abs of a complex does sqrtf( r^2 + i^2 ).
pOut[idx]   = std::abs( pIn[idx] );

However when I do this I see the spectrum reflected around the midpoint of the vector.  This is very strange.
Oddly, however, if I use a vDSP_ztoc followed by a vDSP_vdist I get exactly the results I expect.  So I wrote a bit of code to try and understand whats going wrong.
bool VecMagnitude( float* pOut, const std::complex< float >* pIn, unsigned int num )
{
    std::vector< float > realTemp( num );
    std::vector< float > imagTemp( num );

    DSPSplitComplex dspsc;
    dspsc.realp = &realTemp.front();
    dspsc.imagp = &imagTemp.front();

    vDSP_ctoz( (DSPComplex*)pIn, 1, &dspsc, 1, num );

    int idx = 0;
    while( idx < num )
    {
        if ( fabsf( dspsc.realp[idx] - pIn[idx].real() ) > 0.0001f ||
             fabsf( dspsc.imagp[idx] - pIn[idx].imag() ) > 0.0001f )
        {
            char temp[256];
            sprintf( temp, "%f, %f - %f, %f", dspsc.realp[idx], dspsc.imagp[idx], pIn[idx].real(), pIn[idx].imag() );
            fprintf( stderr, temp );
        }
    }
    return true;
}

Now whats strange is the above code starts failing when idx = 1 and continues to the end.  The reason is that dspsc.realp[1] == pIn[0].imag().  Its like instead of splitting it into 2 different buffers that it has straight memcpy'd half the vector of std::complexes into dspsc.realp.  ie the 2 floats at std::complex[0] then the 2 floats in std::complex[1] and so on.  dspsc.imagp is much the same.  dspsc.imagp[1] = pIn[1].real().
This just makes no sense.  Can someone explain where on earth I'm failing to understand whats going on?


text:
Q: Decimal conversion scale errors I am trying to  understand data types more..here are few examples which are still puzzling me.

Decimal(p,s)--p is the total digits,s is number of digits after point

So given below example
declare @st decimal(38,38)
set @st=1.22121065111115211641641651616511616

I am getting below error..

Arithmetic overflow error converting numeric to data type numeric

len(digits) after point is 35,total digits including . are 37 ...shouldn't my decimal of (38,38) work
So my question is why i am getting the above error
Here is my research so far..
How do I interpret precision and scale of a number in a database?
Decreasing scale like below works..
declare @st decimal(38,37)
set @st=1.22121065111115211641641651616511616

Answer by boumbh points out an out of range error,but i am not getting error for same example

A: @TheGameisWar
According to the above example , you have specified decimal(38,38).
and value = 1.22121065111115211641641651616511616, Sql Server checks whether they're any digits to left of point. As (p-s) gives the total number of digits to the left. Therefore if we do it for your case we get (38-38)= (0)
hence the value given by you doesn't satisfy the decimal precision and scale value.
if you place 0 to left of the point ,then it works
Ex:- 0.22121065111115211641641651616511616
And for the below case decimal(38,37), We get (38-37) = (1) therefore one digit can be accepted left of the point. hence the value is accepted and executed.
Precision and scale indirectly decides the number of digits to the left of point.  :)

A: The answer is in MSDN.

decimal[ (p[ , s] )]
p (precision) The maximum total number of decimal digits that will
  be stored, both to the left and to the right of the decimal point. The
  precision must be a value from 1 through the maximum precision of 38.
  The default precision is 18.
s (scale) The number of decimal digits that will be stored to the
  right of the decimal point. This number is subtracted from p to
  determine the maximum number of digits to the left of the decimal
  point. The maximum number of decimal digits that can be stored to the
  right of the decimal point. Scale must be a value from 0 through p.
  Scale can be specified only if precision is specified. The default
  scale is 0; therefore, 0 <= s <= p.

I highlighted the relevant phrase.
When you specify the same value (38) for p and s you don't leave room for any digits before the decimal point.


text:
Q: C - Вывести на экран из файла строки длиной больше 60 символов #include <stdio.h>
#define N 255

void main()
{
    char mem[N];
    FILE * fil;
    int temp, k, length = 60;
    fil = fopen("D:\\FilesProjects\\1file.txt", "rt");
    while (fgets(mem,N,fil)!=NULL)
    {
        if (strlen(mem) >= 60) printf("%s \n", mem);

    }
    fclose(fil);
    system("pause");
}

Возможно ли переделать данный код так, чтобы он выводил на экран строки из файла определенной длины БЕЗ использования массивов или строк? Очень надо.

A: Да, можно. Вам нужно уметь находить и запоминать границы строк, где левая граница - начало файла или <позиция последнего перевода строки + 1>, а правая - позиция следующего перевода строки. То есть запоминаете позицию начала строки, считываете символы и считаете их количество с помощью getchar() до тех пор, пока не встретите перевод строки или конец файла, затем, если количество считанных символов подходит под условие для вывода строки, то с помощью fseek переводите курсор чтения файла на запомненную ранее позицию начала строки, опять читаете посредством getchar() символы и сразу же выводите их до конца строки. Повторяете для каждой строки, не забывая сбрасывать счетчик посчитанных символов в строке.

A: Может так?
long cur = 0;

while (fgets(mem,N,fil) !=NULL)
{
    long next = fseek(fil, 0, SEEK_CUR);
    if ((next - cur) > 60)
       fputs(mem,fil);

    cur = next;

}
fputc('\n',fil);


text:
Q: How to format hour and minute in Chinese with PHP I need to display a time in Chinese format with PHP.
I already try to use strftime :
setlocale(LC_TIME, "zh_CN");
echo strftime("%a, %Y %B %d");

It's work for date and display : 二, 2013 十一月 05
but for time :
setlocale(LC_TIME, "zh_CN");
echo strftime("%H %M");

display : 14 30
But 2:30pm have to be displayed like : 下午2时30分 for zh_CN and 下午2時半 for zh_HK
Did you kwon a solution or a php library to do that ?
Thx
PS : a javascript solution on client side can be good also ;)

A: I don't get the exact output you want but this is normally a good job for the intl extension:
<?php

$locales = array(
    'en_US',
    'en_GB',
    'zh_CN',
    'zh_HK',
);

$date = new DateTime('14:30');
foreach($locales as $locale){
    $fmt = new IntlDateFormatter($locale, IntlDateFormatter::NONE, IntlDateFormatter::SHORT);
    echo $fmt->format($date) . PHP_EOL;
}

... prints:
2:30 PM
14:30
下午2:30
下午2:30

If you stick to strftime you'd have to use %I ("Two digit representation of the hour in 12-hour format") rather than %H ("Two digit representation of the hour in 24-hour format") together with %p/%P ("AM/PM"). There's also %X ("Preferred time representation based on locale, without the date").
If you don't really need to support many languages, writing your own date formatter would be a sensible alternative.
As for JavaScript, I always see Moment.js recommended here but I haven't used it.

A: PHP gives inconsistent results when it comes to Chinese time support.
The solution which worked for me is to output the time ISO format and use jQuery and moment.js to get very close to the perfect solution to deal with internationalised time:
In php output your time to a .
echo ''
    .date('h:n').'';

where date('c') returns the ISO formatted date and moment-format defines the format moment.js should use to replace the ISO time
In Javascript you simply replace all the time formats :
    moment.lang('zh-cn'); // or zh-tw
    $('span[moment-format]').each(function(index, element) {
        if($(this).attr('date'))
        {
            $(this).html(
                moment().format($(this).attr('moment-format'))
            );
        }
    });


text:
Q: Access denied for user 'root'@'%' to database 'information_schema' I created a Google Cloud sql database, and I tried to access it with DataGrip.  However, I get this message when I try to create a table:
Access denied for user 'root'@'%' to database 'information_schema'

A: Access denied for user 'root'@'%' to database 'information_schema':
1.) Check username and password.
2.) Check user access permission.

A: Check your conection information or try creating a new username and password.
In other cases can be the host..
Regards!


text:
Q: rxdart: Get buffered elements on stream subscription cancel I'm using a rxdart ZipStream within my app to combine two streams of incoming bluetooth data. Those streams are used along with "bufferCount" to collect 500 elements each before emitting. Everything works fine so far, but if the stream subscription gets cancelled at some point, there might be a number of elements in those buffers that are omitted after that. I could wait for a "buffer cycle" to complete before cancelling the stream subscription, but as this might take some time depending on the configured sample rate, I wonder if there is a solution to get those buffers as they are even if the number of elements might be less than 500.
Here is some simplified code for explanation:
subscription = ZipStream.zip2(
  streamA.bufferCount(500),
  streamB.bufferCount(500),
  (streamABuffer, streamBBuffer) {
    return ...;
  },
).listen((data) {
  ...
});

Thanks in advance!

A: So for anyone wondering: As bufferCount is implemented with BufferCountStreamTransformer which extends BackpressureStreamTransformer, there is a dispatchOnClose property that defaults to true. That means if the  underlying stream whose emitted elements are buffered is closed, then the remaining elements in that buffer are emitted finally. This also applies to the example above. My fault was to close the stream and to cancel the stream subscription instantly. With awaiting the stream's closing and cancelling the stream subscription afterwards, everything works as expected.


text:
Q: Reasonable Security for a shared user identification token? I've run into an odd crypto problem that I'm probably making more of than needs to be, on which I will blame my current low fever. I just really dislike rolling my own solution on anything crypto related without at least some review.
I'm in the process of implementing a SSO solution for integrating a third party service, wherein I authenticate users against our own authentication platform, which returns to me a limited number of consistently available variables when the user properly authenticates against it.
One of these that is guaranteed to always represent a given user is their login ID on our network. None of the others which are allowable in this context are guaranteed to remain the same for a given user.
I can't store the login ID in plaintext on the third party service as a shared token. (before you question why, there is a very simple reason: legal doesn't like it... while this identifier was created specifically to not be FERPA sensitive, it's essentially only once removed)
I can hash it. Since there is presumably a good reason for not storing it elsewhere in plaintext, I would like to hash it at least reasonably well. Normally, if there were some other, non sensitive identifier for a given user, I could bcrypt the sensitive information (like, if it were a password) and store that salt+hash and a PK non-sensitive identifier in a table, then look it back up based on the non-sensitive identifier when doing a comparison.
Without a non sensitive identifier to perform retrievals with, it would seem I would be stuck just doing a basic hash operation without a unique salt (I can still pepper them). Anything I store in my own DB would be just as vulnerable as what is being passed as a token, so there's no point in creating a map table of raw login IDs to salted and hashed login IDs. Blindly testing a given hash against every salt+hash I have stored would be ridiculous.
I could just go ahead and SHA2 with a pepper the login IDs and call it a day (these are, after all, "just" login IDs and not passwords--and that solution has been deemed at least adequate), but I'm wondering if there isn't a better solution for this case?

A: I guess you should know this: letter from US Department of Education to University of Wisconsin-River Falls:

We believe that FERPA allows an institution to designate and disclose
  as "directory information" a unique personal identifier, such as a
  student's user or account logon ID (or an email address used as a
  logon ID), as long as the identifier cannot be used, standing alone,
  by unauthorized individuals to gain access to non-directory
  information from education records. In other words, if a student must
  use a shared secret, such as a PIN or password, or some other
  authentication factor unique to the student, along with their personal
  identifier to gain access to their records in the student information
  system, then that identifier may be designated and disclosed as
  directory information under FERPA in accordance with the requirements
  of § 99.37 of the regulations. (Allowance is made for school officials
  to use the student's published personal identifier alone, just as they
  use a student's name, to obtain access to the student's education
  records, provided the school official has a legitimate educational
  interest in accordance with § 99.31(a)(1) of the regulations.)
Conversely, if an institution allows students to access own education
  records using a personal identifier but without the use of a password
  or other factor to authenticate the student's identity (or if the
  identifier itself is also used to authenticate the student's
  identity), then that identifier may not be disclosed as directory
  information under FERPA because it could result in the disclosure of
  protected information to someone other than the student and thus would
  be "harmful or an invasion of privacy if disclosed." (Some
  institutions may continue to use a student's "official ID number" in
  this manner.) Under this reasoning, an institution that allows a
  student (or any other party, for that matter) to obtain access to
  education records by providing just publicly available information,
  such as a student's name or published email address, without any
  additional proof or authentication of identity, could have a policy or
  practice in violation of FERPA because it could lead to the disclosure
  of education records to unauthorized recipients.

However, if this isn't acceptable, consider an additional ID (shared secret) that is temporary.
You could use random tokens (prefixed with a peppered time and user ID to avoid having to check for collisions) that are temporarily assigned to users (most likely via some kind of lookup table) and cleared out in reasonable time intervals.
If you still don't want anything that's tied to the user, even temporarily, you won't be able to use hashes, because hashes aren't reversible. You'd be stuck testing the hash against each record, which would not be technically feasible.
Finally, you could use a hash + random token and user ID, similar to SSO, but encrypt the user ID using a secret key stored on the server in code or configuration. This way, an attacker would have to gain access to both the database and your code or configuration to make use of the data. Ideally, change the secret key daily.

A: Currently implemented solution
The login ID is currently being run through a series of algorithms to create a unique salt that can be regenerated based on the given raw login ID at run time, allowing for a repeatable lookup process. With the salt and a pepper, the login ID is bcrypt hashed.
Known issues
low entropy (relying only on the login ID's inherent entropy), and an algorithmic process to create the salt severely limits the strength of this crypto process: with knowledge of the process to create the salt and the value of the pepper, it would be possible to create a rainbow table for these hashes. Still, any standard pre-genned rainbow table would not work: it would have to be custom done for this set of hashes, and would require enough programming knowledge/a flexible enough generator to duplicate the salt creation process. The use of bcrypt and the custom salt routine hopefully makes the process more time consuming than the retrieval of the associated values would be worth.
Unfortunately this is essentially security through obscurity, by degrees. But it's the best I can come up with at the moment.
Further considerations
Per Marcus Adams' answer, one possibility that might improve security would be to store the hashed login IDs in a lookup table, and then only pass a completely random/unique GUID style token to the third party software for SSO purposes. This would eliminate the chance of an intercept of a hashed login ID in transmittal (relatively low to begin with, as every step of this is SSL encoded via https, and the hashed login ID is folded into an SSO payload encrypted via rijndael and a PSK before being sent). While this eliminates the chance of a third party compromise leading to potential breach of the login IDs, it only shifts that potential to our systems, which we can't assume are necessarily any more secure. Given that the current solution would require a compromise of the source code to find the pepper and the salt algorithm, and given that any such compromise would also be capable of revealing any DB keys, there seems to be no real added security to using a lookup table in terms of any potential full compromises.
Deeper analysis into exactly how at risk what I have implemented is to attack is beyond my own cryptographic knowledge or what I have the time to devote to at the moment.


text:
Q: Pull for new results inside jQuery's getJSON I'm working on adding a way to pull for results in my jQuery.JamCity.
Right now, it uses getJSON to pull api data from Last.Fm each $.each to parse through that data and output it.
I want to make it so that it checks for new results ever minute and IF there is a new item in data[0] to display it but ELSE, don't do anything because I don't want to just keep having the recent song pop-up.
How would I go about doing this? I imagine I use something like setInterval but I don't fully get how that works. Any code examples or ideas on how to achieve this functionality?

A: here is some starting code that would do this:
var lastSong = null;
var fetch = function(){
   $.getJSON('....', function(data) {
       if(data.length) {
           currentSong = data[0].some_unique_id
           if(lastSong != currentSong){
              //put code here to play song
              lastSong = currentSong;
           }
       }
       setTimeout(fetch, 1000 * 60);
   });
}
fetch();

A: setInterval takes a function and a timeout interval (x) in milliseconds as in input. Once set interval is specified, after x milliseconds the function will be called.
https://developer.mozilla.org/en/DOM/window.setInterval
That is indeed how you would want to code this functionality. Simply create a function that calls getJSON to get your data with an interval of 60000 (one minute).
After the call to getJSON returns, process the data accordingly to see if the results have changed from the last time the function was called.


text:
Q: Using Radio Buttons in Rails I have a Category model with two booleans, article_cat? and profile_cat?. I want to be able to create a new Category with a form that lists these two using radio buttons. If one radio button is marked, the other one is unmarked. It should send a true value to the create method of the one that is checked and create a new category where either article_cat or profile_cat is true. The Rails API for radio buttons does not make sense to me. Here is what I have, and it is breaking badly:
<%= f.radio_button "category", "article_cat", true %>Article
<%= f.radio_button "category", "profile_cat", true %>Profile
I honestly do not know what I am doing up there. I am just experimenting.

A: But you don't really need two fields for this you could just use one:
<%= f.radio_button :article_cat, true %><%= f.label :article_cat %>

<%= f.radio_button :article_cat, false %><%= f.label :article_cat %>

Then it's article_cat if article_cat is true, otherwise it's profile_cat. Also you might need to set the default value for your boolean in the migration:
add_column :categories, :article_cat, :boolean, :default => true

A: Use any string value like "true" and "false", not boolean values like true and false
Refer here for the explanation http://roninonrails.blogspot.com/2008/02/rails2-and-boolean-radio-buttons.html

A: I am going to add a comments_cat boolean later to categorize the comments. Is there anyway to make a choice of three radio buttons. The one selected sets the other values to false? Right now, the buttons are all automatically selected.


text:
Q: Displaying a localised version of iPhone Contact Picker (ABPeoplePickerNavigationController) In my app I use the ABPeoplePickerNavigationController to present an address book to the user so they can select a contact from their contacts.
I want my app to support multiple localizations (English, French) and I was expecting the ABPeoplePickerNavigationController to display the correct localised strings when I changed the phone's locale. However, this does not happen - no matter what language I change the iPhone to, the ABPeoplePickerNavigationController always displays English strings. This is strange as the Contacts application on the iPhone does change its text depending on the locale.
Does anyone know how to instruct the ABPeoplePickerNavigationController to display the correct text for the current locale?

A: Is your app already localized or are you just planning to add localization later? AFAIK, the built-in controls only display localized texts in those languages that your app supports.

A: fileName : InfoPlist.strings

view -> Utilities -> show file inspector
      -> Localization "+" button click >> add language


text:
Q: Criar uma estrutura a partir de um xml Estou usando o Framework SWXMLHash para ler o XML e preciso criar de alguma forma a seguinte estrutura a partir do XML
Estrututa a ser criada:
Catalogo
   Book1
    Autor = Gambardella
    Genre = Computer
   Book1
   Book2
    Autor = Ralls
    Genre = Fantasy
   Book2

XML que estou usando
<root>
      <catalog>
        <book id=\"bk101\">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications with XML.</description>
        </book>
        <book id=\"bk102\">
          <author>Ralls, Kim</author>
          <title>Midnight Rain</title>
          <genre>Fantasy</genre>
          <price>5.95</price>
          <publish_date>2000-12-16</publish_date>
          <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
      </catalog>
    </root>

Código em Swift
for retorno in dados["root"]["catalog"]["book"]{
 //
}

A: Aparentemente o Catalog é um array de books, correto? Se você já tem o XML como um dicionário e a classe Book criada, uma maneira de ler o dicionário seria a seguinte:
for rawBook in dados["root"]["catalog"] {
    guard let author = rawBook["author"] as? String,
          let genre = rawBook["genre"] as? String else {
              continue
          }
    let book = Book(autor: author, genre: genre)
    //...
}


text:
Q: How can i select max of rows without using groupby in SQL code? Please look at my question in this photo
I created an sql code but the problem is ;
Column A    Column B     CreationDate
1              50        2019-10-10 10:41
1              80        2019-10-10 10:43
1              70        2019-10-10 11:05
2              60        2019-10-10 10:40
2              58        2019-10-10 10:41
2              50        2019-10-10 10:44
2              47        2019-10-10 11:00

By sorting, at the end I wanna see the data related to the latest Creation Date like:
Column A    Column B     CreationDate
1              50        2019-10-10 11:05
2              47        2019-10-10 11:00

Therefore i need to do some iterations in CreationDate column but i dont know how to do it in sql.
I cannot use groupby because Column B prevents it to do. This column is a forecast column which is created at CreationDate. Therefore, I just want to get the latest forecast.

A: It seems like you want filtering.  I would write this as:
select t.*
from t
where t.creation_date = (select max(t2.creation_date)
                         from t t2
                         where t2.a = t.a
                        );

If you really want to avoid aggregation functions (although there is no need to), here are three other ways:
select t.*
from t
where t.creation_date = (select t2.creation_date
                         from t t2
                         where t2.a = t.a
                         order by t2.creation_date desc
                         limit 1
                        );

And:
select t.*
from t
where t.creation_date >= all (select t2.creation_date
                              from t t2
                              where t2.a = t.a
                             );

And:
select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.creation_date > t.creation_date and
                        t2.a = t.a
                 );

A: You should use the RANK() function, e.g.
 ;WITH result as
 ( SELECT ColumnA, ColumnB, CreationDate,
   RANK() OVER(PARTITION BY ColumnA ORDER BY CreationDate DESC) as Rank
   FROM TableName
 )
 SELECT * FROM result WHERE Rank=1

A: You can use NOT EXISTS to only get rows for which no later row entry exists:
select *
from mytable m
where not exists
(
  select *
  from mytable m2
  where m2.column_a = m.column_a
  and m2.creationdate > m.creationdate
)
order by column_a;

A: Please try this sql I wrote for you:
SELECT
    a.Column_A, a.Column_B, b.latest_date
FROM
    your_table a
INNER JOIN
    (SELECT
        Column_A, max(CreationDate) AS latest_date
    FROM
        your_table
    GROUP BY Column_A) b
ON a.Column_A = b.Column_A
WHERE a.Column_B = 50;

As your request changed, your expectation in your image was not the same as your description, if Column_B is fixed to 50, please try the sql above. if not, please try the sql below:
SELECT
    a.Column_A, a.Column_B, b.latest_date
FROM
    your_table a
INNER JOIN
    (SELECT
        Column_A, max(CreationDate) AS latest_date
    FROM
        your_table
    GROUP BY Column_A) b
ON a.Column_A = b.Column_A
AND a.CreationDate = b.latest_date


text:
Q: Error calling method on NPObject! in uploadify I am having Uploadify plugin for uploading files. It was working fine and suddenly it stopped working. I am not able to fix. It would be great if I get some help here
Mycode :
jQuery(".fileSelectBox  > input:checked").each(function(){

    if( !jQuery(this).parent().parent('div').hasClass('completed')){
             jQuery('#file').uploadifyUpload(jQuery(this).parent().parent('div').attr('id').replace('file',''));
    }
 });

Getting Error in the following line
document.getElementById(jQuery(this).attr('id') + 'Uploader').startFileUpload(ID, checkComplete);


text:
Q: Firebase, IN clause query and lists of datas In my opinion this is pretty obvious question when someone has to deal with a DB, so I don't know why I can't find anything about it.
I'm trying to design the non-relational database for my project. I have a list of products described by some info (e.g. the code, an image and a multi language description) and they are categorized in different ways. Here is a snap of the structure:
"products" : {
    "-JiGh_31GA20JabpZBfa" : {
      "code" : "IR3300000000",
      "schema" : "http://lorempixel.com/400/200/",
    },
    "-JiGh_31GA20JabpZBfb" : {
      "code" : "PJ0000000000",
      "schema" : "http://lorempixel.com/400/200/",
    }
  }

"it" : {
    "products" : {
      "-JiGh_31GA20JabpZBfa" : {
        "description" : "desc product IR330000000"
      },
      "-JiGh_31GA20JabpZBfb" : {
        "description" : "description product PJ00000 lorem ipsum"
      }
    }
  }

And below there are a couple of usages of the products, the real structure is much more complex, but probably it's enough to explain my problem:
"families" : {
    "family1" : {
        "products" : {
            "-JiGh_31GA20JabpZBfa" : true,
            "-JiGh_31GA20JabpZBfb" : true
        }
    },
    "family2" : {
        "products" : {
            "-JiGh_31GA20JabpZBfa" : true
        }
    }
}

"applications" : {
    "application_1" : {
        "products" : {
            "-JiGh_31GA20JabpZBfa" : true,
            "-JiGh_31GA20JabpZBfb" : true
        }
    },
    "application_1" : {
        "products" : {
            "-JiGh_31GA20JabpZBfa" : true,
        }
    }
}

Ok, now let's move to the client side!
I have a couple of tables, one that shows the families and one for the applications of the products. Selecting one of them I want to show all products that belong to the family or that are used in an application.
And here is what I'm struggling with: if I want to show the description and the code of each product in a cell, do I have to perform a query for every product to retrieve their fields or can I use some sort of "IN" query? Something like select * from products where key IN {"-JiGh_31GA20JabpZBfa", "-JiGh_31GA20JabpZBfa"}. I know that it's an SQL like query, but this was just to better explain myself.
Btw, I don't exclude that my way of designing the DB is wrong.

A: As indicated in the first comment by @Frank van Puffelen, there is no way to perform a IN query or, I suppose, something similar to a JOIN.
So here are a few pieces of my code and a brief of the pipeline that I have implemented!
I created 2 UITableViewController, the first one to show the families and the second one to show the products of the selected one.
So, in the first controller I wrote this code to retrieve the list of families:
let ref = FIRDatabase.database().reference()
ref.child("families").observeSingleEvent(of: .value, with: { snap in
    if snap.value is NSNull { return }
    let families = snap.value as! [String:AnyObject]
    for familyKey in families.keys {
        let familyDetails = familyes[familyKey] as! [String:AnyObject]
        self.families.append(FamilyL1.init(familyName: familyKey, familyDetails: familyDetails))
    }
    self.tableView.reloadData()
})

After the selection of a family, in the second controller I'll perform two queries: one to retrieve the details of the product and the other one for the multi-language description.
for (index, product) in (family?.products ?? []).enumerated() {
    self.ref.child("products").child(product.id).observeSingleEvent(of: .value, with: { snap in
        if snap.value is NSNull { return }
        product.populateProduct(product: snap.value as!  [String:AnyObject])
        self.tableView.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: .none)
    })
    self.ref.child("it").child("products").child(product.id).observeSingleEvent(of: .value, with: { snap in
        if snap.value is NSNull { return }
        product.populateProductDescription(product: snap.value as! [String:AnyObject])
        self.tableView.reloadRows(at: [IndexPath.init(row: index, section: 0)], with: .none)
    })
}

As suggested, I've taken advantage of the parallelism, so the queries aren't performed sequentially and the interested cells will be refreshed at each update. I've taken care of the optional values to achieve that:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let product = self.family?.products[indexPath.row]
    cell.textLabel?.text = product?.code ?? "..."
    cell.detailTextLabel?.text = product?.pDescription ?? "..."
    return cell
}

I hope this answer will help those who are trying to use this great platform!