text:
Q: How to create unique id entries and filter for specific column values for these ids (Postgresql) Below you can see for each customer several product entries and the time they bought the product. However I am only intersted whether they ever bought product 1, and if they have never bought it I would fill the cell with product x instead of skipping the id. I am using Postgresql!
This is the current table:

and this is the desired outcome:

I am trying this table but it does not provide quite what I am looking for. Is it possible to transform the first table into the 2nd at all?
select distinct on ("id")
"id", "buying date", "product",
case when "product"='product 1' then 'product 1' else 'product x' as "Product2"
from product
order by 1,2

A: If I understand correctly, the logic you want should be in the order by clause:
select distinct on ("id")
       "id", "buying date", "product"
from product
order by id,
         ("product" = 'product 1') desc,  -- put product1 first
         "buying date";

For a boolean expression, DESC orders the true value first then the false.


text:
Q: PL/SQL: SELECT INTO using a variable in the FROM clause Code:
lc_tab1_col1 VARCHAR2(4000);
lc_tab1_col2 VARCHAR2(4000);
lc_tab2_col2 VARCHAR2(4000);
lc_tab2_col2 VARCHAR2(4000);
CURSOR my_cursor IS select col1, col2 from tab1;

[...]

    OPEN my_cursor;

       LOOP
       FETCH my_cursor INTO lc_tab1_col1, lc_tab1_col2;
       EXIT WHEN my_cursor%NOTFOUND;

           SELECT lc_tab1_col2.col1, lc_tab1_col2.col2 INTO lc_tab2_col2, lc_tab2_col2 FROM lc_tab1_col2 WHERE lc_tab1_col2.col3 = lc_tab1_col1;

           [...]

       END LOOP;

    CLOSE my_cursor;

Hey folks,
I am trying to get the above code working.
The issue I am having is that a SELECT INTO statement apparently does not support using a variable (in that case lc_tab1_col2) as the table  name in the FROM clause of the statement.
When compiling the package an ORA-000942 is thrown (table or view does not exist), which tells me the variable is interpreted directly instead of being replaced and interpreted at runtime.
I can't think of a workaround on the fly, any ideas on how to fix this?
Some more background: lc_tab1_col2 contains the name of a table in the database whereas lc_tab1_col1 contains an ID.
This ID is present in all of the tables that can be contained in lc_tab1_col2 (hence the WHERE clause).
Apart from the ID there are two other columns (lc_tab1_col2.col1 and lc_tab1_col2.col2) that are present in all those tables, but that are not present in tab1. I need to select those two values to work with them inside the loop.
As there are many tables to consider, I need this SELECT INTO statement to be dynamic. It wouldn't be feasible to parse the tables one by one. Looking forward to anyone sharing a clever idea for overcoming this issue :) Thanks in advance!

A: I think, you exception really means that this table does not exist or you don't have privileges to SELECT it.
I've executed a below code and everything was ok. I have tried to compile it in a package and also I didn't have any compilation errors
DECLARE
  user_tables varchar2(30) := 'TBLCOMPANIES';
BEGIN
  SELECT table_name
    INTO user_tables
    FROM user_tables
   WHERE user_tables.table_name = user_tables;

  dbms_output.put_line(user_tables) ;
END;
/

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the size of a Service Broker Queue quickly when the table is >500K rows, and filter it by MessageType A couple of years ago, a question was asked on StackOverflow about getting the count of messages in a large queue.
How do I get the size of a Service Broker Queue quickly when the table is >500k rows?
An answer was given to query the underlying b-tree.
http://rusanu.com/2006/11/09/fast-way-to-check-message-count/
If there are multiple MessageTypes in the queue, is there a way to do this same query of the underlying b-tree with the counts filtered by MessageType?
We can do it this way, but we fear this could cause performance problems on large queues.
SELECT COUNT(*) FROM My_Queue WHERE message_type_name = 'MyMessageType'

A: No - the query on the b-tree is looking at the real data structure (the concept of a table that we think all relational databases are composed if is, itself, not really what's there underneath).
The only way to filter on a value in a column is to run the query against the table - unfortunately.


text:
Q: How to properly emulate statement level triggers with access to data in postgres I am using PostgreSQL as my database for a project at work. We use triggers in quite a few places to either maintain computed columns, or tables that essentially act as a materialized view.
All this worked just fine when simply utilizing row level triggers to keep all this in sync. However when we wrote scripts to periodically import our customers data into the database, we ran into issues with either performance or problems with number of locks in a single transaction.
To alleviate this I wanted to create a statement-level trigger with access to the modified rows (inserted, updated or deleted). However as this is not possible I instead created a BEFORE statement-level trigger that would create a temporary table. Then an AFTER row-level trigger that would insert the changed data into the temporary table. At last an AFTER statement-level trigger that would read the changes and perform necessary updates, and then drop the temporary table.
All this works just fine, assuming that within the triggers, no one would re-trigger the same flow again (as the temporary table would then already exist).
However I then learned that when using foreign key constraints with ON DELETE SET NULL, it is simply implemented with a system trigger that sets the column to NULL. This of course is not a problem at all, except for the fact that when you have several foreign key constraints like this on a single table, all referencing the same table (let's just call this files). When deleting a row from the files table, all these system level triggers to handle the ON DELETE SET NULL clause all fire at the same time, that is in parallel. Which presents a serious issue for me.
How would I go about implementing something like this? Here is a short SQL script to illustrate the problem:
CREATE TABLE files (
    id serial PRIMARY KEY,
    "name" TEXT NOT NULL
);

CREATE TABLE profiles (
    id serial PRIMARY KEY,
    NAME TEXT NOT NULL,
    cv_file_id INT REFERENCES files(id) ON DELETE SET NULL,
    photo_file_id INT REFERENCES files(id) ON DELETE SET NULL
);

CREATE TABLE profile_audit (
    profile_id INT NOT NULL,
    modified_at timestamptz NOT NULL
);

CREATE FUNCTION pre_stmt_create_temp_table()
RETURNS TRIGGER
AS $$
BEGIN
    CREATE TEMPORARY TABLE tmp_modified_profiles (
        id INT NOT NULL
    ) ON COMMIT DROP;
    RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';

CREATE FUNCTION insert_modified_profile_to_temp_table()
RETURNS TRIGGER
AS $$
BEGIN
    INSERT INTO tmp_modified_profiles(id) VALUES (NEW.id);
    RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';

CREATE FUNCTION post_stmt_insert_rows_and_drop_temp_table()
RETURNS TRIGGER
AS $$
BEGIN
    INSERT INTO profile_audit (id, modified_at)
    SELECT t.id, CURRENT_TIMESTAMP FROM tmp_modified_profiles t;

    DROP TABLE tmp_modified_profiles;

    RETURN NULL;
END;
$$ LANGUAGE 'plpgsql';

CREATE TRIGGER tr_create_working_table BEFORE UPDATE ON profiles FOR EACH STATEMENT EXECUTE PROCEDURE pre_stmt_create_temp_table();
CREATE TRIGGER tr_insert_row_to_working_table AFTER UPDATE ON profiles FOR EACH ROW EXECUTE PROCEDURE insert_modified_profile_to_temp_table();
CREATE TRIGGER tr_insert_modified_rows_and_drop_working_table AFTER UPDATE ON profiles FOR EACH STATEMENT EXECUTE PROCEDURE post_stmt_insert_rows_and_drop_temp_table();

INSERT INTO files ("name") VALUES ('photo.jpg'), ('my_cv.pdf');

INSERT INTO profiles ("name") VALUES ('John Doe');

DELETE FROM files WHERE "name" = 'photo.jpg';

A: It would be a serious hack, but meanwhile, until PostgreSQL 9.5 is out, I would try to use CONSTRAINT triggers deferred to the end of the transaction. I am not really sure this will work, but might be worth trying.

A: You could use a status column to track inserts and updates for your statement-level triggers.
In a BEFORE INSERT OR UPDATE row-level trigger:
    SET NEW.status = TG_OP;

Now you can use statement-level AFTER triggers:
    BEGIN
        DO FUNNY THINGS
         WHERE status = 'INSERT';

        -- reset the status
        UPDATE mytable
           SET status =  NULL
         WHERE status = 'INSERT';
    END;

However, if you want to deal with deletes as well, you'll need something like this in your row-level trigger:
    INSERT INTO status_table (table_name, op, id) VALUES (TG_TABLE_NAME, TG_OP, OLD.id);

Then, in your statement-level AFTER trigger, you can go like:
    BEGIN
        DO FUNNY THINGS
         WHERE id IN (SELECT id FROM status_table
                       WHERE table_name = TG_TABLE_NAME AND op = TG_OP); -- just an example

        -- reset the status
        DELETE FROM status_table
         WHERE table_name = TG_TABLE_NAME AND op = TG_OP;
    END;


text:
Q: How to find this limit using integration? What is the value of $$\lim_{n \to \infty}\frac{(\sum_{k=1}^{n} k^2 )*(\sum_{k=1}^{n} k^3 )}{(\sum_{k=1}^{n} k^6)}$$
I just know that it has to be done by converting it into an integral. I have no idea how to do it. Any other solution is also welcome.

A: For every $a\geqslant0$, $x\mapsto x^a$ is nondecreasing on $x\geqslant0$ hence $(k-1)^a\leqslant x^a\leqslant k^a$ for every $x$ in $(k-1,k)$. Thus,
$$
(k-1)^a\leqslant\int_{k-1}^kx^a\mathrm dx\leqslant k^a.
$$
Summing these on $k$ yields
$$\frac{n^{a+1}}{a+1}=\int_0^{n}x^a\mathrm dx\leqslant\sum_{k=1}^n k^a\leqslant\int_1^{n+1}x^a\mathrm dx\leqslant\frac{(n+1)^{a+1}}{a+1},
$$
In particular, considering
$$
S_a(n)=\sum_{k=1}^n k^a,$$
one sees that
$$
n^{-(a+1)}S_n(a)\to\frac1{a+1}.
$$
Using this for $a=2$, $3$ and $6$ yields
$$
\frac{S_n(2)S_n(3)}{S_n(6)}=\frac{n^{-3}S_n(2)\,n^{-4}S_n(3)}{n^{-7}S_n(6)}\to\frac{6+1}{(2+1)(3+1)}=\frac7{12}.
$$

A: As
 $\displaystyle\lim_{n \to \infty} \frac1n\sum_{r=1}^n f\left(\frac rn\right)=\int_0^1f(x)dx$
$$\lim_{n\to\infty}\frac1n\sum_{r=1}^n\left(\frac kn\right)^r=\int_0^1x^r dx=\frac1{r+1}$$ for $r+1\ne0$


text:
Q: GoogleToolboxForMac.framework and GoogleOpenSource.framework conflict I already using GoogleOpenSource.framework in my app for Google+ integration. Now I want to add Firebase Analytics with Google Tag Manager. In order to do that, It needs to include GoogleToolboxForMac.framework. Now my contains both GoogleToolboxForMac and GoogleOpenSource frameworks.
Issue is both frameworks has GTMLogger class, so the project cannot compile. It gives
duplicate symbol _OBJC_METACLASS_$_GTMLogAllowedLevelFilter

I try to remove the GTMLogger class from one of the framework, but It cannot be done. What should be I do to overcome this issue?

A: this answer those who use manual integration for adding the Firebase,
I also faced the same issue, both google+ and Firebase analytics has same file GTMLogger we can't remove it from the framework, instead, we need to review the Google plus integration see thisStep 2.(in point 4) Initialize the Google+ Client in they have mentioned If your project already includes some of the open source files, you can instead include the remaining files from the OpenSource folder. this did the trick.
since  GTMLogger is present in the GoogleToolboxForMac.framework we don't need to add this, so remove the framework of Google plus's  GoogleOpenSource.framework and add the files in open source and do not include the file GTMLogger.m and GTMLogger.h of newly downloaded google+ frameworks folder, and remove all imports of this frame work, this might give some error like in the line
[GPPSignIn sharedInstance].scopes = @[kGTLAuthScopePlusLogin]; //error

simply command click on kGTLAuthScopePlusLogin and import the .h file that is #import "GTLPlusConstants.h".
Hope this helps


text:
Q: A word that means the opposite of "menagerie" I'm trying to find a couple antonyms of the word "menagerie".  Some word that means a group of clones, or a collection of virtually identical things.  I haven't been able to find one.  Can you help me?
EDIT: this word must fit:

"Mr. Smith had a ______ of birds.  They all looked exactly the same."

(Must imply the birds being the same w/o second sentence)

A: Sorry but no such word exists and it would be much more useful for you to completely rephrase the question, than to pursue it as originally posed.
"Menagerie" does always mean a group of creatures but it's by no means always assumed that they're different creatures.
"Menagerie" does have more to do with the place where they are kept or cared for than the creatures themselves.
Either way, asking for an "opposite" or "antonym" of "menagerie" or any word like it, is rather like asking for an "opposite" or "antonym" of "people" or of "fish".
My point is that that kind of thinking should be recognised as a dead end, and turned away from.
A word for a group or herd or bunch or flock of birds that all looked exactly the same is such a different thing, it's very unlikely to be found from that perspective.
Unless I and others have completely misunderstood, the concept is much too broad to be expressed in a simple sentence such as "Mr. Smith had a ______ of birds. They all looked exactly the same" - the more so if the answer "Must imply the birds being the same w/o second sentence."
Aside from the original question, can you please rephrase "They all looked exactly the same" to express your meaning in different words?

A: See my comment for Richard Kayser, above.
In the military, the attempt in Basic Training is to eliminate differences between soldiers among the ranks. Individuality is discouraged, except for the exceptional standout, who ends up in a key unit, such as the Green Berets, Navy SEALs, etc.
Everyone else is, by design, made to look just like the next guy. There are many opinions as to why this is, but the fact is, it is this way. Every man gets the same uniform. The haircuts are the same, even the glasses are identical, except for the prescription.
So, maybe an army term based on size would be suitable, with an adjective preceding it to further describe the collection.
For example, some size words: squad, platoon, brigade, army...
"Mr. Smith had a squad of birds. They all looked exactly the same."
"Mr. Smith had a platoon of birds. They all looked exactly the same."
"Mr. Smith had a brigade of birds. They all looked exactly the same."
"Mr. Smith had an army of birds. They all looked exactly the same."
Adjectives to describe the collection: unorganized, disciplined, undisciplined, etc.
"Mr. Smith had an unorganized squad of birds. They all looked exactly the same."
"Mr. Smith had a disciplined squad of birds. They all looked exactly the same."
"Mr. Smith had an undisciplined squad of birds. They all looked exactly the same."

A: The word you are looking for may be embodied in the phase you've mentioned in  your question -- "groups of clones". This usage of clones as individual organisms is consistent with the following definition from Dictionary.com:

clone: a cell, cell product, or organism that is genetically identical to the unit or individual from which it was derived.

However, Dictionary.com also provides the following definition:

clone: a population of identical units, cells, or individuals that derive from the same ancestral line. [emphasis added]

So it would seem that clone works in your example, and it works without the second sentence:

"Mr. Smith had a clone of birds."

Translation: "Mr. Smith had a population of identical individual birds derived from the same ancestral line."

A: Mr Smith had a Homogeneity of birds. But I would say Mr Smith had a homogeneous group of birds.
http://www.merriam-webster.com/dictionary/homogeneous

A: If you look at the definition of menagerie, it isn't specific to an assortment of species, although that is often, or often assumed to be, the case.
It stems from the french ménagerie meaning "the management of a household" or farm or "a place where animals are tended." Though in that paragraph it is admittedly commented that it is predominantly taken to mean a mixture.
To come to the point of your question, the least ambiguous way to phrase what you wish to as far as I can see is to phrase the point differently:

e.g. "Mr. Smith had a flock of identical-looking/seemingly identical ravens."

A: Could you rephrase and still convey the information you intend by stating he had "flock of doppelganger birds"?  This is not one word so (-1) myself, but this verbiage lends fantastic imagery to the sentence imo.

A: Mr. Smith had a monotonous collection of birds.
Monotonous connotes sameness or

wearisome uniformity or lack of variety, as in occupation or scenery (Dictionary.com)

A: The only way you could have a collection of birds that looks exactly the same would be if you made them, i.e., if you cloned them from a single bird. So, let's assume that we can clone birds.
If we can do that, we can have a production run or run of birds. According to Oxford Dictionaries and Merriam-Webster, respectively:

production
run: a
continuous period or spell of producing something; specifically a run
in the manufacture of a product
run: the quantity
of work turned out in a continuous operation, e.g., a press run of
10,000 copies

Okay, so now we've had a run of birds. How can we characterize the results of that run? Well, we could characterize the results as a run or as an edition. From Merriam-Webster:
edition: the whole number of articles of one style put out at one time
This logic leads to the following possible answers to the OP's question:

"Mr. Smith had a run of birds. They all looked exactly the
same." (Must imply the birds being the same w/o second sentence)
"Mr. Smith had an edition of birds. They all looked exactly the
same." (Must imply the birds being the same w/o second sentence)

Both run and edition appear to meet the OP's stated requirements:

*

*They render unnecessary the second sentence in the OP's example.

*They are "words that mean a group of clones, or a collection of virtually identical things."
You have to think of them in futuristic terms, I.e., as applying once we have developed the technology to clone birds.
Note: Logic aside, I still rather like my other answer to the OP's question, but it hasn't gotten much traction -- one up vote and one down vote, for a net zero. :-)

A: You may need to reach into the realm of the figurative to generate the expression you need.
Consider the following metaphors:

"Mr. Smith had a Danto's Gallery of birds. They all looked exactly the same."
"Mr. Smith had an avian Gallery of Indiscernibles. All his birds looked the same."
"Mr. Smith had an Aviary of Indiscernibles. All his birds looked the same."

Arthur Danto was a philosopher who came up with a thought experiment involving a gallery of qualitatively identical red canvases, each painted with a different intention. This hypothetical gallery has come to be called the Gallery of Indiscernibles.
If you don't mind the figurative language or the high-brow reference, you might consider one of the above sentences or variations on them.

A: "Matched set".  This could apply to anything, including animals or any other collection.  It is true that "matched" does not literally imply identical ("a matched set of chess pieces"), but in many cases it does ("matched set of duelling pistols").  I think "matched set of birds" would suggest that they were hatched at the same time from the same parents, and are nearly identical.  If they are truly identical, then you can use "set of identical ___" or similar.

A: "Mr. Smith had a colony of birds."
In that sense a "Colony" is a community of animals of one kind living close together or forming a herd.
For example: Never decide to
remove an established bird colony from its location, this can be very disastrous.


text:
Q: if statement always returning false on string comparison
I have used this code to try and confirm that the user input
  passwords are the same and there is no mismatch, before proceeding to
  the next activity. But the if statement always returns a false. It works fine for hardcoded text, but always returns a false for if. Am I missing something?

private void validate(EditText userPassword, EditText userConfirmPassword){
   String userPasswordtext = userPassword.getEditableText().toString();
  String userConfirmPasswordtext = userConfirmPassword.getEditableText().toString();

    if(userPasswordtext == userConfirmPasswordtext){
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }else{
        Toast a=Toast.makeText(this, "Passwords do not match", Toast.LENGTH_SHORT);
        a.show();
    }
}

A: Use .equals when comparing two strings
if (userPasswordtext.equals(userConfirmPasswordtext)) {


text:
Q: Obtain reference to Object calling superclasses method I am trying to write an abstract class. In that class I have a method which is supposed to access the actual object for which the method is called.
"this" however will only return the "part of the object" that I write myself (the abstract one).
To specify some more:
If the method I was writing had a parameter of the type of my class, what i want looks like this:
public abstract class MyClass {
  public void foo(MyClass invoker) {
    ...
  }
}

The above code would allow me access to the object invoking the method, but it would be tedious to write it like this, since this is supposed to become part of a library I want to supply to others and I cannot know for certain, that the passed argument would in fact be the right object and not some other object of a class derived from MyClass.
Is there a way to invoke something along the lines of getNestingObject() or do I specifically have to give the method a parameter and constantly infer "this" to every call?
Finally, since I am no master in java, a perhaps less obvious question:
Is there a security reason, why the above described concept is flawed? Could someone
with malicious intent abuse that kind of keyword?

A:
I am trying to write an abstract class. In that class I have a method
  which is supposed to access the actual object for which the method is
  called. "this" however will only return the "part of the object" that
  I write myself (the abstract one).

this will return a reference to "the whole" object, not "a part". To proof this, if you cast this reference to a class that is lower in the hierarchy, you can access any property or method of this class using the instance referenced by this.
However, casting the instance referenced by this, would not be a good design practice. Speaking in general terms, you should write a foo method  in MyClass with the general behaviour, and override it with the particular behaviour of each classs. If you want to use the foo method of the parent class, you can invoke it using super.


text:
Q: SwiftUI Tutorial PresentationButton Bug I started to experiment with the new SwiftUI framework, announced on the WWDC 2019 and started the tutorial on https://developer.apple.com/tutorials/swiftui.
Now I came to the point where to connect the Profile to the HomeScreen via the PresentationButton. More precisely I am talking about this section of code in Home.swift:
            .navigationBarItems(trailing:
                PresentationButton(
                    Image(systemName: "person.crop.circle")
                        .imageScale(.large)
                        .accessibility(label: Text("User Profile"))
                        .padding(),
                    destination: ProfileHost()
                )
            )

When I first click on the button the Profile Sheet appears just fine, but when I dismiss it and then click on the button again nothing happens.
Does anyone know why this is the case ?
Thanks in advance

A: It looks like a bug in SwiftUI.
It is probably linked to the fact that onDisappear is never called.
You can verify that by adding
.onAppear{
  print("Profile appeared")
}.onDisappear{
  print("Profile disappeared")
}

to ProfileHost view. It would make sense that an appear should be balanced by a disappear for the dismissal to be complete.
It is possible to work around it by implementing a function that returns a PresentationButton that "depends" on a state variable.
@State var profilePresented: Int = 0
func profileButton(_ profilePresented: Int) -> some View {
  return PresentationButton(
    Image(systemName: "person.crop.circle")
      .imageScale(.large)
      .accessibility(label: Text("User Profile"))
      .padding(),
    destination: ProfileHost(),
    onTrigger: {
      let deadlineTime = DispatchTime.now() + .seconds(2)
      DispatchQueue.main.asyncAfter(deadline: deadlineTime, execute: {
        self.profilePresented += 1
      })
  })
}

And replace
.navigationBarItems(trailing:
      PresentationButton(
          Image(systemName: "person.crop.circle")
              .imageScale(.large)
              .accessibility(label: Text("User Profile"))
              .padding(),
          destination: ProfileHost()
      )
  )

with
.navigationBarItems(trailing: self.profileButton(self.profilePresented))

I highly recommend to not use this "solution" and just report the bug to Apple.

A: The most simple way to solve this issue is by leaving the destination: parameter on its own and have the Image object in the curly braces:
PresentationButton(destination: ProfileHost()) {
    Image(systemName: "person.crop.circle")
        .imageScale(.large)
        .accessibility(label: Text("User Profile"))
        .padding()
}

A: This was fixed in Beta 3.  I also had the same issue, where PresentationButton (now PresentationLink) was only firing once when embedded in .navigationBarItems.

A: This was a bug resolved in Xcode 11 Beta2: https://developer.apple.com/documentation/xcode_release_notes/xcode_11_beta_2_release_notes.
With the updated API the following should work:
PresentationButton(destination:ProfileHost()) {
    Image(systemName: "person.crop.circle")
    .imageScale(.large)
    .accessibility(label: Text("User Profile"))
    .padding()
}


text:
Q: AJAX OPEN in FirefoxDeveloperEdition fails to work like firefox or chrome Please tell how the APP ID is involved and how it can be changed.
I have been working on Ajax. The application, all in javascript at the client, works great on firefox, safari, and chrome, but not on FirefoxDeveloperEdition.
The issue is at exactly the request.open statement. It does not work on FirefoxDeveloperEdition. In the console I get the error ":" --- that is all, just the colon. As I said, that statement works perfectly on Firefox. I have the most recent version of all apps.
The selection of XMLHttpRequest is working the same in both Firefox and FirefoxDeveloperEdition. Either FirefoxDeveloperEdition is not backward compatible or not meant to be, and I cannot tell which.
Help desired.
D


text:
Q: fourth rank tensor for stress energy The Weyl tensor equates the Riemann tensor in vacuum
$$ C_{\mu \nu \eta \lambda} = R_{\mu \nu \eta \lambda} $$
So it makes me wonder about the tensor
$$T_{\mu \nu \eta \lambda} = C_{\mu \nu \eta \lambda} - R_{\mu \nu \eta \lambda} $$
and how it relates to the 2nd-rank stress-energy tensor $T_{\mu \nu}$. In particular, both tensors are zero and non-zero in the same domains, so they must be related. In the other hand, general relativity says that matter affects geometry only through the 2nd-rank tensor, so in theory no higher rank tensor should contain more information about the matter fields than what it (the 2nd-rank tensor) already does
I'm trying to figure out if the 4th rank tensor can be interpreted or not as containing more information about the energy-matter fields or if the extra degrees of freedom are strictly geometric. The question is relevant for considering alternative formulations of the matter curvature relationship that tend to the Einstein equation in some sensible limit

A: This object is related to the Schouten tensor,
$$S_{ab} = \frac{1}{n-2}\left(R_{ab} - \frac{R}{2(n-1)} g_{ab}\right).$$
We find
$${C_{ab}}^{cd} - {R_{ab}}^{cd} = -4 S_{[a}^{[c} \delta_{b]}^{d]}.$$
As @Luboš Motl mentions, this tensor depends only on the Ricci tensor and scalar curvature.
That is, it doesn't "know" any more than Ricci---on the geometry side it is nothing new.
It doesn't make sense to ask how this is related to $T_{ab}$ without the Einstein equations or some explicit "alternative formulation."
If the Einstein equations can be assumed it is a straightforward exercise to work it out using
$R = -\frac{2}{n-2} 8\pi T$
and
$R_{ab} = 8\pi(T_{ab} - \frac{1}{n-2} g_{ab}T)$.

A: One may simply calculate and simplify your tensor $T_{4}$. Following the definition of the Weyl tensor, it's obvious that your
$$ T_{abcd} = -\frac{2}{n-2} (g_{a[c}R_{d]b} - g_{b[c}R_{d]a}) + \frac{2}{(n-1)(n-2)} R g_{a[c} g_{d]b} $$
so even without using any equations of motion, your tensor is a function of the Ricci tensor only (and the Ricci scalar which is the trace of the Ricci tensor, anyway). So indeed, in the vacuum where the Ricci tensor vanishes by Einstein's equations without a right hand side, your tensor vanishes, too.
It's completely illogical to call this tensor a "generalization of the stress-energy tensor" because as you defined it, it depends on the metric and its derivatives only. You may also replace the Ricci tensor in the formula above by the appropriate multiple of the stress-energy tensor (with the inverted trace), using Einstein's equations. Then, you will see that $T$ with four indices may indeed be obtained from objects such as $T_{ab} g_{cd}$.
But what it would be good for? If your question is whether this object is natural, useful, or justified by something, my answer is No. Nevertheless, if you're excited by various other fields with 4 indices and symmetries of the Riemann tensor, you may want to read the following 2000 paper by Chris Hull (page 10 and so on):

http://arxiv.org/abs/hep-th/0011215


text:
Q: Dynamic value passing in Postgres Here is a complex query where i need to pass some dates as dynamic to this, As of now i have hardcoded this '2021-08-01' AND '2022-07-31' these 2 dates.
But i have to pass this dates dynamically in such a way that next dates ie, 2022-06 month , thew dates passed will be '2021-07-01' and '2022-06-30' , basically 12 months behind data.
if we take 2022-05 then the passed date should be '2021-06-01' and '2022-05-31'.
How can we achieve this ? Any suggestions or help will be much appreciated.
below is the query for reference
WITH base as
(
SELECT created_at as period ,order_number, TRIM(email) as email ,is_first_order
FROM  orders
WHERE created_at::DATE BETWEEN '2021-08-01' AND '2022-07-31'
)
,base_agg as
(
select TO_CHAR(period,'YYYY-MM') as period
    ,COUNT(DISTINCT email)FILTER(WHERE is_first_order IS TRUE) as new_users
    ,COUNT(DISTINCT order_number)FILTER(WHERE is_first_order IS FALSE) as returning_orders
FROM base
       GROUP BY 1
)
,base_cumulative as
(
SELECT ROW_NUMBER() OVER(ORDER BY PERIOD DESC ) as rno
      ,period
      ,new_users
      ,returning_orders
      ,sum("new_users")over (order by "period" asc rows between unbounded preceding and current row) as "cumulative_total"
from base_agg
 )

  SELECT
    (SELECT period FROM base_cumulative WHERE rno=1) period
   ,(SELECT cumulative_total FROM base_cumulative WHERE rno=1) as cumulated_customers
   ,SUM(returning_orders) as returning_orders
   ,SUM(returning_orders)/NULLIF((SELECT cumulative_total FROM base_cumulative WHERE rno=1),0)  as  rate
 FROM base_cumulative

A: You can calculate the end of current month based on NOW() and some logic, the same can be applied with the rest of the calculation
select date_trunc('month', now())::date + interval '1 month - 1 day' end_of_this_month,
    date_trunc('month', now())::date + interval '1 month - 1 day'::interval - '1 year'::interval + '1 day'::interval first_day_of_prev_year_month
    ;

Result
  end_of_this_month  | first_day_of_prev_year_month
---------------------+------------------------------
 2022-08-31 00:00:00 | 2021-09-01 00:00:00
(1 row)


text:
Q: Фильтрация по категориям. JavaScript Доброго времени суток!
Есть массив объектов. Фильтрация происходить через добавление класса.
Но почему-то прячутся те объекты, которые должны оставаться. И оператор "!=" не помогает.
Подскажите что делаю не так.

'use strict';

let filters = document.querySelectorAll('a[data-filter]');

for (let filter of filters) {
  filter.addEventListener('click', function(e) {
    e.preventDefault();

    let catId = filter.getAttribute('data-filter');
    let workCat = document.querySelectorAll('.portfolio__col[data-cat="' + catId + '"]');

    workCat.forEach(function(i) {

      if (workCat !== catId) {
        i.classList.add('hide');
      } else {
        i.classList.remove('hide');
      }

    })

  });
}

Робочий вариант!
' может кому поможет =) '

let filters = document.querySelectorAll('a[data-filter]');

for (let filter of filters) {
  filter.addEventListener('click', function(e) {
    e.preventDefault();

    let catId = filter.getAttribute('data-filter');
    let workCat = document.querySelectorAll('.portfolio__col');

    workCat.forEach(function(c) {

      if (catId === 'all') {
        c.classList.remove('hide');
      } else {
        if (c.getAttribute('data-cat') !== catId) {
          c.classList.add('hide');
        } else {
          c.classList.remove('hide');
        }
      }

    })

  }); /* end listener*/
}
.portfolio__col {
  display: inline-block;
  margin: 10px;
  width: 150px;
}

.hide {
  display: none;
}

  All
  App
  Websites
  Interaction

category: interaction

category: app

category: websites

category: app

category: interaction

category: websites

A: *

*Всегда добавляйте в вопрос разметку и код таким образом, чтобы можно было воспроизвести проблему. (Если Вы выкладываете просто код - велика вероятность, что Вам не скоро ответят или не ответят вообще).

*workCat у Вас возвращает лишь один объект, который соответствует нажатому id.

*Не используйте в функции forEach переменную i. Это не запрещено, но сами потом можете запутаться при других операциях.

*Чтобы реализовать задуманное ищете не один, а все элементы с данном классом.
Пример:

    let filters = document.querySelectorAll('a[data-filter]');
    for (let filter of filters) {
        filter.addEventListener('click', function(e) {
            e.preventDefault();

            let catId = filter.getAttribute('data-filter');
            let workCat = document.querySelectorAll('.portfolio__col[data-cat="' + catId + '"]');
            let alldivs = document.querySelectorAll('.portfolio__col');

            alldivs.forEach(function (c) {
                if (c.getAttribute('data-cat') == catId){
                    c.classList.add('hide');
                } else {
                    c.classList.remove('hide');
                }
            })
        });
    }
    .class{
        color: #b61924;
    }
    .hide{
        display: none;
    }
123

CAT123

125

CAT125

126

CAT126

127

CAT127


text:
Q: Why does this RX-X lock not appear in Extended Events? The Problem
I have a pair of queries that, under serializable isolation, cause an RX-X lock. However, when I use Extended Events to watch lock acquisition, the RX-X lock acquisition never appears, it is only released. Where does it come from?
The Repro
Here's my table:
CREATE TABLE dbo.LockTest (
ID int identity,
Junk char(4)
)

CREATE CLUSTERED INDEX CX_LockTest --not unique!
ON dbo.LockTest(ID)

--preload some rows
INSERT dbo.LockTest
VALUES ('data'),('data'),('data')

Here's my problem batch:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

BEGIN TRAN

INSERT dbo.LockTest
VALUES ('bleh')

SELECT *
FROM dbo.LockTest
WHERE ID = SCOPE_IDENTITY()

--ROLLBACK

I check locks held by this session, and see RX-X:
SELECT resource_type, request_mode, request_status, resource_description
FROM sys.dm_tran_locks
WHERE request_session_id = 72 --change SPID!

But I also have an Extended Event on lock_acquired and lock_released. I filter it on the appropriate associated_object_id...there's no RX-X.

After executing the rollback, I see RX-X (LAST_MODE) released, even though it was never acquired.

What I've Tried

*

*I looked at all locks in Extended Events - no filtering. No RX-X locks acquired.

*I also tried Profiler: same results (except of course it gets the name right...no "LAST_MODE").

*I ran the XE for lock escalations - it's not there.

*There's no XE specifically for conversions, but I was able to confirm that at least the U to X lock conversion is captured by lock_acquired
Also of note is the RI-N that gets acquired but never released. My current hypothesis is that the RX-X is a conversion lock, as described here. There are overlapping key-range locks in my batch that look like they should qualify for conversion, but the RX-X lock isn't in the conversion table.
Where is this lock coming from, and why isn't it picked up by Extended Events?

A: The single row insert acquires an X (exclusive) lock on the new row.
The SELECT attempts to acquire a range-shared, key shared (RangeS-S) lock.
This request is reported by the lock_acquired Extended Event as mode = RS_S.
It is reported by the Profiler event class Lock:Acquired as mode 13 (LCK_M_RS_S).
The requested mode is combined with the existing exclusive lock mode in Lock::CalculateGrantMode in sqlmin.dll. There is no combined mode of range-shared, key exclusive (RangeS-X) so the outcome of the calculation is range-exclusive, key exclusive (RangeX-X), which happens to be mode 15.
The grant mode calculation above is performed just before the extended event is generated by lck_ProduceExtendedEvent<XeSqlPkg::lock_acquired>. Nevertheless, both Profiler and Extended Events log the requested RangeS-S mode, not the resulting lock mode RangeX-X. This is counter to the limited documentation, which says:

Mode | int | Resulting mode after the lock was acquired.

The mode column of the extended event has no documentation at all, and the description in the meta data is blank. Perhaps Microsoft themselves weren't even sure of the behaviour.
I have often thought it would be more useful if lock events reported both the requested and resulting modes, but that is not what we have. The current arrangement makes it pretty much impossible to track and match up lock acquisition and release.
There might be a good reason for reporting locks this way. If it doesn't meet your needs, you could open a support case with Microsoft, or create an Azure Feedback item.

LAST_MODE
The mysterious LAST_MODE is something Erik Darling has remarked on before. It is the highest map_key value in the list of lock modes exposed by sys.dm_xe_map_values:
SELECT
    DXMV.map_key,
    DXMV.map_value
FROM sys.dm_xe_map_values AS DXMV
WHERE
    DXMV.[name] = N'lock_mode'
ORDER BY
    DXMV.map_key;

╔═════════╦═══════════╗
║ map_key ║ map_value ║
╠═════════╬═══════════╣
║       0 ║ NL        ║
║       1 ║ SCH_S     ║
║       2 ║ SCH_M     ║
║       3 ║ S         ║
║       4 ║ U         ║
║       5 ║ X         ║
║       6 ║ IS        ║
║       7 ║ IU        ║
║       8 ║ IX        ║
║       9 ║ SIU       ║
║      10 ║ SIX       ║
║      11 ║ UIX       ║
║      12 ║ BU        ║
║      13 ║ RS_S      ║
║      14 ║ RS_U      ║
║      15 ║ RI_NL     ║
║      16 ║ RI_S      ║
║      17 ║ RI_U      ║
║      18 ║ RI_X      ║
║      19 ║ RX_S      ║
║      20 ║ RX_U      ║
║      21 ║ LAST_MODE ║
╚═════════╩═══════════╝

The memory structure accessed via the DMV (using sqlmin!CMapValuesTable) is stored starting at the address sqlmin!XeSqlPkg::g_lock_mode. Each 16-byte entry in the structure contains the map_key and a pointer to the string returned as map_value by the streaming TVF.
The strings are stored exactly as shown in the table above (though not in that order). It seems to be an error that entry 21 has a map_value of "LAST_MODE" instead of the expected "RX_X". Erik Darling has reported the issue on Azure Feedback.


text:
Q: cakephp hasmany relations give error I have a database with some relations.
I have two tables in this example:
activity_ingredients   ingredient_aliases
---------------        ---------------
id                     id
ingredient_id          ingredient_id

I want to make a conditions into my model to connect the tables by the field "ingredient_id". I have done in this mode:
class ActivityIngredients extends AppModel{
        public $name = 'ActivityIngredients';
        public $useTable = 'activity_ingredients';

        public $hasMany = array (
        'IngredientAlias' => array (
            'className'     => 'IngredientAlias',
            'foreignKey'   => false,
            'conditions' => array('ActivityIngredients.ingredient_id = IngredientAlias.ingredient_id')
        )
        );
    }

class IngredientAlias extends AppModel {

    public $name = 'IngredientAlias';
    public $useTable = 'ingredient_aliases';
    public $belongsTo = array(
         'ActivityIngredients' => array(
            'className'    => 'ActivityIngredients',
            'foreignKey'   => false
        )

    );
}

If I write this code give me an error like this:

Column not found: 1054 Unknown column 'ActivityIngredients.ingredient_id' in 'where clause'

But if Instead of hasMany I write hasOne it doesn't return any error and is perfect. But my relation is hasMany.. why?
To retrieve data I make a query into my UserController.
User is associated with Activity with hasMany, Activity is associated with ActivityIngredients in this mode:
public $hasOne = array(
            'ActivityIngredients' => array(
                'className' => 'ActivityIngredients',
                'conditions' => '',
                'dependent' => true,
                'foreignKey'   => 'activity_id'
            )

To retrieve data I'm using this query at the moment but I think that I have to change all query now
$this->User->Activity->recursive = 2;
        $activity = $this->User->Activity->findAllByUser_id($id);
        $this->set('activity', $activity);

A: The first thing you should use a singular word while defining model class. It means that the model name should be ActivityIngredient instead of ActivityIngredients.
Although if in activity_ingredients table if ingredient_id id is a foreign key that belongs to ingredient_aliases table. Then it should be named as ingredient_alias_id. Similiarly if you would do this same in ingredient_aliases table, i.e. the foreign key name would be activity_ingredient_id. Then there will be no problem at all.
However, I am giving a solution to your problem. Kindly check and verify.
Then your code should looks like:
class ActivityIngredient extends AppModel{
    public $name = 'ActivityIngredient';
    public $useTable = 'activity_ingredients'; // if you use singular term then no need to define $useTable

    public $hasMany = array (
    'IngredientAlias' => array (
        'className'     => 'IngredientAlias',
        'foreignKey'   => false,
        'finderQuery' => 'select * from ingredient_aliases as `IngredientAlias`
                          where `IngredientAlias`.`ingredient_id` = {$__cakeID__$}'
                               )
    );
}

class IngredientAlias extends AppModel {

    public $name = 'IngredientAlias';
    public $useTable = 'ingredient_aliases';
    public $belongsTo = array(
                      'ActivityIngredient' => array(
                                   'className'    => 'ActivityIngredient',
                                   'foreignKey'   => 'ingredient_id'
                                                   )
                             );
}

A: you have used
conditions' => array('ActivityIngredients.ingredient_id = IngredientAlias.ingredient_id')
it should be
conditions' => array('ActivityIngredients.ingredient_id => IngredientAlias.ingredient_id')
Use below code
            public $hasMany = array (
            'IngredientAlias' => array (
                'className'     => 'IngredientAlias',
                'foreignKey'   => false,
                conditions' => array('ActivityIngredients.ingredient_id => IngredientAlias.ingredient_id')
            )
            );
        }

    class IngredientAlias extends AppModel {

        public $name = 'IngredientAlias';
        public $useTable = 'ingredient_aliases';
        public $belongsTo = array(
             'ActivityIngredients' => array(
                'className'    => 'ActivityIngredients',
                'foreignKey'   => false
            )

        );
    }
    ?>


text: Q: Как скомпилировать TOR.exe на windows 7, чтоб был доступ к файлу конфигурации or.h? У меня есть tor.exe, хочу понять как "привязать" к нему файл конфигурации or.h, чтоб была возможность более тонко настраивать соединения


text:
Q: How to Autostart Youtube VIDEO with Low Volume (iframe) This is the iframe I create to autostart a video (music, mostly) in my blog :

It's all perfect. The only problem is the Audio, because the Volume is too high and I would decrease it-
So I added this part on my code : "&player.setVolume(5)"
The final code, then, is this one:

The problem is that it wont works and the Volume is still the deafault one-
(but the code still works with autoplay and all other pref).
What is going wrong?

A: In IFrame API reference, you can use player.setVolume() to set the volume after the player is ready.
If you want to control the volume, you have to write some code in Javascript:
function onYouTubeIframeAPIReady() {
  // iframeId parameter should match your Iframe's id attribute
  var player = new YT.Player('iframeId', {
    width: 140,
    height: 105,
    videoId: 'tGzl_AB4poI',
    events: {
      'onReady': function (event) {
        event.target.setVolume(0);
        event.target.playVideo();
      }
    }
  });
}


text:
Q: java.lang.RuntimeException: java.lang.ClassCastException: [B cannot be cast to java.lang.String I am encountering this error while running storm topology in local mode.
I have a simple program which checks whether a number is prime or not.
I am using KafkaSpout as the source and storm for processing it.
Kafka version 2.10-0.8.2.1
storm version 0.9.4
zookeeper 3.4.6
Below is my bolt which checks the prime number
public class PrimeNumberBolt extends BaseRichBolt
{
    private static final long serialVersionUID = 1L;
    private OutputCollector collector;

    public void prepare( Map conf, TopologyContext context, OutputCollector collector )
    {
        this.collector = collector;
    }

    public void execute( Tuple tuple )
    {
        //System.out.println(tuple.getFields());
        //System.out.println(tuple.getString(0));
        String num = tuple.getString(0);
        //int number = tuple.getInteger( 0 );
        int number = Integer.parseInt(num);
        //System.out.println("IN Primenumber bolt = "+number);

        if( isPrime( number) )
        {
            System.out.println( number );

        }
        collector.ack( tuple );
    }

    public void declareOutputFields( OutputFieldsDeclarer declarer )
    {
        declarer.declare( new Fields( "number" ) );
    }

    private boolean isPrime( int n )
    {
        if( n == 1)
        {
            return false;
        }
        if( n == 2 || n == 3 )
        {
            return true;
        }

        // Is n an even number?
        if( n % 2 == 0 )
        {
            return false;
        }

        //if not, then just check the odds
        for( int i=3; i*i<=n; i+=2 )
        {
            if( n % i == 0)
            {
                return false;
            }
        }
        return true;
    }
}

Error :
 **18156 [Thread-11-prime] ERROR backtype.storm.util - Async loop died!
java.lang.RuntimeException: java.lang.ClassCastException: [B cannot be cast to java.lang.String**
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:128) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.daemon.executor$fn__3439$fn__3451$fn__3498.invoke(executor.clj:748) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.util$async_loop$fn__460.invoke(util.clj:463) ~[storm-core-0.9.4.jar:0.9.4]
    at clojure.lang.AFn.run(AFn.java:24) [clojure-1.5.1.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String
    **at backtype.storm.tuple.TupleImpl.getString(TupleImpl.java:112) ~[storm-core-0.9.4.jar:0.9.4]
    at com.geekcap.storm_test.PrimeNumberBolt.execute(PrimeNumberBolt.java:40) ~[classes/:na]**
    at backtype.storm.daemon.executor$fn__3439$tuple_action_fn__3441.invoke(executor.clj:633) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.daemon.executor$mk_task_receiver$fn__3362.invoke(executor.clj:401) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.disruptor$clojure_handler$reify__1445.onEvent(disruptor.clj:58) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125) ~[storm-core-0.9.4.jar:0.9.4]
    ... 6 common frames omitted
**18158 [Thread-11-prime] ERROR backtype.storm.daemon.executor -
java.lang.RuntimeException: java.lang.ClassCastException: [B cannot be cast to java.lang.String**
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:128) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.utils.DisruptorQueue.consumeBatchWhenAvailable(DisruptorQueue.java:99) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.disruptor$consume_batch_when_available.invoke(disruptor.clj:80) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.daemon.executor$fn__3439$fn__3451$fn__3498.invoke(executor.clj:748) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.util$async_loop$fn__460.invoke(util.clj:463) ~[storm-core-0.9.4.jar:0.9.4]
    at clojure.lang.AFn.run(AFn.java:24) [clojure-1.5.1.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
**Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String**
    at backtype.storm.tuple.TupleImpl.getString(TupleImpl.java:112) ~[storm-core-0.9.4.jar:0.9.4]
    at com.geekcap.storm_test.PrimeNumberBolt.execute(PrimeNumberBolt.java:40) ~[classes/:na]
    at backtype.storm.daemon.executor$fn__3439$tuple_action_fn__3441.invoke(executor.clj:633) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.daemon.executor$mk_task_receiver$fn__3362.invoke(executor.clj:401) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.disruptor$clojure_handler$reify__1445.onEvent(disruptor.clj:58) ~[storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.utils.DisruptorQueue.consumeBatchToCursor(DisruptorQueue.java:125) ~[storm-core-0.9.4.jar:0.9.4]
    ... 6 common frames omitted
18375 [Thread-11-prime] ERROR backtype.storm.util - Halting process: ("Worker died")
java.lang.RuntimeException: ("Worker died")
    at backtype.storm.util$exit_process_BANG_.doInvoke(util.clj:325) [storm-core-0.9.4.jar:0.9.4]
    at clojure.lang.RestFn.invoke(RestFn.java:423) [clojure-1.5.1.jar:na]
    at backtype.storm.daemon.worker$fn__4693$fn__4694.invoke(worker.clj:491) [storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.daemon.executor$mk_executor_data$fn__3272$fn__3273.invoke(executor.clj:240) [storm-core-0.9.4.jar:0.9.4]
    at backtype.storm.util$async_loop$fn__460.invoke(util.clj:473) [storm-core-0.9.4.jar:0.9.4]
    at clojure.lang.AFn.run(AFn.java:24) [clojure-1.5.1.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]

Please suggest me the modifications i need to do in the code.Thanks in Advance !!

A: It seems like your kafka spout read data in byte array format.
Try to use String Scheme by setting spoutconfig.scheme like below.
spoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme());


text:
Q: Getting the last commit ID via a curl command to a git repo URL How can I invoke the URL https://git.appfactorypreview.wso2.com/history/apiapp.git/ as shown in the documentation http://developer.github.com/v3/repos/commits/? I mean, what is the CURL command that I have to give?

A: The github REST api is not for git, its for github.com only.  git is a distributed version control system while github.com is a source code hosting service.
The repo url you have given is not from github. So github API will not work here. What you can do is clone the repo in a directory and invoke git log -n 1


text:
Q: Using strstr() to exclude values in excel while not shifting cells up I am working in PHP using strstr() to remove values which are extracted from a MYSQL db to be outputted to an excel file-
CODE:
        If (!strstr($value, '<script>')){
       $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);

           $row++;
        }

This code excludes the columns that contain a <script> tag. However it shifts the contents of the cells up like so:
=====================================
|Question          |  Answer        |
=====+========+===============+=====|
|   Male/female    |                |
|----+--------+---------------+-----|
|                  |      F         |
|----+--------+---------------+-----|

Instead I would like it to skip the rows  like so:
=====================================
|Question          |  Answer        |
=====+========+===============+=====|
|                  |                |
|----+--------+---------------+-----|
|   Male/female    |      F         |
|----+--------+---------------+-----|

A: Your code is written so that the row is only incremented if your script tag is not found.  However, it sounds like you want to unconditionally increment; if that's the case, then move $row++ to outside the if statement, like so:
if (!strstr($value, '<script>')){
    $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
}
$row++;

If this isn't what you were looking for, then please provide a sample input that can be matched to the output, as this would make what you need crystal clear.


text:
Q: Is it reasonable to isolate iPhone/iPad event handlers in separate .m files and then #import them in the viewcontroller @implementation? Total newbie here on iPhone/iPad development, so forgive me if this seems like a strange question.
Given that most objects (or group of objects) in a view within a UIViewController need to have an event callback defined, would it seem reasonable to group the callbacks into separate .m files and then #import them after the @implementation of the viewcontroller?
This way, the standard methods, initWithNibName:, -viewDidLoad, shouldAutoRotateInterfaceOrientation:, didReceiveMemoryWarning:, -viewDidUnload and dealloc (as provided by Xcode) would be the only methods defined in your viewcontroller.m file.  The viewcontroller.m file would not become this monolithic monstrosity of event callbacks and would be simpler to maintain.  I'm thinking you put them after your @synthesize outlets.
Thoughts?

A: While it may seem like you are making a monolithic file, the ViewController is really the place for all of this stuff.  If you do what you propose (which is entirely possible), you will end up with a bunch of files that do little.
One way to keep organized in a large file is to separate groups of methods with pragma marks like so:
#pragma mark lifecycle methods

-(void)dealloc{}
-(id)init{}
-(id)initWithCoder:

#pragma mark target-action

-(id)doSomethingAction:(id)sender{}
-(id)doSometingElse:(id)sender{}

Xcode will parse the pragma marks and group the methods for you in the pull down item bar for easy access.  Notice that the methods in this list are also listed in alphabetical order.

A: here's an illustration of one alternative, this uses an objc category:
/* File: Header A */
@interface MONViewController : NSViewController
{
    unsigned anIvar;
}

@property (nonatomic, readonly) unsigned anIvar;

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle;
- (void)dealloc;

- (void)viewDidLoad;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation;

/* (continued) */

@end

/* File: Header A or Header B, depending on how you want to organize it */

@interface MONViewController (EventCallbacks)

- (IBAction)triviaButtonWasPressed:(id)sender;

/* (continued) */

@end

/* File: Imp A */
@implementation MONViewController

- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle { /* ... */ }
- (void)dealloc { /* ... */ }
- (unsigned)anIvar { /* ... */ }

- (void)viewDidLoad { /* ... */ }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { /* ... */ }

/* (continued) */

@end

/* File: Imp A or Imp B, depending on how you want to organize it */

@implementation MONViewController (EventCallbacks)

- (IBAction)triviaButtonWasPressed:(id)sender { /* ... */ }

/* (continued) */

@end

fortunately, the compiler verifies that you've defined all your declarations when a category is defined, as is performed in a class. some things must be defined in the proper class implementation, such as protocols.
be careful if you divide this into a ton of smaller files - your build times can really suffer. also, it's somewhat inevitable in this case (since your subclassing) but scalability issues in this regard should serve as reminders that your interfaces/classes are attempting to do too much, and should be divided into smaller components. good luck!

A: The issue I see with separating them out is that most of the callbacks will have to work with class local variables, and it's just handier to have them declared in the corresponding header file for the @implementation you are working with.  To me it makes more sense to keep event handling stuff in the view controller, and move any other functionality left out into some separate file...
But anything you break out may have to use the same class instance variables as well, meaning that you may have to make some class variables public you might not otherwise.
The category breakout Justin presented solves that issue but to me, using class instance variables you cannot technically "see" just seems weird.


text:
Q: Derivative of matrix w.r.t. its own vectorized version I am unable to find what would be the derivative of a $m \times m$ real matrix $A$ with respect to $(\mathrm{vec}(A))^T$ (where $T$ is transpose and $\mathrm{vec}$ stacks the columns) without using tensors (i.e. remaining in 2d notation). I assume it would involve the Kronecker product, but is there a straightforward answer, or a convention?

A: $\def\bb{\mathbb}$
You don't want to use tensors, but they can be quite illuminating.
A matrix and its vectorized form are related by
$$a = {\rm vec}(A) \quad\iff\quad A={\rm Mat}(a)$$
This can alternatively be written using third-order
$\bb V$ectorization/$\bb M$atricization tensors and single/double dot products
$$\eqalign{
a &= \bb V:A \quad\iff\quad &A=\bb M\cdot a \\
a &= A:\bb M \quad\iff\quad &A=a\cdot\bb V \\
}$$
The gradient of a matrix with respect to itself yields the fourth-order identity tensor
$$\frac{\partial A}{\partial A} = \bb E\quad\implies\quad X =(\bb E:X)=(X:\bb E)$$
just as the gradient of a vector wrt itself yields the second-order identity matrix
$$\frac{\partial a}{\partial a} = I\quad\implies\quad x =(I\cdot x)=(x\cdot I)$$
Using these tensors, one can write the vector-by-vector, matrix-by-vector, and vector-by-matrix gradients in terms of the matrix-by-matrix gradient.
$$\eqalign{
\frac{\partial a}{\partial b}
  &= \frac{\partial(\bb V:A)}{\partial(B:\bb M)}
  &= \bb V:&\left(\frac{\partial A}{\partial B}\right):\bb M \\
\frac{\partial A}{\partial b}
  &= \frac{\partial A}{\partial(B:\bb M)}
  &= &\left(\frac{\partial A}{\partial B}\right):\bb M \\
\frac{\partial a}{\partial B}
  &= \frac{\partial(\bb V:A)}{\partial B}
  &= \bb V:&\left(\frac{\partial A}{\partial B}\right) \\
}$$
Combining the above ideas yields
$$\eqalign{
\frac{\partial A}{\partial a}
  &= \left(\frac{\partial A}{\partial A}\right):\bb M
  &= (\bb E):\bb M  = \bb M \\
\frac{\partial a}{\partial A}
  &= \bb V:\left(\frac{\partial A}{\partial A}\right)
  &= \bb V:(\bb E)  = \bb V \\
}$$
So how are these tensors defined?
For matrices in $\;\bb R^{m\times n}\;$ they are
$$\eqalign{
\bb V_{\ell jk} &= \begin{cases}
1\quad{\rm if}\;\;\ell+m=j+mk \\
0\quad{\rm otherwise} \\
\end{cases}
\\
\bb M_{jk\ell} &= \begin{cases}
1\quad{\rm if}\;\;j-1={\rm div}(\ell-1,n)\;\;\&\;\;k-1={\rm mod}(\ell-1,n) \\
0\quad{\rm otherwise} \\
\end{cases}
\\
\bb E_{jkpq} &= \begin{cases}
1\quad{\rm if}\;\;j=p\;\;\&\;\;k=q \\
0\quad{\rm otherwise} \\
\end{cases}
\\
I_{jp} &= \begin{cases}
1\quad{\rm if}\;\;j=p \\
0\quad{\rm otherwise} \\
\end{cases}
\\
}$$
and the index ranges are
$$\eqalign{
1&\le\; j,p  \;&\le m
 &\qquad\big({\rm the}\,row\;{\rm index}\big) \\
1&\le\; k,q  \;&\le n
 &\qquad\big({\rm the}\,column\;{\rm index}\big) \\
1&\le\; \ell \;&\le m\!\cdot\!n
 &\qquad\big({\rm the}\,long\;{\rm index}\big) \\
}$$
In some sense the third-order tensors are the more fundamental quantities,
since given $\big(\bb M,\bb V\big)$
the remaining tensors can be calculated as
$$\eqalign{
\bb E &= \bb M\cdot\bb V
  \qquad&\big({\rm contract\,over\,long\,index}\big) \\
I &= \bb V:\bb M
  \qquad&\big({\rm contract\,over\,row/column\,indexes}\big) \\
}$$
Similarly, $I$ is more fundamental than $\bb E$ since
$$\eqalign{
{\bb E}_{jkpq} &= I_{jp}I_{kq} \\
}$$
Also note that you only need to calculate one of the fundamental tensors,
since they are equal after a cyclic rotation of the indexes
$$\eqalign{
{\bb M}_{jk \ell} &\doteq {\bb V}_{\ell jk} \\
}$$
The definition of $\bb V$ being somewhat simpler, is usually the tensor
which is chosen.

A: Writing row $k$ of $\mu$ as a row vector $\mu_{k}$, we obtain
$$\partial_{\mathrm{vec}(\mu)^T}\mu
=\left[\matrix{
\partial_{\mathrm{vec}(\mu)^T}\mu_1 \\
\partial_{\mathrm{vec}(\mu)^T}\mu_2 \\
\vdots \\
\partial_{\mathrm{vec}(\mu)^T}\mu_m \\
}\right]
=\left[\matrix{
\partial_{\mathrm{vec}(\mu)^T}\mu_{11} & \dots & \partial_{\mathrm{vec}(\mu)^T}\mu_{1m} \\
& \vdots \\
\partial_{\mathrm{vec}(\mu)^T}\mu_{m1} & \dots & \partial_{\mathrm{vec}(\mu)^T}\mu_{mm} \\
}\right]
=[I_mI_m \dots I_m]$$
where the last display is a block matrix of $m$-by-$m$ identity matrices.


text:
Q: How to avoid merging in R I have two vectors, arg1 and arg2 and a data frame df.
arg1 <- c(1, 1, 2, 2)
arg2 <- c(1, 2, 1, 2)

df <- data.frame(a <- c(1, 1, 2, 2, 3, 3, 4, 4))

I want to include the informations of arg1 and arg2 in my data frame but without merge.
The key assignment, here, is to link the first value of arg1 or arg2 with the value 1 of a, the second value of arg1 or arg2 with the value 2 of a, etc..
final output:
df <- data.frame(a = c(1, 1, 2, 2, 3, 3, 4, 4),
             d = c(1, 1, 1, 1 ,2, 2, 2, 2),
             e = c(1, 1, 2, 2, 1, 1, 2, 2))

If I was in the case of unicity of arg1 and arg2, I would do:
df$d <- as.character(factor(a, labels = arg1))

The classic way I think to do it is to convert arg1 and arg2 as a dataframe and merge with df. But this solution seems a bit heavy. Is there a way to do it just with vector assignment?

A: You can make use of factors stored as integers:
i <- as.integer(factor(df$a, levels = unique(df$a)))
cbind(df,
      d = arg1[i],
      e = arg2[i])
#  a d e
#1 1 1 1
#2 1 1 1
#3 2 1 2
#4 2 1 2
#5 3 2 1
#6 3 2 1
#7 4 2 2
#8 4 2 2

I assume that there may be different values than 1:4 in column a and in that case this would match the first unique value in a to the first value in arg1 and arg2, respectively.

As @A.Webb notes in the comments, it would be even easier to use
i <- match(df$a,unique(df$a))

instead of converting to factor and integer.

A: We can use Map
do.call(rbind, Map(cbind, split(df$a, df$a),
               d=arg1, e= arg2))

Or using dplyr
library(dplyr)
df %>%
    mutate(d=arg1[a], e= arg2[a])

Or with data.table
library(data.table)
setDT(df)[, c('d', 'e') := list(a,arg1[.GRP], arg2[.GRP]) ,.(a)]


text:
Q: Div Screenshot with Javascript and html2canvas.js partially working Am trying to capture screenshot of an image inside div elements and everything works fine as long as there is static image inside the div elements as per code below. it displays the right base64 image conversion

Here is my issue. Now Am trying to upload image from a file input and display it on a preview inside the div elements and then capture the uploaded image as screenshot.
The Image is showed on the preview but when I try to capture it as screenshot, its not displaying the right base64 image conversion .
Is the problem because of the fact the uploaded image is not loaded first as the page loads
here is the code below

    <input type="file" accept="image/*" onchange="loadFile(event)">

here is the entire code

or

      <input type="button" id="but_screenshot" value="Take screenshot" class="testbn">

    <input type="file" accept="image/*" onchange="loadFile(event)">

A: The output of canvas.toDataURL() must be set as the src attribute of an image.
You can not just add it to a
.
It should work if you change your

 to an image, eg  and then set document.getElementById("demo_pic").src = dataURL.
Here is a working fiddle.
http://jsfiddle.net/2pha/32o6es8a/


text:
Q: Intended behavior of required=true in composite component? I'm a little bit confused about the rquired="true" attribute in a composite components.
<composite:interface>
  <composite:attribute name="value" required="true" />
</composite:interface>

<composite:implementation>
    <h:outputText value="Value: '#{cc.attrs.value}'" />
</composite:implementation>

I'm expecting an error while using this composite without value like this <my:test/>, but the code will be rendered without any error or warning! I'm using Mojarra-2.1.19-jbossorg-1 and tested this issue with @Named @ViewScoped and @SeesionScoped beans.
This is nearly the opposite than Composite component required attribute throws exception in Mojarra 2.0.3, but there is actually asked about the behavior of value="".


text:
Q: Looking for words or phrases to fit the idea of this form of hierarchy I'm using text as follows to categorize some information. It goes from the general to the specific much as is done in libraries with books.

*

*languages/english/spelling

*science/biology/genetics
What I'd like to find is a word to describe the line above and also each individual word. There's path like in the computing world but that doesn't quite convey the idea.

A: taxonomy or nomenclature could both be used to describe that, although taxonomy is generally used in nature.

A: This type of structure is usually referred to as a tree. Following this analogy, the individual words are nodes, where "spelling" is an end node or leaf, "languages" may be the root node or just root, and "languages/english/spelling" is a branch.
The wikipedia link says "The lines connecting elements are called branches", but I do not fully agree with that. It is common language to refer to all nodes below one node as a branch.

A: This is almost, but not quite, an example of hyponymy, used 'when the meaning of one form is included in the meaning of another' (George Yule, 'The Study of Language'). In your example, languages is a 'superordinate' and English is a hyponym of languages. The structure breaks down with spelling, because that's an aspect of English rather than a kind of English. Hyponyms of English might be Standard English and Caribbean English.

A: I'd like to propose breadcrumb trail, which according to the Wiktionary is:

A trail of hyperlinks that lead consecutively to the current page, displayed in the page as a guide and a means of navigating easily to any of the pages in the trail

The Wikipedia continues:

Breadcrumbs or breadcrumb trail is a navigation aid used in user interfaces. It allows users to keep track of their locations within programs or documents.

Typical breadcrumbs look like this:
    Home page > Section page > Subsection page

A: I like hierarchy, which was suggested earlier. Or how about tiers, strata, categories, or classifications?
In the Dewey Decimal System, the terms used for the layers of classification (faceted classification) are classes, divisions, and sections.


text:
Q: Database DMLOptions and Apex Error Messages We found an issue when portal users leave comments on our cases. Email notifications to the case owners were not being sent. So I did change the code to use the setoptions method.
The problem is that now, validation messages (validation rules triggered) are not showing on the page. Any idea how to fix this? Thanks in advance.
List<CaseComment> toInsert = new List<CaseComment>();

for (CaseComment newCom : newComments) {

    if (newCom.CommentBody! = null)  {
        newCom.parentId = cId;
        newCom.IsPublished = true;
        toInsert.add(newCom);
    }
}

try  {

    Database.DMLOptions dlo = new Database.DMLOptions();
    dlo.EmailHeader.triggerUserEmail = true;
    database.insert(toInsert, dlo);

} catch(DmlException ex) {

    ApexPages.addMessages(ex);

}

A: I ended up doing this:
if (newCom.CommentBody!=null)
        {
            newCom.parentId=cId;
            newCom.IsPublished = true;

            Database.DMLOptions dmo = new database.DMLOptions();
        dmo.EmailHeader.triggerUserEmail = true;
        newCom.setOptions(dmo);
            toInsert.add(newCom);

        }
    }

   try{

 Insert ToInsert;
   }
catch(DMLException ex){

    ApexPages.addMessages(ex);
   }

A: Can you try this if you are using apex pagemessage tag?`
<apex:pageMessages id="apexmsg"/>

method code
catch(DMLException e1) {
ApexPages.addMessages(e1);
 }   catch(Exception e2) {
// uh-oh, something else happened bad, better show it to the user
ApexPages.addMessage(
  new ApexPages.Message(
      ApexPages.Severity.ERROR
    , 'Unknown exception while inserting your list of stuff.  Please contact support. Exception: ' + e
  )
);
}


text:
Q: Greasemonkey script only loads with CTRL + F5? I created this Greasemonkey for batch following/unfollowing Twitter users. The script works just fine. However, it won't always (almost never) load the first time I go to one of the pages on the include list.
For instance, if I go to twitter.com/followers, the script won't load unless I use CTRLF5 (which refreshes the page contents from the server).
I am not sure whether this is how Greasemonkey scripts are supposed to run, or there is something in my code that I need to change?
My GM script:
// ==UserScript==
// @name            Brainstack.net "YOU Follow (Beta)"
// @namespace       net.brainstack.gm
// @description     Script for automating the following of users from the Twitter Followers page
// @require         http://gm.brainstack.net/tasa/tasa.js
// @resource        tasa_CSS http://gm.brainstack.net/tasa/tasa.css
// @downloadURL     http://gm.brainstack.net/tasa/Brainstack.net_tasa.user.js
// @updateURL       http://gm.brainstack.net/tasa/Brainstack.net_tasa.meta.js
// @include         https://twitter.com/followers*
// @include         https://www.twitter.com/followers*
// @include         https://twitter.com/*/followers*
// @include         https://www.twitter.com/*/followers*
// @include         https://twitter.com/*/following*
// @include         https://www.twitter.com/*/following*
// @include         https://twitter.com/following*
// @include         https://www.twitter.com/following*
// @include         https://twitter.com/search/users?*
// @run-at          document-end
// @grant           GM_getResourceText
// @grant           GM_addStyle
// @version         1.14
// ==/UserScript==

//add CSS to head
var CSS = GM_getResourceText("tasa_CSS");
GM_addStyle(CSS);

//hook to the page load
bsnet_app_page_load();

You can download and/or install the script at gm.brainstack.net.
Thanks!

A: This problem is the same type of issue covered by I have to refresh the page for my Greasemonkey script to run?.   Read, understand, and use the techniques of that answer to "fire" your script on "new" pages.
Additionally, the script code in tasa.js has things like:
var localStorageString = localStorage['bsnet_app_follower'];
if (localStorageString.length > 0){

which crash the script, especially on early runs.
That kind of code should be:
var localStorageString = localStorage['bsnet_app_follower'];
if (localStorageString  &&  localStorageString.length > 0){

There may be other issues (didn't see any at a glance; didn't debug the script either), but this is not the place for code review.


text:
Q: How to pass multiple parameters for aiohttp request wit the same name? The API from which I want to receive data takes several values with the same name as a parameter:
https://example.com/method?types=Retail&types=Office&types=Industrial......

I try to do it like this:
params_api_sale = {
    'types': [
        'Retail', 'Office', 'Industrial',
        'Mixed Use', 'Development Site',
        'Land', 'Special Purpose', 'Other'
    ],
    'sortDirection': 'Descending',
    'sortOrder': 'ActivatedOn'
}

async def get_items():
    async with aiohttp.request(
        method='GET', url=vars_.url_api_sale,
        headers=vars_.headers, params=vars_.params_api_sale) as response:
        ...

But this gives me an error:
Traceback (most recent call last):
  File "foo.py", line 85, in <module>
    asyncio.get_event_loop().run_until_complete(main())
  File "C:\Python37\lib\asyncio\base_events.py", line 583, in run_until_complete
    return future.result()
  File "foo.py", line 80, in main
    await asyncio.create_task(get_items())
  File "foo.py", line 44, in get_items
    headers=vars_.headers, params=vars_.params_api_sale) as response:
  File "D:\Dev\venv\lib\site-packages\aiohttp\client.py", line 1051, in __aenter__
    self._resp = await self._coro
  File "D:\Dev\venv\lib\site-packages\aiohttp\client.py", line 473, in _request
    ssl=ssl, proxy_headers=proxy_headers, traces=traces)
  File "D:\Dev\venv\lib\site-packages\aiohttp\client_reqrep.py", line 263, in __init__
    url2 = url.with_query(params)
  File "D:\Dev\venv\lib\site-packages\yarl\__init__.py", line 922, in with_query
    new_query = self._get_str_query(*args, **kwargs)
  File "D:\Dev\venv\lib\site-packages\yarl\__init__.py", line 886, in _get_str_query
    quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query.items()
  File "D:\Dev\venv\lib\site-packages\yarl\__init__.py", line 886, in <genexpr>
    quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query.items()
  File "D:\Dev\venv\lib\site-packages\yarl\__init__.py", line 864, in _query_var
    "of type {}".format(v, type(v))
TypeError: Invalid variable type: value should be str or int, got ['Retail', 'Office', 'Industrial', 'Mixed Use', 'Development Site', 'Land', 'Special Purpose', 'Other'] of type <class 'list'>

I have not found a documented way to do this. All that comes to my mind is to generate a URL string with these parameters, of course, if there is no more correct way.

A: import requests

params = {
    'types': [
        'Retail', 'Office', 'Industrial',
        'Mixed Use', 'Development Site',
        'Land', 'Special Purpose', 'Other'
    ],
    'sortDirection': 'Descending',
    'sortOrder': 'ActivatedOn'
}

r = requests.get("http://www.test.com/", params=params)

print(r.url)

output:
https://www.test.com/?types=Retail&types=Office&types=Industrial&types=Mixed+Use&types=Development+Site&types=Land&types=Special+Purpose&types=Other&sortDirection=Descending&sortOrder=ActivatedOn

For aiohttp you can use MultiDict which is also included in the official document.

For sending data with multiple values for the same key MultiDict may be used as well.

A: As stated at aiohttp documentation, you can pass a list of tuples to params with the same key to achieve your goal:

Also it is possible to pass list of 2 items tuples as parameters, in that case you can specifiy multiple values for each key:

params = [
    ("key1", "value1"),
    ("key1", "value2"),
    ("key2", "value3"),
]


text:
Q: Missing argument list bracket error app.get("/editMBTI", editMBTIFunc(req, res)
{
    // making MongoClient available to all the EJS Files
    // app.locals.MongoClient= MongoClient;
    MongoClient.connect(url, function (err, client) {
        assert.equal(null, err);
        console.log("Connected Successfully to the Database server");
        const db = client.db(dbName);
        //getting the whole collection of MBTI sets
        var cursor = db.collection("mbti_testcontent").find();
        cursor.each(function (err, doc) {
            console.log(doc);
            //send the above retrieved doc to the editMBTI.ejs file(front- end)
            res.render('editMBTI', {
                'mbti_content': doc,
                'db_url': url,
                'dbName': dbName
            });
        });
    });
});

The above is the code and the image of the terminal(https://i.stack.imgur.com/XcOti.png). Why is the missing argument bracket error poping up in the editMBTI api ? I have closed all the brackets that were opened. Where is it missing ?

A: Change this line:
app.get("/editMBTI", editMBTIFunc(req, res)

to this:
app.get("/editMBTI", function editMBTIFunc(req, res)

FYI, a tool like JSHint or JSLint will often give you more detailed info about where something is wrong (which is what I used to see this more easily).


text:
Q: How to add JLabel at run time in Swing? I am making am window application on Java.
I want to add label name at run time in my Swing application. How can I do this using Java Swing?
public class Component1 extends JPanel {

   Component1() {
      JLabel label = new JLabel("dd");
      label.setBounds(370, 340, 150, 20);
     // label.setText("labeVVl");
      add(label);
}

 public static void main(String[] args)
 {
    // create frame
    JFrame frame = new JFrame();
    final int FRAME_WIDTH = 800;
    final int FRAME_HEIGHT = 600;
    // set frame attributes
    frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
    frame.setTitle("My Frame");
    frame.setVisible(true);
    Component1 Com = new Component1();
    Component add = frame.add(Com);
}
}

A: *

*this code should be works by add revalidate() and repaint() as notifiers for LayoutManager

*don't to use NullLayout, use default FlowLayout implemented for  JPanel in API do that the same way

*see Initial Thread

*for example


text:
Q: manually trigger a new thread in python I am trying to implement a program that will be able to execute 2 functions asynchronously, e.g. let each function be triggered regardless of whether the other one is running and how long its been running for.
I know python supports threading, but all examples I have seen call functions in the script, so there is a predetermined order and time separation between the functions.
My question is how to get passed that and trigger the functions myself whenever I am ready.


text:
Q: Checking for equilibrium in a square configuration of charges Four equal positive charges each of magnitude q are placed at the respective vertices of a square of side length l. A point Q is placed at the centre of the square. Then find the state of equilibrium of charge Q (stable, unstable or neutral)
I figured that the charge Q was in equilibrium because the force on it was zero but couldn't find out if it were stable or not. I know that in stable equilibrium, a small displacement results in SHM about the mean position so I tried to write an equation of force for a small displacement but couldn't succeed in formulating the equation. Any help regarding writing the force on a small displacement would be deeply appreciated.
Thank you

A: Take for example, the case when the charge Q at the centre is negative, so the force is attractive.
If it gets displaced even by a small  value $\delta r$ towards either, the separation with this particular vertex would be $(\frac{l}{\sqrt 2}-\delta r)$, while it is slightly larger for the others. Due to the inverse dependence of the force on this separation squared, the attractive force towards this vertex would be larger than towards the other three. The condition of zero net force is no longer satisfied, and the direction of net force is towards this vertex. So, this charge will continuously keep moving towards it, under it reaches the vertex (and annihilates). Clearly, there is no restoration here, so the equilibrium is unstable.

Edit - As prompted by the OP, I am feeding in more details.
The situation is represented by the following diagram:

Charges q each are on the vertices, and Q is at the point O originally. As long as it stays at this point, the net force on it is zero, since forces due to the four vertices cancel out. We have to see what happens if it gets displaced along one of the sides, say towards A. Say, it got displaced infinitesimally, by a small amount $\delta r$ towards A. This $\delta r$ subtends an angle $\theta$ at the vertices B and D, such that
$$\tan \theta = \frac{\delta r}{(l/\sqrt{2})} = \frac{\sqrt{2}\delta r}{l}$$
For convenience, let us adopt "natural units" here, so that Q = q = 1, and $\frac{1}{4 \pi \epsilon_0} = 1$. (This is just for convenience, if you don't like this system of units, simply multiply each of the following terms by the factor $\frac{Qq}{4 \pi \epsilon_0}$. Since this part is common for all all four, it doesn't matter - you can even multiply the final answer by this factor directly.)
Electrostatic force is $\propto \frac{1}{r^2}$ is all we need for this.
Distance to the vertex A  $= (\frac{l}{\sqrt 2} - \delta r)$
Distance to the vertex B  $= (\frac{l}{\sqrt 2} + \delta r)$
Clearly therefore, ${\vec F}_{\rm towards \ A} \ne {\vec F}_{\rm towards \ B}$, the former being larger due to the smaller denominator. These two don't cancel out, and the net force is directed towards A.
In comparison, if we take into account the vertices C and D,
Distance to the vertex C  $= \sqrt{(\frac{l}{\sqrt 2})^2 + (\delta r)^2}$ = Distance to the vertex D
But while distances are equal, these forces are not antiparallel, and hence, won't cancel out completely.
Let us resolve these into components along the axis AB and transverse to it. For example, the force ${\vec F}_{\rm towards \ C}$ has a transverse component $\big\vert {\vec F}_{\rm towards \ C} \big\vert \cos \theta$, while the component along AB is $\big\vert {\vec F}_{\rm towards \ C} \big\vert \sin \theta$.
Two deductions here:
For small angles, $\cos \theta$ is much bigger than $\sin \theta$, so the dominant contribution is the transverse component which cancelled out. So, the component along the axis AB is the smaller component. Secondly, for small angles $\sin \theta \approx \tan \theta$, (both being approximately equal to $\theta$, but I'll not use this. I'll only use $\sin \theta \approx \tan \theta$).
So, the $\cos \theta$ components cancel out, while the $\sin \theta$ components add up. As can be seen from the figure, these will be directed towards B, and this extra contribution has strength:
$$2 \big\vert {\vec F}_{\rm towards \ C} \big\vert \sin \theta \approx 2 \big\vert {\vec F}_{\rm towards \ C} \big\vert \tan \theta, $$
which comes out to be (upon plugging in)
$$\frac{2}{(\frac{l}{\sqrt 2})^2 + (\delta r)^2} \times \frac{\sqrt{2}\delta r}{l}$$
which could be rewritten as
$$\frac{2 \sqrt{2}\delta r}{\frac{l^3}{2}(1 + (\frac{\sqrt{2}\delta r}{l})^2)} = \frac{4 \sqrt{2}\delta r}{l^3(1 + (\frac{2(\delta r)^2}{l^2}))}$$
Since the last factor is small, it can be treated using the binomial theorem, $(1+x)^{-1} \approx (1-x)$.
This reduces the above factor to
$$\frac{4 \sqrt{2}\delta r}{l^3} (1 - (\frac{2(\delta r)^2}{l^2})) \approx \frac{4 \sqrt{2}\delta r}{l^3} $$
since the other term is of the order of $(\delta r)^3/l^5$ and hence, is very very small. This is the extra component aimed towards B.
Now, we have to find the net difference between the force along A and total force along B. For evaluating these, one would need the value of separation squared for both of these cases (in terms of such binomial expansions). Let us do these first.
$$\frac{1}{(\frac{l}{\sqrt 2} - \delta r)^2} = \frac{2}{l^2} (1 - \frac{\sqrt{2}\delta r}{l})^{-2} \approx \frac{2}{l^2} (1 + \frac{2\sqrt{2}\delta r}{l})$$
and by the same token
$$ \frac{1}{(\frac{l}{\sqrt 2} + \delta r)^2} \approx \frac{2}{l^2} (1 - \frac{2\sqrt{2}\delta r}{l}) $$
So, we have
$$\big\vert {\vec F}_{\rm towards \ A}\big\vert - \big\vert{\vec F}_{\rm towards \ B} \big\vert = \Big[ \frac{2}{l^2} (1 + \frac{2\sqrt{2}\delta r}{l})\Big] - \Big[ \frac{2}{l^2} (1 - \frac{2\sqrt{2}\delta r}{l}) + \frac{4\sqrt{2}\delta r}{l^3} \Big]$$
which yields on simplifying,
$$ \big\vert {\vec F}_{\rm towards \ A}\big\vert - \big\vert{\vec F}_{\rm towards \ B} \big\vert = \frac{4\sqrt{2}\delta r}{l^3}$$
Thus,
$$ \big\vert {\vec F}_{\rm towards \ A}\big\vert > \big\vert{\vec F}_{\rm towards \ B} \big\vert$$
and the resultant force is aimed towards A, which goes in support of my claim of the absence of any restoring force. Hence, the equilibrium is unstable.

A: Consider the square to be in the x-y plane. Then see what happens when you displace the central charge in the z-direction.
Of course, the answer will depend upon whether Q is positive or negative and possibly also on the direction of displacement.


text:
Q: Getting lots of  errors with sitemap on google webmasters I use the Google XML Sitemaps (Wordpress Plugin) and the latest wordpress version. Recently i have had a lot of 404 not found errors in webmasters. The urls show up without any categories and it links to the sitemap.xml file. It shows the url as http://mysite.com/welcome-to-my-site/ instead of http://mysite.com/general/welcome-to-my-site/
Since the categories are missing these links return a 404 not found error. These faulty links are piling up and i am in a fix. Please help.

A: the XML sitemaps plugin should be pulling your URL structure that you've set in the permalinks setting. Are you using a plugin or other method to remove the /category-name/ from the URL?


text:
Q: Change annotation symbol properties in bulk? How can a person change annotation properties in bulk?
For example: take the 4500 records in "Waterbody text" annotation feature class and change all occurrences of "Times New Roman", "Cyan" to "Revival", "Cretan Blue".
I don't want to use layer symbol substitution if it can be avoided (and Esri recommends against it for this anyway: "...is not designed to be a wholesale replacement of annotation symbol editing and symbol management")

A: you can work with the annotation properties like with a normal attribute table. So you can update your properties using the field calculator. You just need to know the exact string (or value), so I would first change one annotation manually in order to observe the right syntax.
EDIT : another approach for full control is to start an edit session, select the annotations that you wish to modify, and update based on the attribute window (on the editor toolbar).
If you select the annotation class name it modifies all selected items. Note that you need to press "apply" to actually change your annotations.

Another approach consists in using text formatting instead of annotation properties. This way you have all information in your text string. For instance :
<CLR cyan = "100">Annotation_text</CLR>

that you can create with the filed calculator (python parser used here)
""" <CLR cyan = "100"> """ + !TextString! + """ </CLR> """

A: I found something that works, but it's error prone and would probably crash ArcMap with larger datasets or machines with low memory. A better solution is still desired.
Load the annotation FC in ArcMap, then using the Drawing toolbar, NOT Editor as you might expect:

*

*Select the features to change (Drawing arrow)

*Zoom in so only a few features are visible

*Start Editing

*Change desired property (Drawing toolbar)

*De-select (click on a blank spot)

*Save edits

Wait for the spinny circle to stop before going to next step or you'll have to start over again. Do not click while waiting. Sometimes the spinny circle doesn't start for awhile. Move the mouse cursor over the ArcMap toolbars, If the help tips don't show, it's spinning, wait.
On my moderately powerful 2.5Ghz machine with 12mb memory I have to wait several minutes between operations with 4356 selected elements.
Step 2 & 4 are just to reduce screen redraw time. I don't know that they really make much difference.

A: Esri Mapping Center has another approach, Changing Annotation Feature Class Font:

If you want the change to be permanent, you can add the symbol to the
  symbol collection in ArcCatalog and then open the annotation feature
  class in ArcMap and calculate the symbol ID field to the new symbol.
  You need to be careful using this approach because if there are symbol
  overrides they will be wiped out. You can work around this by
  calculating out the override fields, changing the symbol ID field and
  then calculating back the values.

There would be some research involved in figuring out what Symbol ID to use. In my data they're all -1, e.g. not specified.


text:
Q: Can't boot with new RAM on gigabyte X299 UD4 (rev. 1.0) My pc currently works with a single 8GB RAM GB, I recently bought a new RAM memory exactly the same as I already have.
When I installed the dual channel windows crashes after a stressful use. I did some tests with software and apparently the new RAM has problems, after knowing this I tried to use only the new RAM in the slot that was the previous one but the BIOS not booting (RAM issue). I restarted the bios and the CMOS but it didn't work either. I tried the new RAM on another computer and it worked, I don't know what to do to make it work on my PC.
Motherboard:
Motherboard Intel X299 Durable motherboard con RGB Fusion, Digital LED, Dual M.2, 120dB SNR ALC1220, Intel Gaming LAN, USB 3.1 gen 2 Tipo-A

New Memory Ram:
xpg gammix d10 8gb 3000mhz ddr4 Model: AX4U300038G16-SBG


text:
Q: Ionic 3 height problems I am facing problems in Ionic 3 background height - if I set height 100vh this happens :

How to set background height to always have all background (seen and scrolled) be colored - not white ?
Height 100% - is also bad. for a smaller devices

A: in your app.css copy this:
ion-content {
background-image: url("the url of your image background");
background-repeat: no-repeat;
background-size:cover;

}`


text:
Q: Parsing Text Files in Irregular Formats I have a very large text file that was created by converting a PDF to text format using the XPDF 'pdftotext' utility.  The document contains abandoned property data that I'd like to be able to parse into a database-friendly format.  The file is formatted as follows:
DOE JANE H                                        STATE         1994     0002       SAVINGS       52            33.99   0
                                                  EMPLOYEES                         ACCOUNTS
                                                  CREDIT UNION

                 SOMECITY      ZZ      12345

In general, all of the records look like that.  There are some that span one additional line (having an extra space before the city / state / zip line.
To make this even better, the text was not converted uniformly.  Each page of the PDF converted to a "page" of the text file, having different column widths.  In addition, the data might sometimes look like this:
DOE JANE H      OR SOME OTHER OWNER           STATE         1994     0002       SAVINGS       52            33.99   0
                                              EMPLOYEES                         ACCOUNTS
                                              CREDIT UNION

                SOMECITY      ZZ      12345

Or, alternatively, like this:
DOE                                      STATE         1994     0002       SAVINGS       52            33.99   0
JANE                                     EMPLOYEES                         ACCOUNTS
H                                        CREDIT UNION

            SOMECITY      ZZ      12345

So, is there anything I can do about this?  Any help is appreciated.
UPDATE:
To clarify - I've tried to parse this using regular expressions and Perl, but with no luck (I was not able to figure out a decent way to deal with chunks of 5 lines at a time, or varied chunks as the records sometimes span 6 lines).  In my best attempt, I was able to parse out only the first line of every record, which only contains partial information (some or all of the name, the first line of the holder, the report year, property type, etc...).  Ideally, I'd like to be able to get all of the information for a record, regardless of the different formats.  The programming language does not matter, so any appropriate tool for the job will do.  I was hoping to get some input on different options of parsing a file like this, perhaps different tools or even applications that deal with issues like this.

A: Here's a start in Python. Something similar can probably be done in perl.
col_start_pat = re.compile( r'\s+\s(?=\S)' )
for row in ( r.rstrip() for r in data.splitlines() ):
    if not row: continue
    def matches( row ):
        offset= 0
        for m in col_start_pat.finditer( row ):
            yield offset, row[offset:m.end(0)].rstrip()
            offset= m.end(0)
        yield offset, row[offset:].rstrip()
    columns= list( matches( row ) )
    if not columns: continue
    print( columns )

It doesn't do the whole job.  It merely identifies the "fields" in each line as a sequence of tuples that look like this.
[(0, 'DOE JANE H'), (50, 'STATE'), (64, '1994'), (73, '0002'), (84, 'SAVINGS'), (98, '52'), (112, '33.99'), (120, '0')]
[(0, ''), (50, 'EMPLOYEES'), (84, 'ACCOUNTS')]
[(0, ''), (50, 'CREDIT UNION')]
[(0, ''), (17, 'SOMECITY'), (31, 'ZZ'), (39, '12345')]
[(0, 'DOE JANE H'), (16, 'OR SOME OTHER OWNER'), (46, 'STATE'), (60, '1994'), (69, '0002'), (80, 'SAVINGS'), (94, '52'), (108, '33.99'), (116, '0')]
[(0, ''), (46, 'EMPLOYEES'), (80, 'ACCOUNTS')]
[(0, ''), (46, 'CREDIT UNION')]
[(0, ''), (16, 'SOMECITY'), (30, 'ZZ'), (38, '12345')]
[(0, 'DOE'), (41, 'STATE'), (55, '1994'), (64, '0002'), (75, 'SAVINGS'), (89, '52'), (103, '33.99'), (111, '0')]
[(0, 'JANE'), (41, 'EMPLOYEES'), (75, 'ACCOUNTS')]
[(0, 'H'), (41, 'CREDIT UNION')]
[(0, ''), (12, 'SOMECITY'), (26, 'ZZ'), (34, '12345')]

The next part is to use the header column numbers to identify the format and then collapse the rows into a single object.

Expanding on that...
pat1= [0, 50, 64, 73, 84, 98, 112, 120]
pat2= [0, 16, 46, 60, 69, 80, 94, 108, 116]
pat3= [0, 41, 55, 64, 75, 89, 103, 111]

def columns( data ):
    col_start_pat = re.compile( r'\s+\s(?=\S)' )
    for row in ( r.rstrip() for r in data.splitlines() ):
        if not row: continue
        def matches( row ):
            offset= 0
            for m in col_start_pat.finditer( row ):
                yield offset, row[offset:m.end(0)].rstrip()
                offset= m.end(0)
            yield offset, row[offset:].rstrip()
        columns= list( matches( row ) )
        yield columns

def row_groups( data ):
    columns_iter= columns(data)
    record= []
    for parsed in columns_iter:
        offsets= [ c[0] for c in parsed ]
        if offsets == pat1:
            if record: yield( format, record )
            format= 1
            record= []
        elif offsets == pat2:
            if record: yield( format, record )
            format= 2
            record= []
        elif offsets == pat3:
            if record: yield( format, record )
            format= 3
            record= []
        record.extend( parsed )
    yield( format, record )

for record in row_groups( data ):
    print( record )

Gets you the following:
(1, [(0, 'DOE JANE H'), (50, 'STATE'), (64, '1994'), (73, '0002'), (84, 'SAVINGS'), (98, '52'), (112, '33.99'), (120, '0'), (0, ''), (50, 'EMPLOYEES'), (84, 'ACCOUNTS'), (0, ''), (50, 'CREDIT UNION'), (0, ''), (17, 'SOMECITY'), (31, 'ZZ'), (39, '12345')])
(2, [(0, 'DOE JANE H'), (16, 'OR SOME OTHER OWNER'), (46, 'STATE'), (60, '1994'), (69, '0002'), (80, 'SAVINGS'), (94, '52'), (108, '33.99'), (116, '0'), (0, ''), (46, 'EMPLOYEES'), (80, 'ACCOUNTS'), (0, ''), (46, 'CREDIT UNION'), (0, ''), (16, 'SOMECITY'), (30, 'ZZ'), (38, '12345')])
(3, [(0, 'DOE'), (41, 'STATE'), (55, '1994'), (64, '0002'), (75, 'SAVINGS'), (89, '52'), (103, '33.99'), (111, '0'), (0, 'JANE'), (41, 'EMPLOYEES'), (75, 'ACCOUNTS'), (0, 'H'), (41, 'CREDIT UNION'), (0, ''), (12, 'SOMECITY'), (26, 'ZZ'), (34, '12345')])

Which has all of the information; it just needs some clever assembly.


text:
Q: What's a word to describe an apartment when its owners are on vacation? Please help me choose the most suitable word in this context:

When I went on vacation, thieves climbed into my abandoned apartment.

Does 'abandoned' word fit well in this usage? My apartment does not contain junk and not dilapidated. Good one with all necessary properties. It just was temporarily without owners. Nobody lived there for a few days.
What're better and more suitable options?
derelict, deserted, forsaken, emptied, unoccupied,  outcast, something else?

A: I would go with empty, for example

Burglars in Northern Ireland are having empty houses advertised to them by the growing trend of posting holiday snaps on social media, a police commander has warned.

As Mitch recommended, it may be even better to omit an adjective altogether.

A: I would use the word unattended, as opposite to attended.
From the Vocabulary.com Dictionary:

having a caretaker or other watcher

When I went on vacation, thieves climbed into my unattended apartment.

A: You don't even really need a word for it.  The reader will understand that your apartment is "unoccupied" from the context at the beginning of the sentence.

When I went on vacation, thieves climbed into my unoccupied apartment.
When I went on vacation, thieves climbed into my apartment.

A: I'd use vacant.

*having no occupant; unoccupied:
  no vacant seats on this train.

*not in use: a vacant room.

A:
My home was robbed 1. / got broken into / burgled while I was on vacation

If you were on holiday/vacation, it's clear that your home was (briefly) UNINHABITED during that period, and as such unguarded.

… the higher rate of crime in the inner city may be due to the fact that many urban homes are unguarded during much of the day in single-person and two-career households.
  … a final means of obtaining knowledge of unguarded homes is through information gathered while performing a legitimate occupation. ... several occupations used by residential burglars, including an interior decorator, a cable television installer, ...
RESIDENTIAL BURGLARY by George F. Rengert and Elizabeth R. Groff

1. technically inaccurate, but it is often used in speech

A: Uninhabited.
Because you still own it, you didnt rent it out, so it is not in truth exactly 'empty' or 'vacated' but no-one is living or 'inhabiting' it right now, so I think you can say 'While I was on holiday, thieves broke into my uninhabited apartment'.
Webster's
Definition of uninhabited
: not occupied or lived in by people : not inhabited

A: Re: apartment's occupants on vacation and thus no-one at home.
You could create a US-neologism.  How about "vacationated"?
This combines vacation with vacated.
It resonates with vacant; the closest extant word to your need, as proposed earlier by Roger Lipscombe.

A: I would go with "unalarmed" abode.