text:
Q: Software Based RAID? Via OS or Controller? So, I just discovered that the RAID controller within my Dell Precision 470 is software based. I never recognized until now that Adaptec CERC stood for "Cost Effective Raid Controller"... amazing.
According to this lovely Dell datasheet, it appears that my controller is a "driver-based software raid", which consumes host CPU cycles to operate.
My question, are there advantages to utilizing this "driver-based software raid" over the OS raid available in Windows7/Server2008 for RAID 1 (or RAID 0)?
Under most circumstances, I prefer having RAID handled outside of the operating system. However, I've discovered on this machine how much of a pain that can become -- I cannot easily run tools such as disk check tools on each drive independently without first splitting the RAID (as the individual drives are hidden behind the RAID controller). That consumes my time (split RAID, verify which HD is dieing, rebuild RAID).
Suggestions?

A: Most people on here agree with you, as do I - software RAID us better than this crappy half RAID but really good hardware RAID is the best. I'd leave the one you have and use the Windows RAID myself.


text:
Q: MATLAB Average Every 5 Elements I want to take a large matrix and take the average of all 5x5 grids in it.
The matrix is 245x85x1255.I  reshaped the matrix into a 5x4165x1255 size (the z dimension is not that important) and I want to take the average of elements 1:5, 5:10, 10:15 etc in each row. And then, with the resulting matrix, I want to average the five columns. Then I'll resize it back to it's original shape (but smaller of course).
I don't have to do it this way. I just need to take a 5x5 grid and average all the points in it. Then I take the next 5x5 grid next to it and average all those points.
Here's how I did it for the first 5x5 grid:
A = data_SpecificArea(:,1:5,:);
B = mean(A,2);
C = mean(B,1);

** Here's the working code using blockproc
% Change dataAll_SpecificArea to a 1x1 degree grid (5x5 block averaging)
fun = @(block_struct) mean(block_struct.data);
A = blockproc(dataAll_SpecificArea,[5 1],fun); % Size goes from 245x85x1255 to 49x85x1255
B = blockproc(A,[1 5],fun); % Size is 49x17x1255

A: You can use blockproc for that. For example,
fun = @(block_struct) mean(block_struct.data);
new_matrix = blockproc(old_matrix,[5 5],fun);

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to read file using R in databricks I am trying to read a hash file from a blob storage whis is already having a mount point
i.e /mnt/home.
enter image description here
I can see that the files are located under the same mount point:
enter image description here
I am using R to read the file in databricks with the query as below
%r
install.packages("qs")
data <- qs::read("/mnt/home/country/002273b76c24cb37f3c3f1")
head(data)

however i am coming across the following error message:
Error in qs::qread("dbfs:/mnt/home/country/002273b76c24cb37f3c3f1") :
  Failed to open dbfs:/mnt/home/country/002273b76c24cb37f3c3f1. Check file path.
Some(<code style = 'font-size:10p'> Error in qs::qread("dbfs:/mnt/home/country/002273b76c24cb37f3c3f1;): Failed to open dbfs:/mnt/home/country/002273b76c24cb37f3c3f1. Check file path. </code>)
Error in qs::qread("dbfs:/mnt/home/country/002273b76c24cb37f3c3f1"): Failed to open dbfs:/mnt/home/country/002273b76c24cb37f3c3f1. Check file path.

can i get some advice in fixing the issue

A: you need to append /dbfs to use local file API - see docs:
data <- qs::qread("/dbfs/mnt/home/country/002273b76c24cb37f3c3f1")

But it may not work with mounts (depends on the mount type) - in this case you will need to copy file from mount to local disk by using dbutils:
dbutils.fs.cp("/mnt/home/country/002273b76c24cb37f3c3f1", "file:/tmp/my_file")
data <- qs::qread("/tmp/my_file")


text:
Q: Number of triangles in the figure How many triangles are in the figure show here:

I tried using casework, but it got really messy really fast. I also think that you could easily miscount and get something wrong.

A: There are 36 triangles in that square.


text:
Q: Python - How to transform a list of tuple to a tuple I retrieved data from a sql query and
I have a list of tuple like:
[(34.2424,), (-64.2344,) (76.3534,), (45.2344,)]

And I would like to have a string like (34.2424, -64.2344, 76.3534, 45.2344,)
Does a function exist that can do that?
Notice the ',' at the end of each tuple... I have difficulty to get rid of it

A: If you're using Python 2.x, then you can use:
>>> a = [(34.2424, -64.2344, 76.3534, 45.2344)]
>>> print ' '.join(map(str, a[0]))
'34.2424 -64.2344 76.3534 45.2344'

In Python 3.x, or Python 2.x with a from __future__ import print_function, you can use:
>>> print(*a[0])
34.2424 -64.2344 76.3534 45.2344

You seem to have updated the format of the input data, so:
First element from each tuple...
>>> a = [(34.2424,), (-64.2344,), (76.3534,), (45.2344,)]
>>> print ' '.join(str(el[0]) for el in a)
34.2424 -64.2344 76.3534 45.2344

More than one element in each tuple...
>>> from itertools import chain
>>> print(*chain.from_iterable(a))
34.2424 -64.2344 76.3534 45.2344

However, it does seem you just want a tuple...
>>> tuple(chain.from_iterable(a))
(34.2424, -64.2344, 76.3534, 45.2344)

Which you can then just use str on to make it a str if you so wanted...

A: str.join() only works on strings, so you have to cast them to strings first. I could write that out, but I just read something in the Python Cookbook (my new favorite book) about this, so I'll link to that instead.  Beazley and Jones write that for printing a tuple like this, instead of turning each one into a string, you can simply do:
tup = (34.2424, -64.2344, 76.3534, 45.2344)
print(*tup)

As your tuple is nested inside a list, you can either iterate through the list and print thusly, or you can flatten the list before working with it (and there are a lots of answers on SO, and a nice one in the Python Cookbook, on flattening nested sequences).
Edit: I noticed the title changed to a request to flatten the list of tuples to a tuple, which is a flattening nested sequences request.
I'll link to the Python Cookbook recipe I noted above called "flattening a nested sequence" and also state again that there are lots of answers on this here at SO: "Flattening a Nested Sequence"

A: Sorry I misread your question, but didn't vote down.
>>> data = [(34.2424,), (-64.2344,), (76.3534,), (45.2344,)]
>>> data_str = '(' + ', '.join(map(lambda x: str(x[0]), a)) + ')'
>>> print data_str
(34.2424, -64.2344, 76.3534, 45.2344)
>>>

or just flatten the list and use str to get the resulting tuple as a string.
>>> data_str = str(sum(data, ()))

A: " ".join(tuple)

Will do the job, assuming you would like space separators.

A: The join function of strings will do it.
print " ".join(arrayOfValuesYouWantToJoinTogether)


text:
Q: NSPredicate truncating string I am trying to create NSPredicate, but it's truncating my string.
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"columnId == 1406093563.91876412345"];

But when I print predicate it gives me:
columnId == 1406093563.918764

predicate always keeps max 6 digits after decimal point. It's happening with numeric digits only.

A: This number is being rounded. If you need to use it as an exact string, you should put it in quotes (').


text:
Q: asp.net mvc 2 UIHint with multiple defonitions im using data annotation with buddy classes for error etc
however i have a field for photo on the view it should be an image
but on the edit and add it should be a file upload ???
but UIHint will only let me have one, so how do you have multiple UI
for one type in your class?
thanks

A: You should only need to specify one UIHint. Within the Views\ControllerName folder or Views\Shared you have two additional sub folders DisplayTemplates and EditorTemplates. So when you call:
<%=Html.DisplayFor(x => x.Name) %>

This will look in your DisplayTemplates folder for a control with the UIHint name which in your case will be an images, and when you call:
<%=Html.EditorFor(x => x.Name) %>

This will look in your EditorTemplates folder for a control with the UIHint name which will be a file uploader.
Here's an basic editor example that should help you: example.


text:
Q: Multiple tree list and save in a pandas DataFrame i have 3 list, such as below:
 list1 = [1,2]
 list2 = [x,y]
 list3 = [i,j,l]

how can i multiple them and save into a pandas dataframe, as following dataframe:
  list1  list2  list3
  1      x      i
  1      x      j
  1      x      l
  1      y      i
  1      y      j
  1      y      l
  2      x      i
  2      x      j
  2      x      l
  2      y      i
  2      y      j
  2      y      l

i couldn't find any similar question on Stackoverflow.

A: You can use:
import itertools
df_new=pd.DataFrame(list(itertools.product(list1,list2,list3)),\
                               columns=['list1','list2','list3'])
print(df_new)

    list1 list2 list3
0       1     x     i
1       1     x     j
2       1     x     l
3       1     y     i
4       1     y     j
5       1     y     l
6       2     x     i
7       2     x     j
8       2     x     l
9       2     y     i
10      2     y     j
11      2     y     l

A: Hack from pandas
pd.MultiIndex.from_product([list1,list2,list3],names=['list1','list2','list3']).to_frame().reset_index(drop=True)
Out[196]:
    list1 list2 list3
0       1     x     i
1       1     x     j
2       1     x     l
3       1     y     i
4       1     y     j
5       1     y     l
6       2     x     i
7       2     x     j
8       2     x     l
9       2     y     i
10      2     y     j
11      2     y     l


text:
Q: Heroku - how to update price list which has size 38MB? My client has an e-commerce system with products (there is ~60k product items). The price list is placed on the URL address in ZIP format.
I need firstly download the price list, unzip that, then open the CSV file and start read line by line. In his database is updated price from the CSV (if is product's price different in the CSV than in his database, use the price from CSV and update database).
But, is possible to do this on Heroku? The download of almost 40MB file take some time, import data from CSV to database (the import on localhost takes about 17 minutes - but this is import of whole CSV to database) as well.
How would you solve this situation? What options do I have?
Unfortunately, there is no way to change the CSV file, so I have to work with that file...
Thanks

A: There's a common misconception about the file system on heroku. It's not that it's read-only, it's that it's ephemeral. You can start a process and start writing to the filesystem, but as soon as that process exits, the data is gone forever.
So, you can indeed download a zip file and then process it, but even if you run into an error while processing, causing your program to exit, the unzipped data will be lost. You might want to think about unzipping it, creating chunks of data that you put on S3, and then having any number of workers crunching that data and internalizing it with your own database.

A: This is possible by running the work on a delayed job on a worker process. For more information see: https://devcenter.heroku.com/articles/ps. Note that if this is a regular task you want to run on a scheduled time interval you can also use Scheduler (https://devcenter.heroku.com/articles/scheduler).


text:
Q: How to override two methods of 2 parents that inherits same classes with virtual methods in C++ Consider the next Example:
#include <iostream>

class Base{
    public:
    virtual void f() {
        std::cout << "Base::f()" << std::endl;
    }
};

class Derived1 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived1::f()" << std::endl;
    }
};

class Derived2 : public Base
{
    public:
    virtual void f() override
    {
        Base::f();
        std::cout << "Derived2::f()" << std::endl;
    }
};

class DerivedUnion : public Derived1, public Derived2
{
    public:
    void Derived1::f() override { // Errors

    }

    void Derived2::f() override { // Errors

    }

};

is there some how that allow me to override the
Derived2::f()
in the
DerivedUnion{}
class?
I have tried to target specific one with namespace like style, but it didnt worked:
class DerivedUnion : public Derived1, public Derived2
   // Notice DerivedUnion is not a Union, name is for
   // Demostration Purposes, not intended to create
   // A union Behavior
{
    public:
    virtual void Derived1::f() override; // Compile error
    virtual void Derived2::f() override; // Compile error
    virtual void f() override; // Not a compile error, but both Derived1 and Derived2 call same
};

void UseBase(Base* b){
       b->f(); // expected Ambiguos call compile time
       b->DerivedUnion::f() // Expected overriden DerivedUnion::f() to be called
       b->Derived1::f(); // Expected overriden Derived1::f() to be called
       b->Derived2::f(); // Expected overriden Derived2::f() to be called
}

An Example of it could be this one, code is self explanatory:
#include <iostream>

/* Interface Drawable */
class IDrawable {
    public:

    virtual void Draw() {};
};

/* Asume this is a button from one kind of bar */
class ButtonA : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonA::Draw()" << std::endl;
    }
};

/* Asume this is a button from another kind of bar */
class ButtonB : public IDrawable{
    public:
    virtual void Draw() override {
        std::cout << "ButtonB::Draw()" << std::endl;
    }
};

/**
Where Component X is a representation that will represent 2 buttons types
*/
class ComponentX : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function 'ButtonA::Draw' within 'ComponentX'
        ButtonA::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function 'ButtonB::Draw' within 'ComponentX'
        ButtonB::Draw();
        std::cout << "Custom ComponentX::Draw()" << std::endl;
    }
};

class ComponentY : public ButtonA, public ButtonB {
    public:
    void ButtonA::Draw() override { // cannot define member function 'ButtonA::Draw' within 'ComponentY'
        ButtonA::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }

    void ButtonB::Draw() override { // error: cannot define member function 'ButtonB::Draw' within 'ComponentY'
        ButtonB::Draw();
        std::cout << "Custom ComponentY::Draw()" << std::endl;
    }
};

using namespace std;

void DummyAddButtonA(ButtonA* pBtnA)
{
    //Add it somewhere ...
}

void DummyAddButtonB(ButtonB* pBtnB)
{
    //Add it somewhere ...
}

int main()
{
    ComponentX compx;
    ComponentY compy;

    DummyAddButtonA(&compx);
    DummyAddButtonB(&compx);

    DummyAddButtonA(&compy);
    DummyAddButtonB(&compy);

    return 0;
}


text:
Q: SQL Server Management Objects for Windows Phone 8 Can I use SQL Server Management Objects in Windows Phone 8 app to manage SQL Server ?

A: SQL Server Management Objects resides in the Microsoft.SqlServer.Management.Smo Namespace, which is not present in the .NET API for Windows Phone.  There might be a way to get it on there, but I doubt it.


text:
Q: Conditional distribution and correlation in multivariate normal distribution. Consider the random vector $(X_1, X_2, X_3)^T \sim \mathcal{N}_3 (\underline{\mu}, C)$, where $\underline{\mu}=(\mu_1, \mu_2, \mu_3)^T$ and
$$C=\begin{bmatrix}
    1 & \rho & \rho^2 \\
    \rho & 1\ & 0\\
    \rho^2 & 0 & 1
\end{bmatrix}$$
$(0 < \rho < 1)$ is a given parameter. Determine the conditional distribution of $(X_1, X_2)^T$ conditioned on $X_3=x_3$.
Now suppose, that $\mu_1=\mu_2=\mu_3=0$, so $(X_1, X_2, X_3)^T \sim \mathcal{N}_3 (\underline{0}, C)$ and $C$ remains the same.
Find the multiple correlation between $(X_1, X_2)^T$ and $X_3$.
Find the partial correlation between $X_1$ and $X_2$, after eliminating the effect of $X_3$.
I am familiar with the definition of conditional distribution and correlation, but I haven't really solved any exercises in multivariate cases. Anything which can help me to get started is appreciated.


text:
Q: Pre store big amount of data in app I have a big amount of data (more then 100 entries) to show on a table view. The data will be static, so i was thinking in store it on a plist file. The problem is when it is shown in table view, the user will be able to select or deselect a row and this information must be stored.
In other words the app will have a list of things and the user can select the things he own.
What's the best way to store the data in the app and the selected information?
PS.: I was avoiding Core Data, but if this is the best way how can i pre store the data in an entity?

A: 100 entres isn't actually a large amount of data.
I would be inclined to use a plist for this small amount of data.
If you wanted, you could keep the user-data in the same plist too:
When app first runs it could copy the plist to the document directory so that it can be edited (the ownership data written).
Or, you could use a separate plist for the user-data.

A: There is no "best way", but one viable approach is to use a JSON file. If the data isn't too large, say the JSON file is much less than 1 MByte.
Creating and modifying a JSON file is quite comfortable in an editor. You can parse and create a representation as usual with NSJSONSerialization.
Hint: A JSON file which has N number of bytes, creates a representation of Foundation objects which roughly need a total of 5*N to 10*N allocated space.

A: The easiest way to track the selected and unselected row is here:
this code will save value with your tap on the cell.
   - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BOOL isSelected=[[NSUserDefaults standardUserDefaults] boolForKey:[indexPath.row stringValue]];
    [[NSUserDefaults standardUserDefaults] setBool:!isSelected forKey:[indexPath.row stringValue]];

}


text:
Q: How to prevent columns from not displaying in WPF datagrids when using '/' in the header? I have a WPF Datagrid in my application where I set the value of the ItemSource to the DefaultView of a DataTable that I have constructed.  The problem lies in the fact that whenever I set the ColumnName of one of the columns in my DataTable to a string that includes '/' the header shows up in the DataGrid control but the values do not.  How can I get around this?

This is the same table with the '/' replaced with '-'

as an aside this also appears to happen with headers that have a '.' in them.  So any decimal will cause the same behavior.
My grid is defined as
<DataGrid x:Name="dgLFKPI" />

and I am setting the value in code behind (yes it should be in a viewmodel and MVVM but it is a legacy app that is slowly moving that way).
dgLFKPI.ItemsSource = dt.DefaultView;

A: The special characters in the column names are incorrectly parsed by the binding path parser.
So a column binding to 3/4 is actually only binding to the property 3, and not the property 3/4. (The same thing with the . binding)
You'll probably see binding errors in the debug window while this is running that should say the same sort of thing.

System.Windows.Data Error: 40 : BindingExpression path error:
  '3' property not found on 'object' ''DataRowView'

According to this answer

There are a number of different characters which have special meaning
  in a binding path including full stop ('.'), slash ('/'), square
  brackets ('[',']') and parenthesis ('(',')'), the parenthesis will
  cause your app to crash. These special characters can be escaped by
  surrounding the binding path with square brackets. More information
  about paths and character escaping can be found in the [Binding
  Declarations Overview][2]

That linked question also contains a good solution for dealing with grids that want to use auto-generated columns.
Use the AutoGeneratingColumn event, and manually create the bindings for columns with these special characters in their name to escape them using the square brackets.
<DataGrid x:Name="dgLFKPI"
          AutoGeneratingColumn="dgLFKPI_AutoGeneratingColumn" />

private void dgLFKPI_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    if (e.PropertyName.Contains('/') && e.Column is DataGridBoundColumn)
    {
        var col = e.Column as DataGridBoundColumn;
        col.Binding = new Binding(string.Format("[{0}]", e.PropertyName));
    }
}

A: You need to set the columns specifically, then set the Header value of the column to your fraction value.
<DataGrid x:Name="dgLFKPI">
   <dg:DataGridTextColumn Header="0" Width="50" Binding="{Binding <columnname>}"  />
   <dg:DataGridTextColumn Header="1/4" Width="50" Binding="{Binding <columnname>}"  />
    ...
</DataGrid>

Alternatively, you could build it up in the codebehind:
var col = new DataGridTextColumn{
              Header = "1/4";
              Binding = new Binding("<columnname>")};
dataGrid1.Columns.Add(col);


text:
Q: Flink - unable to recover after yarn node termination We are running flink on yarn. We were performing Disaster recovery Testing and as part of that, we manually terminated one of the nodes that had a flink application running. Once the instance was brought back up, the application went in for multiple attempts and each attempt had the following error :
AM Container for appattempt_1602902099413_0006_000027 exited with exitCode: -1000
Failing this attempt.Diagnostics: Could not obtain block: BP-986419965-xx.xx.xx.xx-1602902058651:blk_1073743332_2508
file=/user/hadoop/.flink/application_1602902099413_0006/application_1602902099413_0006-flink-conf.yaml1528536851005494481.tmp
org.apache.hadoop.hdfs.BlockMissingException:
 Could not obtain block: BP-986419965-10.61.71.85-1602902058651:blk_1073743332_2508 file=/user/hadoop/.flink/application_1602902099413_0006/application_1602902099413_0006-flink-conf.yaml1528536851005494481.tmp
 at org.apache.hadoop.hdfs.DFSInputStream.refetchLocations(DFSInputStream.java:1053)at
 org.apache.hadoop.hdfs.DFSInputStream.chooseDataNode(DFSInputStream.java:1036)at
 org.apache.hadoop.hdfs.DFSInputStream.chooseDataNode(DFSInputStream.java:1015)at
 org.apache.hadoop.hdfs.DFSInputStream.blockSeekTo(DFSInputStream.java:647)at
 org.apache.hadoop.hdfs.DFSInputStream.readWithStrategy(DFSInputStream.java:926)at
 org.apache.hadoop.hdfs.DFSInputStream.read(DFSInputStream.java:982)at
 java.io.DataInputStream.read(DataInputStream.java:100)at
 org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:90)at
 org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:64)at
 org.apache.hadoop.io.IOUtils.copyBytes(IOUtils.java:125)at
 org.apache.hadoop.fs.FileUtil.copy(FileUtil.java:369)at
 org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:267)at
 org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:63)at
 org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:361)at
 org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359)at
 java.security.AccessController.doPrivileged(Native Method)at
 javax.security.auth.Subject.doAs(Subject.java:422)at
 org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1844)at
 org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:359)at
 org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:62)at
 java.util.concurrent.FutureTask.run(FutureTask.java:266)at
 java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)at
 java.util.concurrent.FutureTask.run(FutureTask.java:266)at
 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)at
 java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)at
 java.lang.Thread.run(Thread.java:748)For
 more detailed output, check the application tracking page: http://<>.compute.internal:8088/cluster/app/application_1602902099413_0006 Then click on links to logs of each attempt.

Could someone let us know what content is being stored in HDFS and if this could be redirected to S3?
Adding checkpoint related settings :
StateBackend rocksDbStateBackend = new RocksDBStateBackend("s3://Path", true);
streamExecutionEnvironment.setStateBackend(rocksDbStateBackend)
streamExecutionEnvironment.enableCheckpointing(10000);
streamExecutionEnvironment.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
streamExecutionEnvironment.getCheckpointConfig().setMinPauseBetweenCheckpoints(5000);
streamExecutionEnvironment.getCheckpointConfig().setCheckpointTimeout(60000);
streamExecutionEnvironment.getCheckpointConfig().setMaxConcurrentCheckpoints(60000);
streamExecutionEnvironment.getCheckpointConfig().enableExternalizedCheckpoints(ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
streamExecutionEnvironment.getCheckpointConfig().setPreferCheckpointForRecovery(true);

A: I had the same issue,
I fixed with setting for hdfs-site
{
    "Classification": "hdfs-site",
    "Properties": {
        "dfs.client.use.datanode.hostname": "true",
        "dfs.replication": "2",
        "dfs.namenode.replication.min": "2",
        "dfs.namenode.maintenance.replication.min": "2"
    }
}

I think hdfs lost data on node terminated, so i replication data on multi node.


text:
Q: search a word not containing something in "vi" I want to search words as following in "vi":
"AA" not followed by "BB" or "CC"

i.e.
AAXC... -- OK
AABB... -- NOT OK
AACC... -- NOT OK

Not sure how to do that.

A: vim supports regex searching and substituting http://vimregex.com/:
That is the desired regex:
AA((?!B{2})|(?!C{2}))

The above regex can be validate here.

In vim:
/^\(AA\)\(BB\)\@!.*$

will find all the AA.. format strings and will skip AABB strings.

*

*in order to skip AACC and AABB you can use:
/^\(AA\)\(\(BB\)\|\(CC\)\)\@!.*$

or equivalently:
/^\(AA\)\(\(B\{2\}\)\|\(C\{2\}\)\)\@!.*$

*eliminate the ^ from the strings if you want to find strings like
AAXC inside string of the form BAAXC.

A: You can search using regular expressions, just use A[^BC], if it's actually that simple (just characters, not words).


text:
Q: Stack around the variable was corrupted I am having a problem with gets.
The purpose is to get input from the user until he hits the 'Enter'.
This is the code:
struct LinkedListNode* executeSection2()
{
    char inputArr [3] = {'\0'};
    struct LinkedListNode* newNode;
    struct  LinkedListNode* head = NULL;

    gets (inputArr);

    while (inputArr[0] != 0) // The user didn't press "Enter"
    {
        newNode=newLinkedListNode();
        newNode->tree=newHuffmanNode(inputArr[0],atoi(inputArr+2));

        head = addNode(&head, newNode);

        gets (inputArr);
    }

    head = buildHuffmanTree(&head);
    return head;
}

It seems OK, the user hits the 'Enter', the code go out from the while, but after the return, I get the error message:

Stack around the variable 'inputArr' was corrupted

I guess I dont read the input from the keyboard properly.
I will be happy for some guidness.
Thanks.

A: This error is a perfect illustration to the reason why gets has been deprecated: it is prone to buffer overruns, which corrupt stack or whatever memory happens to be near the end of your buffer. When the user enters more than two characters, the first three get placed into the buffer, and the rest go into whatever happens to be in the memory after it, causing undefined behavior.
You need to replace the call of gets with a call of fgets, which accepts the size of the buffer, end prevents user input from overrunning it:
fgets (inputArr, 3, stdin);

on every while iteration, the user hit enter and at the end, when he wants to stop, he hits only enter.

fgets considers '\n' part of the string, so when the user hits enter the only character in the returned string will be '\n':
while (inputArr[0] != '\n') { // The user didn't press "Enter"
    ...
}

A: The gets function in C is a classic buffer overflow function.  gets is one of the functions which gives C a bad name for security.  You are experiencing a buffer overflow.  As long as you never intend to distribute this code, I won't object.  However, you should never use gets for anything more than a toy program.  The man page says as much, and informs you that no check for buffer overrun is performed.  On my Mac, the man page say:

It is the caller's responsibility to ensure that the input line, if any, is sufficiently short to fit in the string.

As to why this happens, it happens because the user is inputting more data than your program can handle.  Your program can handle two characters.  It doesn't look like the newline character(s) should be counted.  In a properly coded application, it should be impossible for user input to corrupt memory in this way.


text:
Q: Jquery: Getting certain url path using window.location Our url pathname is
www.nicadpower.com/index.com

but we only want to get the pathname after www.nicadpower.com which is
index.com

how can we get index.com using window.location and jquery

A: I think you want
window.location.pathname

This would give you /index.com
To get rid of the leading /, you could simply use substring:
window.location.pathname.substring(1);

A: Here is another trick that you can use.
You can split the pathname parts using split method, like that:
If you have the url: www.nicadpower.com/posts/2012
Using: window.location.pathname.split('/')
You'll Give: ["", "posts", "2012"]


text:
Q: if i create my database with sql server 2008 r2 management studio I Create my database with sql server 2008 R2 .
now when setup this software in other computers must install sql server 2008 R2 management studio ?
not exist other way ?
and how i set SqlConnection that run at other systems.
(i connect to database with data connection in visual studio)
thanks.

A: Exist other way.  I mean, there are other ways.  Nearly any software that can connect to a database created in SQL Server 7, 2000, 2005 or 2008 is capable of connecting to a database created in SQL Server 2008 R2.
SQL Server Management Studio is used when a human user wants to connect to the database, but not when software connects to it.


text:
Q: Sqoop2: Compile fails: missing org.apache.sqoop:sqoop-core:test-jar:tests:2.0.0-SNAPSHOT When compiling latest Sqoop2 I get an error resulting from missing dependency:
org.apache.sqoop:sqoop-core:test-jar:tests:2.0.0-SNAPSHOT
How to install this jar?
I am runing:
Apache Maven 3.2.1
Java version: 1.7.0_51
CentOS 6.5, kernel 2.6.32-431.5.1.el6.x86_64
$ mvn compile -Dhadoop.profile=200

[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for org.apache.sqoop:sqoop-common:jar:2.0.0-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.codehaus.mojo:build-helper-maven-plugin is missing. @ line 73, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] Sqoop
[INFO] Sqoop Common
[INFO] Sqoop SPI
[INFO] Sqoop Core
[INFO] Sqoop Repository
[INFO] Sqoop Derby Repository
[INFO] Sqoop Tools
[INFO] Sqoop Execution Engines
[INFO] Sqoop Mapreduce Execution Engine
[INFO] Sqoop Submission Engines
[INFO] Sqoop Mapreduce Submission Engine
[INFO] Sqoop Connectors
[INFO] Sqoop Connector SDK
[INFO] Sqoop Generic JDBC Connector
[INFO] Sqoop Server
[INFO] Sqoop Client
[INFO] Sqoop Shell
[INFO] Sqoop Documentation
[INFO] Sqoop Tomcat additions
[INFO] Sqoop Distribution
[INFO] Sqoop Integration Tests
[INFO]
[INFO] Using the builder org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder with a thread count of 1
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ sqoop ---
[INFO] Setting property: classpath.resource.loader.class => 'org.codehaus.plexus.velocity.ContextClassLoaderResourceLoader'.
[INFO] Setting property: velocimacro.messages.on => 'false'.
[INFO] Setting property: resource.loader => 'classpath'.
[INFO] Setting property: resource.manager.logwhenfound => 'false'.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop Common 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-antrun-plugin:1.6:run (save-version) @ sqoop-common ---
[INFO] Executing tasks

main:
[INFO] Executed tasks
[INFO]
[INFO] --- build-helper-maven-plugin:1.8:add-source (add-source) @ sqoop-common ---
[INFO] Source directory: /home/dk/wks/sqoop2/common/target/generated-sources/java added.
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ sqoop-common ---
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ sqoop-common ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/dk/wks/sqoop2/common/src/main/resources
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ sqoop-common ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop SPI 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ sqoop-spi ---
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ sqoop-spi ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /home/dk/wks/sqoop2/spi/src/main/resources
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ sqoop-spi ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop Core 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ sqoop-core ---
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ sqoop-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ sqoop-core ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop Repository 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ repository ---
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Sqoop Derby Repository 2.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-remote-resources-plugin:1.1:process (default) @ sqoop-repository-derby ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Sqoop ............................................. SUCCESS [  1.220 s]
[INFO] Sqoop Common ...................................... SUCCESS [  2.352 s]
[INFO] Sqoop SPI ......................................... SUCCESS [  0.106 s]
[INFO] Sqoop Core ........................................ SUCCESS [  0.365 s]
[INFO] Sqoop Repository .................................. SUCCESS [  0.073 s]
[INFO] Sqoop Derby Repository ............................ FAILURE [  0.257 s]
[INFO] Sqoop Tools ....................................... SKIPPED
[INFO] Sqoop Execution Engines ........................... SKIPPED
[INFO] Sqoop Mapreduce Execution Engine .................. SKIPPED
[INFO] Sqoop Submission Engines .......................... SKIPPED
[INFO] Sqoop Mapreduce Submission Engine ................. SKIPPED
[INFO] Sqoop Connectors .................................. SKIPPED
[INFO] Sqoop Connector SDK ............................... SKIPPED
[INFO] Sqoop Generic JDBC Connector ...................... SKIPPED
[INFO] Sqoop Server ...................................... SKIPPED
[INFO] Sqoop Client ...................................... SKIPPED
[INFO] Sqoop Shell ....................................... SKIPPED
[INFO] Sqoop Documentation ............................... SKIPPED
[INFO] Sqoop Tomcat additions ............................ SKIPPED
[INFO] Sqoop Distribution ................................ SKIPPED
[INFO] Sqoop Integration Tests ........................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.639 s
[INFO] Finished at: 2014-02-25T18:08:27+04:00
[INFO] Final Memory: 17M/119M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-remote-resources-plugin:1.1:process (default) on project sqoop-repository-derby: Failed to resolve dependencies for one or more projects in the reactor. Reason: Missing:
[ERROR] ----------
[ERROR] 1) org.apache.sqoop:sqoop-core:test-jar:tests:2.0.0-SNAPSHOT
[ERROR]
[ERROR] Try downloading the file manually from the project website.
[ERROR]
[ERROR] Then, install it using the command:
[ERROR] mvn install:install-file -DgroupId=org.apache.sqoop -DartifactId=sqoop-core -Dversion=2.0.0-SNAPSHOT -Dclassifier=tests -Dpackaging=test-jar -Dfile=/path/to/file
[ERROR]
[ERROR] Alternatively, if you host your own repository you can deploy the file there:
[ERROR] mvn deploy:deploy-file -DgroupId=org.apache.sqoop -DartifactId=sqoop-core -Dversion=2.0.0-SNAPSHOT -Dclassifier=tests -Dpackaging=test-jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
[ERROR]
[ERROR] Path to dependency:
[ERROR] 1) org.apache.sqoop.repository:sqoop-repository-derby:jar:2.0.0-SNAPSHOT
[ERROR] 2) org.apache.sqoop:sqoop-core:test-jar:tests:2.0.0-SNAPSHOT
[ERROR]
[ERROR] ----------
[ERROR] 1 required artifact is missing.
[ERROR]
[ERROR] for artifact:
[ERROR] org.apache.sqoop.repository:sqoop-repository-derby:jar:2.0.0-SNAPSHOT
[ERROR]
[ERROR] from the specified remote repositories:
[ERROR] apache.snapshots (http://repository.apache.org/snapshots, releases=false, snapshots=true),
[ERROR] central (http://repo.maven.apache.org/maven2, releases=true, snapshots=false)
[ERROR] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <goals> -rf :sqoop-repository-derby

A: This issue has been discussed in the Sqoop mailing list and should be fixed in the future. You can workaround it now by calling "mvn install" instead of "mvn compile".

A: you can directly do following to build sqoop2
mvn package -Pbinary -Dmaven.test.skip=true


text:
Q: explode string into variables Is there a way to explode a string into variables e.g
some_function($min, $max, "3, 20");

such that $min is assigned the value 3 and $max is assigned the value 20.
I know I can simply use
$data = explode("3, 20");

just wondering if there is another way.

A: Since PHP 7.1 there is a new feature called

Symmetric array destructuring: The shorthand array syntax ([]) may now
  be used to destructure arrays for assignments (including within
  foreach), as an alternative to the existing list() syntax, which is
  still supported.

That means that you can do now:
[$one, $two] = explode(";", "one;two");
echo $one; // one
echo $two; // two

As an alternative to list(), I find it myself a very elegant and readable solution that arrived with 7.1+ ... it is the same, but better.
Note: As the quote indicates, you can use the shorthand array syntax ([]) to assign variables in foreach declarations, but that's not related to the question, so check it out!
Documentation: https://www.php.net/manual/en/migration71.new-features.php

A: PHP's language construct list() can perform multiple assignments to variables (or even other array keys) by assigning an array.
list($min, $max) = explode(",", "3,20");

However, you would still need to apply a trim() to your variables since the $max value would have a leading space, or replace explode() with preg_split('/\s*,\s*/', $string) to split it on commas and surrounding whitespace.
Note: Use caution with list() to be sure that the array you're assigning contains the same number of elements as list() has variables.
In PHP 5.x, when assigning a value directly to another array, as an element of that array, list() values are assigned from right to left in PHP 5.x, not left to right. In other words, you'll end up with array that is populated backwards (last value, first).
https://www.php.net/manual/en/migration70.incompatible.php
In PHP 7.x list() arguments are assigned from left to right, when assigning elements directly to an array. In other words, you'll end up with the first value as the first element in the recipient array.

<?php
    list($a[], $a[], $a[]) = [1, 2, 3];
    var_dump($a);
?>

PHP Manual
PHP 5.X Last value gets the first element position, but the recipient must an array (in this case $a, is the array)!
array(3) {
  [0]=>
  int(3)
  [1]=>
  int(2)
  [2]=>
  int(1)
}

PHP 7.x First value becomes the first array element.
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

PHP Manual


text:
Q: Empty snippet when using "sulu_snippet_load_by_area" The snippet return "null" when I try to get it in my varaible.
 {% set snippets = sulu_snippet_load_by_area('banner') %}
 {{ dump(snippets) }}

and
<key>banner</key>

<meta>
    <title lang="en">Banner</title>
    <title lang="fr">Bannière</title>
</meta>

<areas>
    <area key="banner">
        <meta>
            <title lang="fr">Banniere</title>
            <title lang="en">Banner</title>
        </meta>
    </area>
</areas>

<properties>
    ....

I try to use the sulu_snippet_load_default instead but it returns me an empty array. If I try to dump the content.snippet I manage to get my values.
enter image description here
Thank you

A: The snippet will only be returned when you are creating first a snippet of that type. going to your Webspace click on Default Snippets Tab and select the snippet you did create before.
Keep in mind the sulu_snippet_load_by_area will return you the single snippet you did select there. So not an array of snippets.


text:
Q: How do i know what resistor value, that's attached to a BLDC motor, i should use in order to get a torque of 100 lb-ft put on my actuator? Motor P/N is M-3441Y-LN-02D.
Back EMF [Ke] is 38.95 (Vpeak/Krpm).
Continuous torque 2.495 lb-ft.
User manual.
I want to run the actuator coupled with the BLDC motor 60:1 gear ratio in reverse.
So the actuator will run at 50 RPM and the BLDC motor will run at 3000 RPM. I will rectify the 3 phases of the BLDC motor into DC voltage, then add the resistor. Would the torque constant (Nm/A) equal my back EMF constant of 38.95 (Vpeak/Krpm)?
If so, would i convert the rpm into radian/second?
It just seems that the more resistance I add to the rectified BLDC motor, the more torque should be applied to the actuator?
Thanks all.

A: It seems like you're trying to use a BLDC motor as a passive, constant toque load by shorting the leads together.
This is not possible. When shorting the leads of a BLDC motor it behaves variable torque load. The following equations relate motor speed and torque to voltage and current: $$ V = K_e\dot{\theta} $$ $$\tau = K_{\tau}I $$
Substuting, the equation to determine the motor torque when driven as a generator with the leads shorted together is as follows:
$$    \tau = K_{\tau}\frac{K_e \dot{\theta}}{R}$$
As you can see, the motor load torque is directly proportional to the rotor velocity. Assuming your actuator could maintain a controlled 3000rpm, the motor in theory would only produce ~48ft-lb of torque maximum (with the leads all shorted together). Of course, according to the datasheet, the motor is only rated for 10A of current, which means that the motor would be slag long before it got there.
As a side note, 100lb-ft is quite a bit of torque. This motor when driven actively is only rated to produce ~2.4ft-lb. I'm wondering if maybe you made a mistake with your units somewhere.

A: Your motor rated for 479 oz-in = 2.59 lb-ft @ 10 Arms  (current limit)
Thus 100 lb-ft  needs 40x more powerful torque just to hold with no acceleration !!
No Go. !

A: by  John David Heinzmann (edited)
A little more context here would help.  As in, what are you trying to do?  Sounds like maybe you want to use the motor/actuator as a brake?  Or a damper?  Is that what you mean by running the actuator in "reverse"?  You want the actuator to absorb mechanical power rather than supply mechanical power?  By actuator, it seems you might mean a gearbox?
When using a brushed DC motor and SI units, the torque constant and the back EMF constant are numerically equal (they are both expressing the same physical phenomenon of interaction of an electrical conductor with a magnetic field).  Thus, a motor with Ke = 25 VDC / krpm, in SI units Ke = 0.239 V/(rad/s).  That's the open-circuit voltage generated at the terminals as a function of shaft speed.  When using it as a motor, the torque produced will be 0.239 Nm/A = Kt, the torque constant.   (By the way, 1 V/(rad/s) = 1 Nm/A = 1 weber!  The weber is the unit of magnetic flux.)
Unfortunately, it is a bit more complicated for a brushless DC motor, which is actually an AC motor, and a 3-phase motor at that.  If you drive the motor mechanically it will act as a generator and produce a 3-phase back-emf voltage wave form, in your case with 38.95 Vpk/krpm or 0.372 Vpk/(rad/s).  I can show you the math if you need me to, but I long ago reverted to using MathCAD (free from PTC) to do these calculations because it completely carries the units through the analysis.   Indeed, you can rectify that voltage and if you apply a resistor across that rectified voltage current will flow through the motor and the resistor and cause a braking torque to appear at the shaft of the motor (in the direction that opposes the direction of rotation regardless of direction of rotation).  However, it is not a matter of simply applying ohms law to the rectified DC voltage to select the resistor.

*

*Depending on the efficiency of the gearbox, the friction in a 60:1 gear ratio when back driven can appear as a significant drag torque and absorb quite a bit of the mechanical power.

*The three-phase configuration of the motor will require a 3-phase rectifier bridge (six diodes in a full-bridge configuration like in the alternator of a car).

*The forward voltage drop of the diodes in the bridge will have a non-linear effect on the load curve, especially at low speeds when Vemf is low and the diode drop voltage is significant by comparison.

*The resistance of the windings will absorb some of the power

*The inductance of the windings will limit the current that can flow at higher frequencies (motor speeds) and thus the amount of braking torque the motor will provide.
For all these reasons, it may be easier for you to determine the needed resistance experimentally.  At 50 rpm and 2.5 ft-lb, you are only talking 17.7 W of mechanical power which, because of losses along the way means your resistor will be absorbing less than that, maybe only 10 or 12 W.  That is not a very big resistor so buying a handful of power resistors or even a variable power resistor in the neighborhood of the resistance you needed may suffice.
At 3000 rpm, the back emf will be  (314 rad/s)*0.372 Vpk/(rad/s) = 117 Vpk.  Since we know the power that will need to be absorbed is less than 17.7 W, the resistor current will have to be less than 17.7 W/117 VDC = 0.15 ADC.  Using ohm's law, the resistance will have to be more than 117 V / 0.15 A = 770 Ω.  In reality, if the power that needs to be absorbed is more like 12 W, the resistance will be more like 1.1 kΩ.
With all that in mind, you might want to buy a 1.5 kΩ adjustable power resistor and lower the resistance until you get the torque you want.  To be safe, it should probably be at least 30 W rated resistor.  I see on Digi-key that they only have 1 kΩ and 500 Ω resistors in stock so maybe buy one of these https://www.digikey.com/product-detail/en/vishay-huntington-electric-inc/AVT05006E1K000KE/AVT50-1-0K-ND/257637 and one of these https://www.digikey.com/products/en?keywords=AVT05006E500R0KE and put them in series?  You get the idea.
By the way, contrary to your original assumption, the higher the resistance the lower the torque.  A short circuit (0 Ω) would give you the highest torque because it would cause the highest current.


text:
Q: How to index small words (3 letters) with SQL Full-text search? I have an Incident table with one row that has the value 'out of office' in the Description column.
However the following query does not return that row.
SELECT * FROM Incident
WHERE CONTAINS( (Incident.Description), '"out*"' )

The word 'out' is not in the noise file (I cleared the noise file completely and I rebuilt the index).
Is it because SQL Full-text search does not index small words? Is there a setting for that? Is there a command that I can run to see exactly which noise file has been used to build the index?
Note: I'm on SQL 2005.

A: when you deal with the noise files, they are not considered until you restart the propper SQL Server FullText Search service for your instance.
I have tested your scenario doing the following and it works...

*

*Having the noise file with the value 'out' in it

*Insert records with value like '% out %' in them

*Executed your select statement and see that they are not returned

*Modify the word file and remove the 'out' entry

*Restarted the SQL Server FullText Search service for my instance

*Rebuild the full text catalog using "ALTER FULLTEXT CATALOG [NameOfMyCatalog] REBUILD"

*Wait a bit (give a chance to the full text service to do the job)

*Executed your select statement and see that they are now returned

Hope this helps...

A: If you haven't already, try rebuilding the index after clearing out the noise file, as mentioned in this answer which links to a helpful blog post.


text:
Q: Update values in jsonfield for particular keys I have JSONField in my model with following structure:
{
    "1":
        {
            ...
            "is_disabled": false
        },
    "2":
        {
            ...
            "is_disabled": false
        },
    "3":
        {
            ...
            "is_disabled": false
        }
}

And I have set of pks like:
pk_set = {1, 2}

How can i update "is_disabled" key to true only for pks in pk_set in single query?


text:
Q: What is the frontend language/platform of api.ai and wit.ai? I am trying to develop a web application like wit.ai or api.ai. I am not sure what would be the best frontend language/platform/technology for such a web applications.
In api.ai and wit.ai you create chat robots. For each robot the user define a bunch of keywords as entity. For example
Entity: Pizza -> {Italian, French, Greek}
Then the user define templates for the input sentences and assign the keywords of the input sentence to the corresponding entities. For example:
I would like to order a Italian with two topping.

In the sentence above, the user assign the "Italian" keyword to the "Pizza" entity. Then they just assign a output response for such a input.
The frontend should let the user performs these tasks such as highlighting a keyword, assigning to entities, showing lists of entities to the user.
Since the algorithms that I am developing are in Python, I was thinking about using Django. Do you think it is the best platform for the such a task?
I really appreciate your help.
Amir

A: While questions about technology are typically subjective and have no 'right' answer, a 'frontend' esque language will do you a lot of good here.
Something like JS, nodejs etc.. You need to be able to highlight the words on the client side and not make any request to the server yet until the user specifies what the highlighted text is. Ofcourse the service that powers your API (to persist the selected entity information) can be powered by py  or any language that makes you smile :)
All the best


text:
Q: Object expected in IE8 Of all the solutions i have seen for this they fall into 3 categories.

*

*Syntax or mispelling.

*Using a type other than text/javascript.

*Having two or more id with the same name.
I have none of these issues and i get an error on the process table data call.
What do i need to do so this will work in Internet Explorer.  Firefox and others do work.
window.onload=function() {
  ProcessTableData();
  mapzoom.add(document.getElementById('UtCounties'),{buttons:false,fading:true});
}

As requested here is the full and complete code.  Please dont mention the html tag or doctype as the content management system (WebEoc - ESI) takes care of that.  Pleases dont mention any tags that refer to eocrepeatallrecords as those are cms specific.  What it does there is build a table of which i consume and set options for the mapzoom product via the calssname.

<title>Image Map Dispaly</title>

<eocrepeatallrecords sort="County_Select, initial_datetime desc">

<eocfield name="County_Select"></eocfield>
<eocfield name="status"></eocfield>
<value-of select="/data/listitems[@listname='Activation Status' and @name=current()/@status]/@listvalue"></value-of>
<eocfield name="initial_datetime"></eocfield>

</eocrepeatallrecords>

County Activation Status

Beaver

Box Elder

Cache

Carbon

Daggett

Davis

Duchesne

Emery

Garfield

Grand

Iron

Juab

Kane

Millard

Morgan

Piute

Rich

Salt Lake

San Juan

San Pete

Sevier

Summit

Tooele

Uintah

Utah

Wasatch

Washington

Wayne

Weber

<map id="UtCounties" name="UtCounties">

<area shape="poly" title="" alt="" href="#" coords="8,432,9,389,128,393,128,400,135,407,135,409,141,416,140,425,138,429,130,433" />
<area shape="poly" title="" alt="" href="#" coords="20,48,162,51,172,71,170,76,171,83,173,96,179,97,182,105,176,109,171,117,155,116,136,142,114,148,18,147" />
<area shape="poly" title="" alt="" href="#" coords="210,51,160,51,173,71,172,75,169,79,172,84,173,90,172,96,182,103,181,109,192,112,200,109,208,108,215,94,215,81,210,67,212,60,212,58" />
<area shape="poly" title="" alt="" href="#" coords="227,270,326,269,330,272,325,278,323,284,321,293,322,303,242,303,235,292,228,278" />
<area shape="poly" title="" alt="" href="#" coords="323,150,393,148,395,184,387,182,382,165,370,164,370,171,362,177,358,169,343,171,333,173,322,169" />
<area shape="poly" title="" alt="" href="#" coords="190,164,182,137,161,135,134,142,152,174,172,158,175,169" />
<area shape="poly" title="" alt="" href="#" coords="325,271,324,170,302,168,283,176,267,177,263,181,256,179,255,258,258,262,259,270" />
<area shape="poly" title="" alt="" href="#" coords="324,399,325,388,321,383,315,379,318,373,312,357,314,351,323,356,322,350,313,347,315,339,319,328,319,319,323,311,323,303,242,303,228,280,228,304,224,304,223,399" />
<area shape="poly" title="" alt="" href="#" coords="131,434,332,434,323,438,320,448,315,447,310,454,310,459,294,461,290,470,288,482,282,486,279,494,275,495,114,494,114,468,124,468,124,458,133,458" />
<area shape="poly" title="" alt="" href="#" coords="325,401,325,395,323,391,317,379,319,376,311,359,314,357,314,352,323,357,323,351,314,348,316,335,320,327,318,322,323,312,323,303,391,302,397,301,398,399" />
<area shape="poly" title="" alt="" href="#" coords="8,431,131,434,131,460,123,460,121,469,113,469,113,494,98,495,97,498,69,501,67,495,51,493,50,485,6,486" />
<area shape="poly" title="" alt="" href="#" coords="13,256,13,292,154,294,155,316,166,317,172,315,177,312,191,311,192,303,193,282,201,278,201,269,186,271,189,263,183,256,169,271,163,272,165,259,158,250,142,259" />
<area shape="poly" title="" alt="" href="#" coords="96,549,95,494,276,496,275,500,269,501,272,506,267,508,269,513,262,517,258,514,257,519,256,529,251,536,239,538,234,540,228,545,225,543,221,549" />
<area shape="poly" title="" alt="" href="#" coords="12,293,153,295,154,316,168,318,169,344,164,353,158,357,156,363,152,365,152,378,143,382,133,381,130,393,9,389" />
<area shape="poly" title="" alt="" href="#" coords="222,138,231,136,227,131,225,120,217,115,211,130,203,128,196,132,186,128,183,139,186,156,190,165,200,171,206,172,211,169,207,158,202,154,207,147,216,143" />
<area shape="poly" title="" alt="" href="#" coords="180,435,180,409,189,399,129,397,133,408,137,410,142,414,138,425,141,429,133,433" />
<area shape="poly" title="" alt="" href="#" coords="211,51,244,51,243,127,230,136,227,127,224,117,216,115,209,109,217,88,210,67,212,59" />
<area shape="poly" title="" alt="" href="#" coords="153,173,173,158,175,168,189,165,199,169,202,182,204,192,201,194,195,199,190,199,174,209,168,206,164,208,158,204" />
<area shape="poly" title="" alt="" href="#" coords="322,400,399,399,402,548,219,549,234,540,246,538,255,532,258,515,267,517,270,510,270,502,274,501,281,491,286,482,291,472,293,461,309,458,316,448,327,437,334,429,330,418,323,409" />
<area shape="poly" title="" alt="" href="#" coords="169,346,168,318,173,316,177,313,190,312,192,303,191,284,202,277,202,270,227,269,228,305,224,304,223,347" />
<area shape="poly" title="" alt="" href="#" coords="223,399,224,346,169,346,166,353,162,353,159,358,152,364,152,376,148,381,133,382,128,397" />
<area shape="poly" title="" alt="" href="#" coords="323,150,245,152,243,152,243,126,232,135,221,137,216,142,208,145,204,154,207,156,212,167,208,173,200,171,203,180,204,190,211,189,215,183,220,189,233,196,239,193,247,195,252,184,256,177,262,182,267,177,287,175,304,169,323,171" />
<area shape="poly" title="" alt="" href="#" coords="13,256,18,147,113,149,134,141,156,183,158,201,155,205,158,216,160,233,157,251,145,259" />
<area shape="poly" title="" alt="" href="#" coords="325,171,334,174,359,169,361,177,369,173,369,164,382,165,384,171,387,184,395,186,397,298,393,302,323,303,322,293,326,276,332,270,325,269" />
<area shape="poly" title="" alt="" href="#" coords="258,269,256,260,242,259,231,247,229,235,225,224,215,222,214,218,207,216,202,207,204,194,197,198,191,198,175,209,169,204,165,207,156,204,158,217,158,226,161,233,157,241,159,248,162,253,162,258,165,265,165,272,173,267,185,257,190,266,188,269" />
<area shape="poly" title="" alt="" href="#" coords="256,260,255,179,249,191,238,194,236,196,220,188,217,184,210,190,204,187,203,196,201,208,206,217,213,218,214,222,225,224,231,238,229,246,239,257,244,261" />
<area shape="poly" title="" alt="" href="#" coords="6,485,50,485,50,493,68,495,69,500,79,500,86,500,98,499,95,549,3,547" />
<area shape="poly" title="" alt="" href="#" coords="187,399,323,400,326,401,325,407,329,412,334,427,332,433,272,433,180,434,182,408" />
<area shape="poly" title="" alt="" href="#" coords="204,128,212,126,215,115,209,109,195,107,191,113,177,109,173,116,153,117,137,141,160,135,182,136,187,127,196,133" />

<area shape="poly" title="" alt="" href="#" coords="255,50,255,2,317,2,317,6,309,4,308,14,302,17,280,17" />
<area shape="poly" title="" alt="" href="#" coords="316,2,357,2,357,6,352,5,342,7,335,6,332,13,321,8" />
<area shape="poly" title="" alt="" href="#" coords="254,51,283,43,307,42,310,44,320,45,322,60,328,69,325,70,332,85,320,88,311,88,309,75,302,75,277,97" />
<area shape="poly" title="" alt="" href="#" coords="400,33,400,2,357,2,356,6,366,13,373,13,382,22,381,32,385,33,385,44" />
<area shape="poly" title="" alt="" href="#" coords="350,117,348,124,338,129,312,140,306,145,299,141,284,137,285,118,277,97,302,75,308,75,308,85,312,89,333,84,340,85,343,96" />
<area shape="poly" title="" alt="" href="#" coords="400,33,400,120,396,127,373,116,368,113,368,109,364,109,360,114,358,120,351,118,344,100,342,90,350,94,356,92,359,85,356,70,348,68,348,64,353,58,364,53,369,52,373,47,387,43" />
<area shape="poly" title="" alt="" href="#" coords="282,146,280,140,285,138,284,121,281,104,254,53,255,146" />
<area shape="poly" title="" alt="" href="#" coords="349,146,345,143,349,137,347,125,336,129,315,137,307,145,300,139,285,139,281,139,283,146" />
<area shape="poly" title="" alt="" href="#" coords="401,122,401,146,349,146,345,143,347,137,348,124,350,118,360,120,364,108,370,108,378,118,387,123,394,126" />
<area shape="poly" title="" alt="" href="#" coords="255,51,280,16,302,16,308,14,309,5,312,6,318,5,327,10,331,12,336,6,356,6,365,14,364,21,361,29,357,32,353,30,347,32,345,36,335,38,330,34,326,35,318,40,321,45,309,43,283,44" />
<area shape="poly" title="" alt="" href="#" coords="333,84,325,69,329,69,322,57,321,45,319,38,329,34,335,38,343,36,347,31,353,31,358,32,366,14,370,13,378,17,382,24,382,32,385,34,385,44,373,45,368,53,353,58,347,68,353,71,359,84,356,94,349,93,333,83" />

</map>

            Beaver
            2
            4640ff
            10/27/2011 14:34:52

            Beaver
            3
            e00b00
            10/27/2011 14:34:40

            Kane
            2
            4640ff
            11/01/2011 09:17:40

            Piute
            3
            e00b00
            11/01/2011 09:17:05

            San Juan
            1
            f0ec00
            10/27/2011 14:35:00

            Wayne
            2
            4640ff
            11/01/2011 09:16:54

A: I've placed your code into this jsFiddle where I can attempt to run it and debug it.
I can see these issues in the code you have included:

*

*You have multiple javascript coding errors where > appears instead of > and < appears instead of < in your javascript comparisons.   All those have to get fixed before the code will even run.

*The code starts to run OK after fixing those errors, but we don't have access to mapzoom.js so I have to comment out any references to it.

*In IE9 (and only in IE9), I find that early on in the ProcessTableData() function, the total value is zero which causes the first loop to do nothing.  This only occurs in IE9.  In Chrome, total is 1 when that loop starts.  This appears to be because of the non-standard HTML you have in oecTable HTML.  Remove that non-standard stuff (e.g. make it look like normal table HTML with no unusual tags in the HTML) and that code starts working again.

Since I have no idea what your code is supposed to actually do, that's all I can see so far.  If you want to provide more info on what it's supposed to do or what else you need help with, perhaps we can help further.

A: IE did not like the fact that i was using .childNodes[0].textContent; to retrieve the info from the table that was generated by the cms.  Nothing was being grabbed and as a result everything went null.  Once i used innerhtml (yes some people warn against it I will update it later) it worked in IE and firefox.  I did need to filter some of the html off of it.
If anyone is interested in the final code send me a message.  Perhaps later this month i will have time to revamp this script.


text:
Q: Firebase Cloud Messaging Android using Kotlin I am trying to send cloud messages (push notifications) from the firebase console to my app. I have seen similar questions on here but nothing worked for me.
I followed the documentation, watched the tutorial, searched online, and StackOverflow and nothing seems to work for me. MainActivity, I am getting the token and trying to use it to send a test message.
FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener(OnCompleteListener { task ->
                if (!task.isSuccessful) {
                    Log.w(TAG, "getInstanceId failed", task.exception)
                    return@OnCompleteListener
                }

                // Get new Instance ID token
                val token = task.result?.token

                // Log and toast
                val msg = getString(R.string.msg_token_fmt, token)
                Log.d(TAG, msg)
            })

MyFirebaseMessagingService similar to the code from the documenttaion
class MyFirebaseMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // [START_EXCLUDE]
        // There are two types of messages data messages and notification messages. Data messages are handled
        // here in onMessageReceived whether the app is in the foreground or background. Data messages are the type
        // traditionally used with GCM. Notification messages are only received here in onMessageReceived when the app
        // is in the foreground. When the app is in the background an automatically generated notification is displayed.
        // When the user taps on the notification they are returned to the app. Messages containing both notification
        // and data payloads are treated as notification messages. The Firebase console always sends notification
        // messages. For more see: https://firebase.google.com/docs/cloud-messaging/concept-options
        // [END_EXCLUDE]

        Log.e(TAG, "From: ${remoteMessage.from}")

        // Check if message contains a data payload.
        if (remoteMessage.data.isNotEmpty()) {
            Log.d(TAG, "Message data payload: ${remoteMessage.data}")

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                scheduleJob()
            } else {
                // Handle message within 10 seconds
                handleNow()
            }
        }

        // Check if message contains a notification payload.
        remoteMessage.notification?.let {
            Log.d(TAG, "Message Notification Body: ${it.body}")

            sendNotification(it.body.toString())
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.
    }
    // [END receive_message]

    // [START on_new_token]
    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    override fun onNewToken(token: String) {
        Log.d(TAG, "Refreshed token: $token")

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        sendRegistrationToServer(token)
    }
    // [END on_new_token]

    /**
     * Schedule async work using WorkManager.
     */
    private fun scheduleJob() {
        // [START dispatch_job]
        val work = OneTimeWorkRequest.Builder(MyWorkerActivity::class.java).build()
        WorkManager.getInstance().beginWith(work).enqueue()
        // [END dispatch_job]
    }

    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private fun handleNow() {
        Log.d(TAG, "Short lived task is done.")
    }

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private fun sendRegistrationToServer(token: String?) {
        // TODO: Implement this method to send token to your app server.
        Log.d(TAG, "sendRegistrationTokenToServer($token)")
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private fun sendNotification(messageBody: String) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT)

        val channelId = getString(R.string.default_notification_channel_id)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_stat_sample_notification)
            .setContentTitle(getString(R.string.fcm_message))
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build())
    }

    companion object {

        private const val TAG = "MyFirebaseMsgService"
    }
}

And inside my AndroidManifest file I have this
<!-- [START firebase_service] -->
        <service
            android:name=".ui.services.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->

I saw a similar question that had an answer to downgrading the firebase messaging dependency, I also tried that with no luck. I will post more If I have to. Any help will be much appreciated, thanks.

A: First just make sure that testing notification works,inside onNewToken place just log the token and try to send it manually, make sure that your software accept/receive notification while on background.( open up Settings and go to Apps & Notifications. Within that screen, tap on See all X apps (where X is the number of apps you have installed) then select yours and make sure that "background activity" is on.
Try this out also,It works for me.I hope it could help
dependency : implementation 'com.google.firebase:firebase-messaging:20.2.0'
class MyFirebaseMessagingService : FirebaseMessagingService() {
    val TAG = "FirebaseMessagingService"

    @SuppressLint("LongLogTag")
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.d(TAG, "msg received: ${remoteMessage.from}")
        if (remoteMessage.notification != null) {
            showNotification(remoteMessage.notification?.title, remoteMessage.notification?.body)
        }
    }
    override fun onNewToken(token: String) {
        Log.d("TAG", "Refreshed token: $token")
    }
    private fun showNotification(title: String?, body: String?) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
        val pendingIntent = PendingIntent.getActivity(this, 0, intent,
            PendingIntent.FLAG_ONE_SHOT)
        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(soundUri)
            .setContentIntent(pendingIntent)
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.notify(0, notificationBuilder.build())
    }
}

A: Turns out I had to retype my Service in order for it to work. I have to remember not to copy and paste any more. Going to leave it here for anybody who faces this problem in the future. Happy coding!
class FCMService : FirebaseMessagingService() {

    val TAG = "FCMService"

    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)

        Log.d(TAG,"From: ${remoteMessage.from}")

        if (remoteMessage.data.isNotEmpty()) {
            Log.d(TAG, "Message data payload: ${remoteMessage.data}")

            if (true) {
                scheduleJob()
            }else {
                handleNow()
            }
        }

        remoteMessage.notification?.let {
            Log.d(TAG, "Message notification body: ${it.body}")

            sendNotification(it.body.toString())
        }

    }

    private fun sendNotification(messageBody: String) {
        val intent = Intent(this, MainActivity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

        val pendingIntent = PendingIntent.getActivity(this, 0,
            intent,
            PendingIntent.FLAG_ONE_SHOT)

        val channelId = getString(R.string.default_notification_channel_id)
        val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notificationBuilder = NotificationCompat.Builder(
            this, channelId
        )
            .setSmallIcon(R.drawable.ic_stat_sample_notification)
            .setContentTitle(getString(R.string.fcm_message))
            .setContentText(messageBody)
            .setAutoCancel(false)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent)

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId,
                "Channel human readable title",
                NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(channel)
        }

        notificationManager.notify(0, notificationBuilder.build())

    }

    override fun onNewToken(token: String) {
        //super.onNewToken(token)

        Log.d(TAG, token)
    }

    private fun handleNow() {
        Log.d(TAG, "Short lived task done")
    }

    private fun scheduleJob() {
        TODO("Not yet implemented")
    }

}

<service
            android:name=".ui.services.FCMService"
            android:enabled="false"
            android:exported="false">

            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>

        </service>


text:
Q: Tables not found in Spark SQL after migrating from EMR to AWS Glue I have Spark jobs on EMR, and EMR is configured to use the Glue catalog for Hive and Spark metadata.
I create Hive external tables, and they appear in the Glue catalog, and my Spark jobs can reference them in Spark SQL like spark.sql("select * from hive_table ...")
Now, when I try to run the same code in a Glue job, it fails with "table not found" error.  It looks like Glue jobs are not using the Glue catalog for Spark SQL the same way that Spark SQL would running in EMR.
I can work around this by using Glue APIs and registering dataframes as temp views:
create_dynamic_frame_from_catalog(...).toDF().createOrReplaceTempView(...)
but is there a way to do this automatically?

A: This was a much awaited feature request (to use Glue Data Catalog with Glue ETL jobs) which has been release recently.
When you create a new job, you'll find the following option
Use Glue data catalog as the Hive metastore
You may also enable it for an existing job by editing the job and adding --enable-glue-datacatalog in the job parameters providing no value

A: Instead of using SparkContext.getOrCreate(), you should use SparkSession.builder().enableHiveSupport().getOrCreate(), with enableHiveSupport() being the important part that's missing. I think what's probably happening is that your Spark job is not actually creating your tables in Glue but rather is creating them in Spark's embedded Hive metastore, since you have not enabled Hive support.

A: Had the same problem. It was working on my Dev endpoint but not the actual ETL job. It is fixed by editing the job from Spark 2.2 to Spark 2.4.

A: in my case
SparkSession.builder
      .config(
        "hive.metastore.client.factory.class",
        "com.amazonaws.glue.catalog.metastore.AWSGlueDataCatalogHiveClientFactory")


text:
Q: Redux-Toolkit Store does not have a valid reducer I'm using Redux-Toolkit for the first time, followed the Quick-start in their documentation and am met with this error

Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.

I logged the reducers and the store objects to console and found that the store object from configure store doesn't have a reducer property at all.
If any of you can help out, I'd really appreciate it.
P.S : I already looked at all the other stackoverflow question on this. Nothing is relevant.
Here's my code

*

*store.js

import { configureStore } from "@reduxjs/toolkit";

// Redux Reducers
import { authSlice } from "./slices/authSlice";
import { projectSlice } from "./slices/projectSlice";

export const store = configureStore({
    reducer: {
        auth: authSlice.reducer,
        project: projectSlice.reducer,
    },
});

*

*authSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const authSlice = createSlice({
    name: "auth",
    initialState: {
        isUserLoggedIn: false,
        userDetails: {},
    },
    reducers: {
        login: (state) => {
            state.auth.isUserLoggedIn = true;
        },
        logout: (state) => {
            state.auth.isUserLoggedIn = false;
        },
        register: (state) => {
            state.auth.isUserLoggedIn = true;
        },
    },
});

export const { login, logout, register } = authSlice.actions;


text:
Q: Solucion al problema de JSON.parse ¡Buenas noches!; tengo un sistema de compra y venta de artículos en el archivo "cliente.js" que dentro de mi proyecto esta en la carpeta (/vistas/js) ya que el proyecto esta dividido en varias partes; este el mi código "clientes.js"

var tabla;

var tabla_en_ventas;

//Función que se ejecuta al inicio
function init(){

 listar();

 //llama la lista de clientes en ventana modal en ventas.php
    listar_en_ventas();

  //cuando se da click al boton submit entonces se ejecuta la funcion guardaryeditar(e);
 $("#cliente_form").on("submit",function(e)
 {

  guardaryeditar(e);
 })

    //cambia el titulo de la ventana modal cuando se da click al boton
 $("#add_button").click(function(){

   $(".modal-title").text("Agregar Cliente");

   });

}

//Función limpiar
/*IMPORTANTE: no limpiar el campo oculto del id_usuario, sino no se registra
el cliente*/
function limpiar()
{

 $('#cedula').val("");
 $('#nombre').val("");
 $('#apellido').val("");
 $('#telefono').val("");
 $('#email').val("");
 $('#direccion').val("");
 $('#estado').val("");
 $('#cedula_cliente').val("");
}

//Función Listar
function listar()
{
 tabla=$('#cliente_data').dataTable(
 {
  "aProcessing": true,//Activamos el procesamiento del datatables
     "aServerSide": true,//Paginación y filtrado realizados por el servidor
     dom: 'Bfrtip',//Definimos los elementos del control de tabla
     buttons: [
              'copyHtml5',
              'excelHtml5',
              'csvHtml5',
              'pdf'
          ],
  "ajax":
    {
     url: '../ajax/cliente.php?op=listar',
     type : "get",
     dataType : "json",
     error: function(e){
      console.log(e.responseText);
     }
    },
  "bDestroy": true,
  "responsive": true,
  "bInfo":true,
  "iDisplayLength": 10,//Por cada 10 registros hace una paginación
     "order": [[ 0, "desc" ]],//Ordenar (columna,orden)

     "language": {

       "sProcessing":     "Procesando...",

       "sLengthMenu":     "Mostrar _MENU_ registros",

       "sZeroRecords":    "No se encontraron resultados",

       "sEmptyTable":     "Ningún dato disponible en esta tabla",

       "sInfo":           "Mostrando un total de _TOTAL_ registros",

       "sInfoEmpty":      "Mostrando un total de 0 registros",

       "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",

       "sInfoPostFix":    "",

       "sSearch":         "Buscar:",

       "sUrl":            "",

       "sInfoThousands":  ",",

       "sLoadingRecords": "Cargando...",

       "oPaginate": {

           "sFirst":    "Primero",

           "sLast":     "Último",

           "sNext":     "Siguiente",

           "sPrevious": "Anterior"

       },

       "oAria": {

           "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",

           "sSortDescending": ": Activar para ordenar la columna de manera descendente"

       }

      }//cerrando language

 }).DataTable();
}

//Mostrar datos del cliente en la ventana modal
function mostrar(cedula_cliente)
{
 $.post("../ajax/cliente.php?op=mostrar",{cedula_cliente : cedula_cliente}, function(data, status)
 {
  data = JSON.parse(data);

   //alert(data.cedula);

     console.log(data);

    $('#clienteModal').modal('show');
    $('#cedula').val(cedula_cliente);
    $('#nombre').val(data.nombre);
    $('#apellido').val(data.apellido);
    $('#telefono').val(data.telefono);
    $('#email').val(data.correo);
    $('#direccion').val(data.direccion);
    $('#estado').val(data.estado);
    $('.modal-title').text("Editar Cliente");
    $('#cedula_cliente').val(cedula_cliente);

  });

 }

 //la funcion guardaryeditar(e); se llama cuando se da click al boton submit
function guardaryeditar(e)
{
 e.preventDefault(); //No se activará la acción predeterminada del evento
 var formData = new FormData($("#cliente_form")[0]);

  $.ajax({
   url: "../ajax/cliente.php?op=guardaryeditar",
      type: "POST",
      data: formData,
      contentType: false,
      processData: false,

      success: function(datos)
      {
            /*bootbox.alert(datos);
            mostrarform(false);
            tabla.ajax.reload();*/

           //alert(datos);

                 /*imprimir consulta en la consola debes hacer un print_r($_POST) al final del metodo
                    y si se muestran los valores es que esta bien, y se puede imprimir la consulta desde el metodo
                    y se puede ver en la consola o desde el mensaje de alerta luego pegar la consulta en phpmyadmin*/
           console.log(datos);

             $('#cliente_form')[0].reset();
    $('#clienteModal').modal('hide');

    $('#resultados_ajax').html(datos);
    $('#cliente_data').DataTable().ajax.reload();

                limpiar();

      }

  });

}

//EDITAR ESTADO DEL CLIENTE
//importante:id_cliente, est se envia por post via ajax

    function cambiarEstado(id_cliente, est){

 bootbox.confirm("¿Está Seguro de cambiar de estado?", function(result){
  if(result)
  {

   $.ajax({
    url:"../ajax/cliente.php?op=activarydesactivar",
     method:"POST",
    //data:dataString,
    //toma el valor del id y del estado
    data:{id_cliente:id_cliente, est:est},
    //cache: false,
    //dataType:"html",
    success: function(data){

                  $('#cliente_data').DataTable().ajax.reload();

       }

   });

    }

   });//bootbox

   }

    //Función Listar
function listar_en_ventas(){

 tabla_en_ventas=$('#lista_clientes_data').dataTable(
 {
  "aProcessing": true,//Activamos el procesamiento del datatables
     "aServerSide": true,//Paginación y filtrado realizados por el servidor
     dom: 'Bfrtip',//Definimos los elementos del control de tabla
     buttons: [
              'copyHtml5',
              'excelHtml5',
              'csvHtml5',
              'pdf'
          ],
  "ajax":
    {
     url: '../ajax/cliente.php?op=listar_en_ventas',
     type : "get",
     dataType : "json",
     error: function(e){
      console.log(e.responseText);
     }
    },
  "bDestroy": true,
  "responsive": true,
  "bInfo":true,
  "iDisplayLength": 10,//Por cada 10 registros hace una paginación
     "order": [[ 0, "desc" ]],//Ordenar (columna,orden)

     "language": {

       "sProcessing":     "Procesando...",

       "sLengthMenu":     "Mostrar _MENU_ registros",

       "sZeroRecords":    "No se encontraron resultados",

       "sEmptyTable":     "Ningún dato disponible en esta tabla",

       "sInfo":           "Mostrando un total de _TOTAL_ registros",

       "sInfoEmpty":      "Mostrando un total de 0 registros",

       "sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",

       "sInfoPostFix":    "",

       "sSearch":         "Buscar:",

       "sUrl":            "",

       "sInfoThousands":  ",",

       "sLoadingRecords": "Cargando...",

       "oPaginate": {

           "sFirst":    "Primero",

           "sLast":     "Último",

           "sNext":     "Siguiente",

           "sPrevious": "Anterior"

       },

       "oAria": {

           "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",

           "sSortDescending": ": Activar para ordenar la columna de manera descendente"

       }

      }//cerrando language

 }).DataTable();
}

//AUTOCOMPLETAR DATOS DEL CLIENTE EN VENTAS

   function agregar_registro(id_cliente,est){

  $.ajax({
   url:"../ajax/cliente.php?op=buscar_cliente",
   method:"POST",
   data:{id_cliente:id_cliente,est:est},
   dataType:"json",
   success:function(data)
   {

            /*si el cliente esta activo entonces se ejecuta, de lo contrario
            el formulario no se envia y aparecerá un mensaje */
            if(data.estado){

    $('#modalCliente').modal('hide');
    $('#cedula').val(data.cedula_cliente);
    $('#nombre').val(data.nombre);
    $('#apellido').val(data.apellido);
    $('#direccion').val(data.direccion);
    $('#id_cliente').val(id_cliente);

            } else{

                bootbox.alert(data.error);

             } //cierre condicional error

   }
  })

    }

     //ELIMINAR CLIENTE

  function eliminar(id_cliente){

     bootbox.confirm("¿Está Seguro de eliminar el cliente?", function(result){
  if(result)
  {

    $.ajax({
     url:"../ajax/cliente.php?op=eliminar_cliente",
     method:"POST",
     data:{id_cliente:id_cliente},

     success:function(data)
     {
      //alert(data);
      $("#resultados_ajax").html(data);
      $("#cliente_data").DataTable().ajax.reload();
     }
    });

        }

   });//bootbox

   }

init();

Pero al ejecutar la Vista HTML Bootstrap Clientes.php; sale un error al editar
introducir la descripción de la imagen aquí

<?php

   require_once("../config/conexion.php");

    if(isset($_SESSION["id_usuario"])){

?>

<?php

  require_once("header.php");

?>

Listado de Clientes

                            <button class="btn btn-primary btn-lg" id="add_button" onclick="limpiar()" data-toggle="modal" data-target="#clienteModal"> Nuevo Cliente</button>

                                Cédula
                                Nombres
                                Apellidos
                                Teléfono
                                Correo
                                Dirección
                                Fecha
                                Estado
                                Editar
                                Eliminar

    <form class="form-horizontal" method="post" id="cliente_form">

          <button type="button" class="close" data-dismiss="modal">×</button>

Agregar Cliente

                  Cédula

                    <input type="text" class="form-control" id="cedula" name="cedula" placeholder="Cédula" required pattern="[0-9]{0,15}">

                  Nombres

                    <input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombres" required pattern="^[a-zA-Z_áéíóúñ\s]{0,30}$">

                  Apellidos

                    <input type="text" class="form-control" id="apellido" name="apellido" placeholder="Apellidos" required pattern="^[a-zA-Z_áéíóúñ\s]{0,30}$">

                  Teléfono

                    <input type="text" class="form-control" id="telefono" name="telefono" placeholder="Teléfono" required pattern="[0-9]{0,15}">

                  Correo

                    <input type="email" class="form-control" id="email" name="email" placeholder="Correo" required="required">

                  Dirección

                 <textarea class="form-control  col-lg-5" rows="3" id="direccion" name="direccion"  placeholder="Direccion ..." required pattern="^[a-zA-Z0-9_áéíóúñ°\s]{0,200}$"></textarea>

                  Estado

                      <select class="form-control" id="estado" name="estado" required>
                      <option value="">-- Selecciona estado --</option>
                      <option value="1" selected>Activo</option>
                      <option value="0">Inactivo</option>
                    </select>

          <input type="hidden" name="id_usuario" id="id_usuario" value="<?php echo $_SESSION["id_usuario"];?>"/>
          <input type="hidden" name="id_cliente" id="id_cliente"/>
          <input type="hidden" name="cedula_cliente" id="cedula_cliente"/>

          <button type="submit" name="action" id="#" class="btn btn-success pull-left" value="Add"> Guardar </button>

          <button type="button" class="btn btn-danger" data-dismiss="modal"> Cerrar</button>

    </form>

<?php

  require_once("footer.php");
?>

<?php

  } else {

        header("Location:".Conectar::ruta()."vistas/index.php");

  }

?>


text:
Q: joining two collections in json store Is it possible to join two collections in JSONStore?
I want to access data from the given two collections in the json store one of which has a foreign key.

A: There's nothing equivalent to a join in Relational Databases for JSONStore. However, like Namfo said in the other answer, you may take advantage of additionalSearchFields for this use case. It allows you to index values that are not part of the data being stored. For example, if you have a order collection and are storing objects like {item: 'knife'} you could have an additional search field for customer_id which references an id search field in the customer collection. Here is a post that explains additional search fields.

A: JSONSTORE does not have the ability to combine collections. However, you can use a common index between the two collections to access relevant data. For instance, order_id search field can be shared between the customer collection and order collection.


text:
Q: function still running after .hide()? I have a link whenever I click, there's a popup. I've set up a modal window within a function and it does some other stuff within it. In the modal window, I have a close button. But for some reason
function popup(){
//dostuff
}

$('selector').hover(function(){
   $('open_selector').click(function(){
   popup();
});
},function(){
   //button to .hide();
});

When I hid the popup, the stuff in the function still operates. Shouldn't it not do anything? unless I click on the link again?
Thanks!
Edit: I have an element that is hidden and I wanted to show it on hover, thats why I have the hover statement. But I forgot to add a button close in this script which closes the popup();
$('button_selector').click(function(){
//hide the dialog box that pops up (in this case popup())
});

A: I think you mean:
$('selector').hover(function(){
   $('open_selector').click(function(){
       popup();
    });
},function(){
   //button to .hide();
});

First, you're subscribing an event inside of a hover function.  Why not put this in your document.ready handler
$('open_selector').click(function(){
   popup();
});

The way you have it, the click handler would not be active until you first hovered over this element.  Also, this selector will try to find tags named 'open_selector' - is this a class?  If so, you want $('.open_selector').click( - ditto for $('selector').hover

As far as your original question, the second function, what you list as
,function(){
   //button to .hide();
}

is what is supposed to execute whenever the mouse hovers out.  It will always execute when your mouse hovers out of whatever your original selector was.


text:
Q: Can a charged particle pass through a superconductor? Can a charged particle pass through a superconductor?
I think it is impossible, because the superconductor will induce an infinite electric field which keeps the particle away.

A: The answer is yes and no.
"Yes", because a superconductor is able to transfer charges from one contacted edge to an other one.
"No" (somehow), because charges do not flow inside the superconductors, but at its edges. This is an old result due to London, showing that the current flows always at the edges of a superconductor, over a distance known as the penetration length. For more details see F. London, Superfluids, Volume I: Macroscopic Theory of Superconductivity (Dover Publications, Inc., 1961).
So in a sense you're right. One usually prefers to say that the magnetic field is zero inside the superconductor instead of this curious statement that the electric field is infinite. That's the reason why there is no current in the bulk, and only at the edge.


text:
Q: Running a Blf file in constant Loop for Emulation using CAPL I want to run a .blf file using the Replay Block in CANalyzer . I want to run this file in a constant loop for emulation purpose. Is it possible using CAPL or can some one instruct me how to do this even without CAPL.

A: You don't need CAPL to replay a log file in a loop.

*

*Right click the Replay block

*In the "General" tab, enable "Repetitive output sending mode"