text:
Q: Delete row with a complex if I want to write a query where it deletes duplicates from table where the Access column value is 1 - 5, but always take the highest number but if it's 5 then that should be the lowest, because of how they designed the database. but 5 have no access.(5 should have been 0 in my opinion.)
So there is an ID column and an Access column, if there are more than 1 IDs, then delete the ID with the lowest Access value. But remember treat 5 as 0 or lowest.

So I thought something like:
Delete from [table]
Where [ID] > 1
AND [Access] = (CASE [Access]
    WHEN Access = 1 THEN ____ <----'Do nothing')
    ...
    WHEN Access = 5 THEN ____ <----'Do Delete')

That is where I struggle. How would I check ID, and see which Access is the highest and delete all the lowest if they exist. Remember, if it's 5 then 4 is actually higher so delete 5.
So confusing!

A: If you want to delete the row for each id that first has access 5 and the rest ordered, then do:
with todelete as (
      select t.*, row_number() over (partition by id
                                     order by (case when access = 5 then -1 else access end)
                                    ) as seqnum
      from table t
     )
delete from todelete
    where seqnum = 1;

If you only want to do this when there is more than one record for the id:
with todelete as (
      select t.*, row_number() over (partition by id
                                     order by (case when access = 5 then -1 else access end)
                                    ) as seqnum,
             count(*) over (partition by id) as cnt
      from table t
     )
delete from todelete
    where seqnum = 1 and cnt > 1;

EDIT:
If you want to delete everything except one row according to your precedence rules:
with todelete as (
      select t.*, row_number() over (partition by id
                                     order by (case when access = 5 then -1 else access end)
                                    ) as seqnum,
             count(*) over (partition by id) as cnt
      from table t
     )
delete from todelete
    where seqnum < cnt;

A: If you apply modulo 5 to the Access column, you will get the following transformation:
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0

As you can see, 5 yields the lowest result, others remain unchanged – seems the proper ranking of privileges for your case. With that in mind, I would probably try the following method:
DELETE FROM u
FROM dbo.UserTable AS u
LEFT JOIN (
  SELECT ID, MAX(Access % 5) AS Access
  FROM dbo.UserTable
  GROUP BY ID
) AS keep
  ON u.ID = keep.ID
 AND u.Access % 5 = keep.Access
WHERE i.ID IS NULL
;

The subquery returns a set of IDs with Access values to keep. The main query anti-joins the target table to that set to determine which rows to delete.
This method is somewhat specific to your particular situation: it may not work correctly after extending the current set of valid values for Access. As an alternative, you could use CASE, as others suggested, that would certainly be more flexible. However, I would actually suggest you add an AccessRank column to the Access table to indicate which privilege is higher or lower than others.
That would make your DELETE query more complex but you wouldn't need to adapt it every time new Access values are introduced (you'd just need to define proper ranking in your data):
DELETE FROM u
FROM dbo.UserTable AS u
INNER JOIN dbo.Access AS a
  ON u.Access = a.ID
LEFT JOIN (
  SELECT u.ID, MAX(a.AccessRank) AS AccessRank
  FROM dbo.UserTable AS u
  INNER JOIN dbo.Access AS a
    ON u.Access = a.ID
) AS keep
  ON u.ID = keep.ID
 AND a.AccessRank = keep.AccessRank
;

It is implied that AccessRank contains unique rankings only.

A: Sample Access table:
|id|access|
-----------
|1 |  1   |
|1 |  2   |
|1 |  5   |
|2 |  1   |
|2 |  3   |

On running the below query:
DELETE a
FROM acc a
INNER JOIN
(SELECT row= ROW_NUMBER() OVER(PARTITION BY ID ORDER BY  (CASE WHEN ACCESS=5 THEN 0 ELSE ACCESS  END) DESC), * FROM acc) b
ON a.id = b.id AND a.access = b.access
WHERE b.row > 1

The result is:
|id|access|
|1 |  2   |
|2 |  3   |

A: This should be the fastest and most portable solution as it allows an index to be used on Access and uses standard SQL.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
CREATE TABLE Table1
    ([ID] int, [Access] int)
;

INSERT INTO Table1
    ([ID], [Access])
VALUES
    (1, 5),
    (1, 1),
    (1, 2),
    (2, 5),
    (2, 1),
    (2, 2),
    (3, 5)
;

Query 1:
delete t
from Table1 t
inner join (
    select ID, max(Access) as MaxAccess
    from Table1
    where Access <> 5
    group by ID
) pm on t.Access <> pm.MaxAccess
    and t.ID = pm.ID

select * from Table1

Results:
| ID | ACCESS |
|----|--------|
|  1 |      2 |
|  2 |      2 |
|  3 |      5 |


text:
Q: How can I make ssh "faster" by not trying to find pubkeys on my host and immediately skip to password authentication? Sometimes I need to ssh to a new remote server and immediately fix something without ssh trying to find any private keys on my host. It usually stalls at this point:
debug1: Next authentication method: gssapi-with-mic

debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/blah' not found

debug1: Unspecified GSS failure.  Minor code may provide more information
Credentials cache file '/tmp/blah2' not found

debug1: Unspecified GSS failure.  Minor code may provide more information

Is there a way I can specify for ssh to just do password based authentication immediately?

A: It's trying to find private keys on your computer; the remote computer would have the public key. Remote computers should never have your private key (unless it's a computer under your control).
Looks like you've got GSS Auth turned on, from the command line you can turn it off with something like ssh -o GSSAPIAuthentication=no user@host.example.com.
If that works it would probably be easier to turn off for default connections by adding GSSAPIAuthentication no under the Host * section of your ~/.ssh/config file (or the system wide ssh_config file). If you need it for local servers you can then add a Host *.my_company.com section with it turned back on.

A: ssh -o PreferredAuthentications=password,keyboard-interactive,gssapi-with-mic,hostbased,publickey user@host.example.com

This setting can also be put into ~/.ssh/config if you do not want key access for any server that allows password access.

A: If you connecting to the server with a command like
ssh user@192.168.1.188
then problem you are seeing is most likely caused by the client not being able to resolve the hostname of the server. Once the client can resolve the server's hostname you still get the error messages but without the delay which is caused by the name service timing out.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Visual studio  How to set the active test settings Hi
My question is about how can i set the active test settings in the project file for visual studio 2010, I mean, what flag or entry does the visual studio modify in the solution file or where is that setting.
Im developing a solution file generator but cant find the way to auto select the required test settings as the default settings

A: If you do not see anything under the Menu Item "Test > Select Active Test Settings" or "Test > Edit Test Settings", Check your Solution Explorer window for files ending with ".testsettings" under the "Solution Items" folder.
If there are not any .testsettings files, you can right click the "Solution Items" or "Solution" folder, then click on "Add" then select "New Item". Under the "Installed Templates" select "Test Settings". Select the "Test Settings" template, name the file, and click the "Add" button. This is now part of your solution and now appears in the "Test > Select Active Test Settings" and "Test > Edit Test Settings" menu items.

A: If memory serves, the active test settings is stored in the .vsmdi file, not the solution file.
Edit: specifically, it is the "storage" attribute on the RunConfiguration element in the .vsmdi file.


text:
Q: mono develop Combobox Entry - Autocomplete I am trying to make a window form in Mono develop.
in the form, I need a Combobox Entry with Autocomplete/AutoSuggest feature.
Could any one guide me how to do it?

A: Check this feature out on an Entry field called EntryCompletion:
Entry entry = new Entry ();
entry.Completion = new EntryCompletion ();

There is an an example here of doing an search auto complete.
Edit:
Here is the Documentation for the feature with the same example


text:
Q: Original and concise class names? How can I come up with original class names that avoid generic style words such as BlahManager ?
Also how to avoid long class names ? Here's an example from Java:
InternalFrameInternalFrameTitlePaneInternalFrameTitlePaneMaximizeButtonWindowNotFocusedState (from com.sun.java.swing.plaf.nimbus)
With a given a context I reckon you could shorten such names. Say have a class used in a library or sub-library such that part of the purpose of a class is implicit.
I'm not looking to start a discussion here and would like insights into the logic or reasoning used when coming up with a name.
Edit: Here's a (funny) generator link: http://projects.haykranen.nl/java/

A: This other (closed) Stackoverflow question is so full of good insights that I can't think of anything to add, other than Sun should be looked at with "do as I say, not as I do" in mind (they generally show not even a vague desire to avoid excessive verbosity): What's the best approach to naming classes?
It includes so many good citations from great authors and programming philosophers


text:
Q: Grabbing users with no orders with mysql & php, simplifying this Currently, this is my php script:
            $users = DB::select('id', 'email', 'firstname', 'lastname')->from('users')->execute()->as_array();

            $orders = array();
            foreach($users as $user)
            {
                $anyOrder = DB::select('id')->from('orders')
                ->where('orders.date_created', 'BETWEEN', array($from, $to))
                ->and_where('orders.user_id', '=', $user['id'])
                ->and_where_open()
                ->and_where('orders.status', '=', 'new')->or_where('orders.status', '=', 'delivered')
                ->and_where_close()
                ->execute()->count();

                if($anyOrder == 0)
                {
                    $orders[] = array('firstname' => $user['firstname'], 'lastname' => $user['lastname'], 'email' => $user['email']);
                }
            }

(DB::select() is a query, im using kohana query builder).
This works fine, until now when I have over thousands users.
How can this be simplified and quicker?
What the script does is saving all who does not have an order between $from and $to into the $orders array.

A: Use a SQL join-query and select for no order results.  Along the lines of
SELECT id, email, firstname, lastname
FROM users
LEFT OUTER JOIN orders ON users.id = orders.user_id
    AND orders.date_created BETWEEN $start AND $end
    AND orders.status = 'new' OR orders.status = 'delivered'
WHERE orders.id IS NULL

Using a join is much better, as you will get everything you need in one query, instead of one per user.
Thanks to the person who edited the query :)

A: /Get all users without any orders/
SELECT id, email, firstname, lastname
FROM users
LEFT JOIN orders
  ON users.id = orders.user_id
  AND orders.date_created BETWEEN $start AND $end
WHERE orders.id IS NULL
UNION

/*Union in all users */
(SELECT id, email, firstname, lastname
FROM users
INNER JOIN orders
  ON users.id = orders.user_id
  AND orders.date_created BETWEEN $start AND $end

/* except those with 'new' & 'delivered' status
/*note: if user bob has 2 orders and one is in status of 'backorder' and one is in 'new'
then bob will show up... is this what you want? */
MINUS
SELECT id, email, firstname, lastname
FROM users
INNER JOIN orders
  ON users.id = orders.user_id
  AND orders.date_created BETWEEN $start AND $end
WHERE Orders.status in ('new','delivered'))


text:
Q: How to combining similar git repositories? I have migrated an big old cvs repository to git. In my project I have several different development teams, which need access to the same or different repository folders. So my idea is to separate the central repository into several repositories, so that each team would have access to one repository with the folders they need. Behind these repositories an integration repository would be necessary.
So the problem is that there are project folders to which several teams need access. For example:
Team-repo 1: folderA, folderB, folderD
Team-repo 2: folderC, folderD
-->Shared repo (repo1 + repo2): folderA, folderB, folderC, folderD

In this example folder D has to be combined.
Is it possible in git to implement such a concept?
My intention is, that each development team only need to clone one little repository instead of the big one.

A: You would need to have each "folder" in its own repository (at least each independant folder).
Then you use the concept of submodules ( http://git-scm.com/book/en/Git-Tools-Submodules )

*

*"modules" repository : RepoA, RepoB, RepoC, RepoD

*"project" repository, using git submodule : Team1, Team 2

If you look at the url I provided, workflow is described.


text:
Q: Nashorn - debug javascript run in Nashorn I use eclipse luna as IDE. I'm working in web application.
When I code in javascript, sometimes I forget to put semicolon, but everything still work fine if my javascript run in browser.
But when I run my javascript in nashorn, it will throw an error because I didn't put semicolon
the error say s

nashorn Error: :1:68 Expected ; but found var ..... ... ... in
   at line number 1 at column number 68

The problem is, the console always shows me the error at line number 1, I think because nashorn reads my javascript file as single line, but truthfully my javascript file contains many lines.
It is hard to find the error because the console always say the error is in line number 1.
I know something is wrong with my code, but I don't know how to fix it.
Nashorn.java
public class Nashorn {

    public Nashorn() {
    }

    public static String readFileAsText(String theUrl){
        String allLine = "";
        try {
            URL url = new URL(theUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader( url.openStream()));

            String inputLine = "";
            while ((inputLine = in.readLine()) != null){
                allLine += inputLine;
                //System.out.println("read : "+inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            System.out.println("url Error: ");
        } catch (IOException e) {
            System.out.println("I/O Error: ");
        }
        return allLine;
    }

    public static void main(String[] args) {
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager(null);
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");

        try {
            //readFileAsText
            String room = Nashorn.readFileAsText("http://localhost:8080/monsterpuzzle/data/Room.js");
            scriptEngine.eval( room );
        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("nashorn Error: "+e.getMessage());
            e.printStackTrace();
        }
    }
}

Room.js
var Room = function(){
    this.test = function(){
        print("lalala");
    };
}

var room = new Room();
room.test();

my problem :
Nashorn always shows me the error at line number 1. However, the error is not in line number 1 but in another line. I think it happens because nashorn reads my entire line of code as single line.
my question :
How to fix this?
(so if there error in line 6, the console will say error in line 6 not line 1)

A: Your JavaScript is ending up as one line because you are making it one line.
while ((inputLine = in.readLine()) != null){
    allLine += inputLine;
    //System.out.println("read : "+inputLine);
}

Try this:
while ((inputLine = in.readLine()) != null){
    allLine += inputLine + "\n"; /* ADD NEWLINE CHARACTER AT END OF LINE */
    //System.out.println("read : "+inputLine);
}


text:
Q: Get a value even if one condition is false Here is my actual query :
SELECT temp.id_company AS id_company
     , temp.code_product AS id_product
     , temp.date_product  AS date_p
FROM (
   SELECT *
   FROM companies
   INNER JOIN products
      ON products.id_company_product = companies.id_company
   WHERE module_key_company = "daL/RqzZcfqc."
   ) AS temp
WHERE temp.code_product = "app_12"

First i get the companies.id_company where companies.module_key_company match "dal....." then i check if i get a match for products.code_product = "app_12" AND products.id_company = companies.id_company i got after the first test.
If both conditions are true, i get what i want. But i also want to get the companies.id_company if there is no match for the products.code_product.
I can't find how i could get the id_company only with the module_key test even if the code_product is wrong.
Thanks for your help.

A: Try this:
SELECT companies.id_company
     , coalese(products.code_product,'NONE') as id_product
     , products.date_product as date_p
FROM companies
LEFT OUTER JOIN products
   ON     products.id_company_product = companies.id_company
      and products.code_product = 'app_12'

WHERE companies.module_key_company = 'daL/RqzZcfqc.'

The id_product column will contain the text NONE and the date_p column will be null for companies that do not have any matching products.  Also, you should use single-quotes to provide character constants, not double-quotes.

A: Hard to tell what your table structure is, unless you are suffixing column names with table names.  So that is what I am guessing.  Try this:
SELECT C.id_company, P.code_product, P.date_product
  FROM Companies AS C
    LEFT OUTER JOIN Products AS P ON P.id_company_product = C.id_company
  WHERE module_key_company = 'daL/RqzZcfqc.'
    AND (P.code_product = 'app_12' OR P.code_product is NULL)

Best,
Joe


text:
Q: Change Node Color based on communities returned from networkX label_propagation_communities I'm using networkX to try and analyze the relations between different songs, and find communities among the songs. I'm using the networkX label_propagation_communities algorithm to try and find these communities and
Since the algorithm returns a dictionary I have just hardcoding the colors manually but that won't be feasible if I start adding more songs into the dataset and there are more communities. I am wondering if there is a simpler way to do this?


text:
Q: Decrypt aes-file in iOS encrypted using a tool from AESCrypt.com I'm working on an app that among other things plays sound files. My problem is the sound files are encrypted with a command line tool that can be found on aescrypt.com just providing the file and a password. I have used the java-code on aescrypt.com to successfully decrypt the files in the android app but I can't for the life of me not get it to work in iOS.
I have tried to decrypt all the bytes of the file and the bytes that does not include the header of the file. I get a result set of bytes back but it won't play and the estimated length of the sound is about one fourth of the actual length.
NSRange range = NSMakeRange(0, self.length);
unsigned char* encrypteddata = malloc(range.length);
[self getBytes:encrypteddata range:range];
size_t outSize;
unsigned char* result = malloc(range.length + 16);
CCCryptorStatus status = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0x00, decryptkey, sizeof(decryptkey), nil, encrypteddata, self.length, result, self.length + 16, &outSize);
NSData *returnData = nil;
if (status == kCCSuccess) {
    returnData = [NSData dataWithBytesNoCopy:result length:outSize];
}

The decryptkey is just the bytes from the password used to encrypt the file.
I have been working on a solution for at least a week now and not made any progress. There are so many things that can be done wrong and so many possible (and impossible) combinations.
Update:
What I need is a tool that is simple enough for our customer to use to encrypt the sound files on their end and also is simple for the apps both on Android and iOS to decrypt on the other end. It does not need to be very secure, it only needs to prevent the common user on Android from just opening and play the file from disc. If aescrypt.com tools isn't optimal for this, I  gladly welcome other suggestions.

A: Why do you stick to that AESCrypt applications? They write their custom header to the encrypted file.
They distribute source code, which will give you enough information about how to decrypt this (and, probably you'll be able to re-use their sources). Check their AESCryptWorkerThreads.cpp in AES crypto source code.

A: The AESCrypt format carries significant configuration information. Most of the format is detailed at their site (aes_file_format.html). This page doesn't explain their custom KDF, unfortunately. You'll have to use or reverse-engineer their encrypt_stream function in aescrypt.c:
// Hash the IV and password 8192 times
memset(digest, 0, 32);
memcpy(digest, IV, 16);
for(i=0; i<8192; i++)
{
    sha256_starts(  &sha_ctx);
    sha256_update(  &sha_ctx, digest, 32);
    sha256_update(  &sha_ctx,
                    (unsigned char*)passwd,
                    (unsigned long)passlen);
    sha256_finish(  &sha_ctx,
                    digest);
}

They don't use CommonCryptor, so if you want hardware-optimized code, you'll have to reimplement this format yourself in CommonCryptor.
Note that your decrypt code has no IV, no KDF, and no HMAC, so anything that actually encrypted that way would be highly insecure. AESCrypt does provide a proper IV and HMAC, and its KDF is likely secure, though non-standard, so it is a reasonable choice.


text:
Q: chkconfig equivalent - RHEL7 In the good old days you would use chkconfig to see if a service was enabled for a run level. E.g.
chkconfig --list tgtd

However, now you're supposed to use systemctl. But I can't get systemctl to give a similarly succinct output as chkconfig.
Any suggestions on how you do so?

A: You can check if it is enabled or disables by using this command:
systemctl list-unit-files --type=service

Where "--type=service" helps you narrow it down to services only.
And you can enable/disable services with commands:
systemctl enable httpd
systemctl disable httpd


text:
Q: Auto backup of MS SQL Server on FTP I have managed to take auto-backup mentioned in the following link on ms sql server express edition.
http://support.microsoft.com/kb/2019698
i would like to know if there is a way i can take this backup automatically on some ftp location.
The above link suggest it to take backup on local drive.


text:
Q: Movie played on Sci-Fi about people with blue or green blood I watched this movie on the Sci Fi Channel sometime between 1992 and 1996. It may have been produced in the late 80s. I vaguely remember watching it as a kid but it took place in the desert. It was most likely low budget and may POSSIBLY be based on a novel.
I think that people in a town started to get sick or started disappearing. I remember a teenage kid getting cut on either a vehicle or construction vehicle and his blood was either blue or green. I also remember towards the end of the movie over a hill in a desert I think, there was some sort of bubble pod or containment that was either lit or blue that was holding people from the town. I think that the main protagonist jumped into it? I don't remember the plot, only smalls bits and pieces. It reminded me of the body snatchers and how people were acting different/getting sick.

A: Possibly The Andromeda Strain:

After a satellite, a U.S. government project code-named Scoop, crashes near the small rural town of Piedmont, New Mexico, almost all of the town's inhabitants die instantly.

It turns out people are infected with an alien microorganism, which is green and turns their blood into crystals.
There are also bio-isolation installations, both in the town and in the research station tasked with combatting the mircoorganism.


text:
Q: Does Android support Apache POI API I am working on PPT VIEWER, The work i want to perform is to convert all slides to images in android. I want to know does android really support Apache POI API.If not,then what other options are present.I would be happy if you provide me a sample code[any example code] of android with Apache POI API support.

A: We can certainly port Apache POI API in Android. The example code that i made is to count the number of slides in a power point presentation with the help of Apache POI.


text:
Q: OneSignal Unsubscribe playerID flutter In my case:
I have 2 options to push:

*

*Use Player ID

*Use Segment

I want to unsubscribe only Player ID, and keep Segment
I've seen:

*

*OneSignalServices.instance.disablePush(true) => But it disable all my pushes.

*Delete user via API:

curl --include \
     --request DELETE \
     --header "Authorization: Basic YOUR_ONESIGNAL_API_KEY" \
https://onesignal.com/api/v1/players/ONESIGNAL_PLAYER_ID?app_id=YOUR_APP_ID

But follow the OneSignal document I need Uninstall the app and re-install the app.
How to do it when the user signs out?

A: Don't send notifications based on player Id instead use an external User Id to send notifications and map your player Id with an external User Id.
In your case, the external User Id will be a random string generated at the time of login and stored in the database as a notification token. Then map this token with the player Id and when the user will logout just delete this token from the database.
Steps Involved:

*

*On user login

*

*Generate a random String and stored it in the database as a notification token.

*Map this notification token with current player ID.
let externalUserId = '123456789'; // You will supply the external user id to the OneSignal SDK
// Setting External User Id with Callback Available in SDK Version 3.9.3+
OneSignal.shared.setExternalUserId(externalUserId).then((results) {
log(results.toString());
}).catchError((error) {
log(error.toString());
});

*Reference Link for mapping: https://documentation.onesignal.com/docs/external-user-ids#setexternaluserid-method

*Send Notification based on this notification Token.

*Reference Link to create notification based on external User Id: https://documentation.onesignal.com/reference/create-notification#platform-to-deliver-to

*On user logout

*

*Delete notification token from your database

Hope this help.


text:
Q: R on Ubuntu 14.04: Error in pdf("Plot.pdf") : cannot open file I'm following textbook instructions to create a file using R and save a plot to it.  When I try to make a pdf I get an error immediately:

pdf("Plot.pdf")
  Error in pdf("Plot.pdf") : cannot open file 'Plot.pdf'

When I try to make a jpeg it gives no error, although I can't find the file on my computer, but when I try to write the plot to it I get the same kind of error.

jpeg("Plot.jpeg")
  plot(x,y,col="green")
  Error in plot.new() : could not open file 'Plot.jpeg'

Could it have something to do with using R on Ubuntu 14.04?

A: The problem was that I had entered R from etc/apt where I was altering sources.list to install R.  I guess R could not make the files in that folder because it's a special system folder and is protected.  Once I returned to my home folder and entered R again everything worked fine.


text:
Q: SQLAlchemy Messing Up Alias In Primary Join For some reason, SQLAlchemy is joining in the target table for my relationship in the secondary join but referencing it with the wrong alias in the primary join.
Here's the python in the Child class:
fact_row = relationship(
        Fact,
        secondary=Parent.__table__
        primaryjoin=and_(
            foreign(child_date_member) == remote(Fact.date_member),
            foreign(Parent.id) == remote(parent_id)),
        secondaryjoin=and_(
            remote(Fact.dimension_1) == foreign(Parent.dimension_1),
            remote(Fact.dimension_2) == foreign(Parent.dimension_2),
            remote(Fact.dimension_3) == foreign(Parent.dimension_3),
        viewonly=True)

Here's the SQL output for the joins:
FROM child
LEFT OUTER JOIN (parent AS parent_1
JOIN fact AS fact_1 ON
    fact_1.dimension_1 = parent_1.dimension_1
    AND fact_1.dimension_2 = parent_1.dimension_2
    AND fact_1.dimension_3 = parent_1.dimension_3) ON
    parent_1.id = child.parent_id
    AND child.child_date_member = fact.date_member

Here's what would work:
FROM child
LEFT OUTER JOIN (parent AS parent_1
JOIN fact AS fact_1 ON
    fact_1.dimension_1 = parent_1.dimension_1
    AND fact_1.dimension_2 = parent_1.dimension_2
    AND fact_1.dimension_3 = parent_1.dimension_3) ON
    parent_1.id = child.parent_id
    AND child.child_date_member = fact_1.date_member

How do I get SQLAlchemy to use the right alias for the child table in the primary join? Right now, it's failing because it can't find the unaliased child table in the query.


text:
Q: Does a timeout on an existing record prove that record exists? If I attempt to edit a record that may (or may not) exist, but get a timeout after a few seconds, can I take that as evidence that the record exists?
Timeouts occur if another transaction hasn't completed on a record, so if I get a timeout then another session must have a lock on that record, therefore the record must exist? Or is there another way a timeout might occur?
Some background.... I have a process that implements an 'upsert'. I attempt to update a record, if the record doesn't exist and the UPDATE fails then I attempt an INSERT. This works fine most of the time, but occasionally the UPDATE fails due to a timeout, then the INSERT fails due to unique constraint violation. Since both failures waste a bit of time, can I just assume that if the UPDATE fails due to a timeout, then there's no point in bothering with the INSERT?
UPDATE - as far as I can tell, there's nothing in the application that might LOCK the whole table (unless there's some background postgres system stuff going on that I don't know about)

A: Does a record in a transaction that was rolled back, or that was just deleted exist? or maybe the table was locked and the record never existed.
Postgresql is going to delay you until it can give an answer.

Some background.... I have a process that implements an 'upsert'. I attempt to update a record, if the record doesn't exist and the UPDATE fails then I attempt an INSERT. This works fine most of the time, but occasionally the UPDATE fails due to a timeout, then the INSERT fails due to unique constraint violation. Since both failures waste a bit of time, can I just assume that if the UPDATE fails due to a timeout, then there's no point in bothering with the INSERT?

Or you could use  INSERT ... ON CONSTRAINT ... DO UPDATE ...
https://www.postgresql.org/docs/14/sql-insert.html


text:
Q: How to get average session duration for a specific user in flurry I am using flurry analytics in my unity game .
In flurry, we are getting average session duration for a specific date or date range. We want to get session duration for all users individually. i.e. assume 10 users played our game today and total no of  session is 25. I like to get session duration for all 25 sessions separately along with user id. is this possible? If yes, can you please share some pointers.

A: It is not possible to get individual session times for each user through Flurry. Flurry session data is geared towards aggregating the session length, to give you an overall idea of how long users are spending in the app, not to drill down to specific user times. The closest metric to what you are describing is The session length distribution chart on the Usage>Session Length page, which distributes the sessions into buckets based on length, so you can see how many sessions of a given range occurred.


text:
Q: AWS Glue Dynamic_frame with pushdown predicate not filtering correctly I am writing an script for AWS Glue that is sourced in S3 stored parquet files, in which I am creating a DynamicFrame and attempting to use pushDownPredicate logic to restrict the data coming in.
The table partitions are (in order): account_id > region > vpc_id > dt
And the code for creating the dynamic_frame is the following:
dynamic_frame = glueContext.create_dynamic_frame.from_catalog(
    database = DATABASE_NAME,
    table_name= TABLE_NAME,
    push_down_predicate = "dt='" + DATE + "'")

where DATE = '2019-10-29'
However it seems that Glue still attempts to read data from other days. Maybe it's because I have to specify a push_down_predicate for the other criteria?

A: As per the comments, the logs show that the date partition column is marked as "dt" where as in your table it is being referred by the name "date"
Logs
s3://route/account_id=XXX/region=eu-west-1/vpc_id=YYY/dt=2019-07-15
s3://route/account_id=XXX/region=eu-west-1/vpc_id=YYY//dt=2019-10-03
s3://route/account_id=XXX/region=eu-west-1/vpc_id=YYY//dt=2019-08-27
s3://route/account_id=XXX/region=eu-west-1/vpc_id=YYY//dt=2019-10-29 ...

Your Code
dynamic_frame = glueContext.create_dynamic_frame.from_catalog(
database = DATABASE_NAME,
table_name= TABLE_NAME,
push_down_predicate = "date='" + DATE + "'")

Change the date partitions column name to dt in your table and same in push_down_predicate parameter in the above code.
I also see extra forward slashes in some of the paths in above logs, were these partitions added manually through athena using ALTER TABLE command? If so, I would recommend to use MSCK REPAIR command to load all partitions in the table to avoid such issues. Extra blank slashes in S3 path some times lead to errors while doing ETL through spark.


text:
Q: PHP PCRE error preg_replace <?php
    function pregForPreg($value)
    {
        $value = preg_replace(array('#\(#', '#\)#', '#\+#', '#\?#', '#\*#', '#\##', '#\[#', '#\]#', '#\&#', '#\/#', '#\$#', '#\\\\#'), array('\(', '\)', '\+', '\?', '\*', '\#', '\[', '\]', '\&', '\/', '\\\$', '\\\\'), $value);
        return $value;
    }

    $var = "TI - Yeah U Know [OFFCIAL VIDEO] [TAKERS] [w\LYRICS]";

    $var = pregForPreg($var);
    //$var is now:
    //    TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
    $var = preg_replace("#" . $var . "#isU", 'test', $var);
    echo $var;

And I get an error: *Warning: preg_replace(): Compilation failed: PCRE does not support \L, \l, \N, \U, or \u at offset 50 in test.php on line 13.*
How to make a correct function pregForPreg?

A: It seems you want to escape special regex characters. This function already exists and is called preg_quote().

You get the error, because you don't escape \ properly:
TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\LYRICS\]
//                   this is not escaped   ------^

and \L has special meaning in Perl regular expression:

\L  Lowercase until \E

but is not supported in PHP's PCRE (Perl Differences):

The following Perl escape sequences are not supported: \l, \u, \L, \U. In fact these are implemented by Perl's general string-handling and are not part of its pattern matching engine.

Update:
Obviously, you cannot use the escaped version as value and as pattern, because in the pattern \[ will be treated as [ and but in the value \[ is taken literally. You have to store the escaped string in a new variable:
$var = "TI - Yeah U Know [OFFCIAL VIDEO] [TAKERS] [w\LYRICS]";

$escaped = preg_quote($var);
echo $escaped . PHP_EOL;
// prints "TI - Yeah U Know \[OFFCIAL VIDEO\] \[TAKERS\] \[w\\LYRICS\]"
$var = preg_replace('#' . $escaped . '#isU', 'test', $var);
echo $var;
// prints test

or easier:
$var = preg_replace('#' . preg_quote($var) . '#isU', 'test', $var);

Side note: If you really wanted to match \[ in a string, the regular expression would be \\\\\[. You see, it can get quite ugly.


text:
Q: Send Form fields to jquery I'm trying to pass all my form fields, to a ajax function where i will insert the user into the database.
But for some reason, my alert (in my JS file) isn't showing anything.
Any ideas what i'm doing wrong?
My HTML:
        <form id="signupForm">
            <input id="signupFormEmail" type="text" name="email" placeholder=" E-mail">

            <input id="signupFormPassword" type="text" name="password" placeholder=" Password">

            <input id="signupFormUsername" type="text" name="userName" placeholder=" User Name">

            <input id="submitSignup" type="button" value="SIGN UP" onclick="signUp(this);">
        </form>

My javascript file:
function signUp(elem)
{
var postData = $(this).serializeArray();

//$('#myResults').html(postData);
alert($.param($(elem).serializeArray()));

if($(elem).parent().children('#signupFormEmail').val() != ''){
    // verifica se o email já existe
    $.ajax(
    {
          url: "/newsletter/check-email/",
          type: "POST",
          data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
    }).done(function(response)
    {
        if(response == -1) {
            $.ajax(
            {
              url: "/newsignup/registare/",
              type: "POST",
              data: postData
            }).done(function(userCreated) {
                if(userCreated == 1) {
                alert('user created');
                    /*
                    $(elem).parent().children('#signupForm').val('');
                    $('#signUpCompleted').show();
                    */
                }
                else
                {
                    /*$('#signUpError').show();*/
                    alert('user not created');
                }
            })

            //testing
            //$('#signUpCompleted').show();
        }
        else //testing
        {
            $('.emailError').show(); //testing
        }

    }
    );
}
}

A: It looks like you are serializing the element itself. You have to serialize the form, please check this out.
function signUp(elem)
    {
    var postData = $('form').serialize();
    //$('#myResults').html(postData);
    alert(postData);

    if($(elem).parent().children('#signupFormEmail').val() != ''){
        // verifica se o email já existe
        $.ajax(
        {
              url: "/newsletter/check-email/",
              type: "POST",
              data: {type:'check',email:$(elem).parent().children('#signupFormEmail').val()}
        }).done(function(response)
        {
            if(response == -1) {
                $.ajax(
                {
                  url: "/newsignup/registare/",
                  type: "POST",
                  data: postData
                }).done(function(userCreated) {
                    if(userCreated == 1) {
                    alert('user created');
                        /*
                        $(elem).parent().children('#signupForm').val('');
                        $('#signUpCompleted').show();
                        */
                    }
                    else
                    {
                        /*$('#signUpError').show();*/
                        alert('user not created');
                    }
                })

                //testing
                //$('#signUpCompleted').show();
            }
            else //testing
            {
                $('.emailError').show(); //testing
            }

        }
        );
    }
    }

A: In your onclick attribute, this is not the FORM; this is the button you clicked.


text:
Q: incompatible types port Bluemix JAVA SQL I've been trying to connect SQL on BlueMix for a while.
I'm getting the error on:
port = ((int) obj.get("port"));
Incompatible types.
I copied the code from the demo supplied:
https://hub.jazz.net/project/pvanrun/SQLDBJava/overview
I tried to flip it around to:
port = Integer.valueOf((String) obj.get("port"));

However, I get this error:
Exception thrown by application class 'com.ibm.callcenter.data.SQLDatabase.processVCAP:144'
java.lang.ClassCastException: java.lang.Integer incompatible with java.lang.String
at com.ibm.callcenter.data.SQLDatabase.processVCAP(SQLDatabase.java:144)
at com.ibm._jsp._index._jspService(_index.java:98)
at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:101)
at [internal classes]

A: Seems like a similar question has been asked on developerWorks here:
https://developer.ibm.com/answers/questions/20560/issue-connecting-to-sqldb-service-instance-from-java-struts-app.html
Port is an integer. Try change
 port = (String) obj.get("port");

to Integer
 port = (Integer) obj.get ("port");

Or use the 'jdbcurl' attribute inside the SQLDB VCAP services:
 connectionUrl = (String) obj.get("jdbcurl");


text:
Q: Running Batch File on Multiple text Files I have a simple batch file that deletes the first 26 lines of a text file specified by the batch file on the desktop.
more +26 "data (1).txt" >"data (1).txt.new"

move /y "data (1).txt.new" "data (1).txt"

What I want to be able to do is run this on multiple text files with similar naming conventions such as data (1).txt, data (2).txt, data (3).txt, with the number of files fluctuating week to week.
I would also like for the program to be able to search for the file in its actual location and not have to bring the text files to the desktop to be able to run it.
Any help is appreciated. Thanks.

A: @ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir\one"
FOR %%a IN ("%sourcedir%\*(*).txt") DO (
 ECHO(MORE +26 "%%a" GTR "%%a.new"
 ECHO(MOVE /y "%%a.new" "%%a"
)

GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.
The required MORE/MOVE commands are merely ECHOed for testing purposes. After you've verified that the commands are correct, change ECHO(MOVE to MOVE and ECHO(MORE to MORE to actually process the files. Append >nul to suppress report messages (eg. 1 file moved) on the MOVE and change GTR to > on the MORE.
This assumes you know which directory contains the files and that the files to be processed conform to the pattern *(*).txt. If the requirement is actually for data(*).txt then change *(*) to that.


text:
Q: Swift UTF8 encoding and non UTF8 character I've a some text from json file. In this text I've applied UTF8 encode but this encoder don't recognize a non standard character àèìòù and it's capital char, is there a method to purify my string?
My function:
func stringToUTF8String (stringaDaConvertire stringa: String) -> String {
    let encodedData = stringa.dataUsingEncoding(NSUTF8StringEncoding)!
    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
    //println(attributedString.string)
    return attributedString.string
}

A: I've found a solution.
The UTF8 take 8 bit of table ASCII, and the UTF16 take 16 bit ASCII table, the solution is simple by modifying my function to:
func stringToUTF16String (stringaDaConvertire stringa: String) -> String {
    let encodedData = stringa.dataUsingEncoding(NSUTF16StringEncoding)!
    let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
    let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
    //println(attributedString.string)
    return attributedString.string
}


text:
Q: Python struct unpack multiple bytes with reverse endianess So I have a buffer with N bytes and i read them with this, which works but has the reverse endianness from the one i need.
buffer=struct.unpack_from( 'h'*(N/2), databuff)
I noticed that endianness is reverse so I wanna experiment with endianess and I use this
buffer=struct.unpack_from( '<h'*(N/2), databuff)
However I get this error:
>>>buffer=struct.unpack_from( '<h'*1344, databuff) struct.error: bad char in struct format

How do I reverse endianness on multiple bytes?

A: You specify endianness at most once in a format, so write
buffer=struct.unpack_from('<'+'h'*(N//2), databuff)

where the // is Python 3 futureproofing.


text:
Q: Set Attribute With Same Name As Databse Field in Laravel returns Error I have a problem in my Project. I have  a field Name contact_number where I stored json data in this format {"code":"","number":""}. I want to set Two Attribute name getCountryCodeAttribute and getContactNumberAttribute so that I can access code and number individually. But it Throws error
Undefined property: App\Models\Profile::$contact_number

My Model Code Is
?php

namespace App\Models;

class Profile extends Model
{
    use SoftDeletes;
    protected $guarded = [];

    protected $casts = [
        'contact_number' => 'array',
    ];

    public function getCountryCodeAttribute()
    {
        $contact_number = $this->contact_number;
        return $contact_number['code'];
    }

    public function getContactNumberAttribute()
    {
        $contact_number = $this->contact_number;
        return $contact_number['number'];
    }

}

I don't know how to solve this. Thanks in advance for your help

A: *

*You already have a field named contact_number, but you want to defined a attribute contract_number, this is a mistake, try to use another name.

*Your contract_number is an json format. After you take it out from database, it need to be decoded, or it will be string, so you cannot  use $contact_number['number'] too.

public function getProfileContractCodeAttribute()
{
    $contact_number = json_decode($this->contact_number, true);
    return $contact_number['code'];
}

public function getProfileContractNumberAttribute()
{
    $contact_number = json_decode($this->contact_number, true);
    return $contact_number['number'];
}

so you can get attribute like this:
Profile::find(1)->profile_contract_number;

A: Within the accessor you can not access the property. So it's Undefined
    public function getContactNumberAttribute()
    {
        $contact_number = $this->contact_number;//$this->contact_number is not valid
        return $contact_number['number'];
    }

change ContactNumber part to something else like PhoneNumber
    public function getCountryCodeAttribute()
    {
        $contact_number = $this->contact_number;

        return $contact_number['code'];
    }

    public function getPhoneNumberAttribute()
    {
        $contact_number = $this->contact_number;

        return $contact_number['number'];
    }

and then access it like this.
    dd(User::find(1)->phone_number);
    dd(User::find(1)->country_code);

A: try it with json_decode
public function getCountryCodeAttribute()
{
    $contact_number = json_decode($this->contact_number);
    return $contact_number['code'];
}

public function getContactNumberAttribute()
{
    $contact_number = json_decode($this->contact_number);
    return $contact_number['number'];
}


text:
Q: Silver Light : How to set unit as constant in a textbox I want to display some value in a TextBox in Silverlight, but I need to set a unit value that remains constant.
Example:
100 gpm
I need to change the value (100), but the unit (gpm) should always stay static.
Here is my current Binding.
<TextBox Text="{Binding Path=Current.SystemDemand,Mode=TwoWay}" />

A: If you are using Binding on the TextBox You can set the Format of the Binding.
Here is how you set the format in Xaml
<TextBox x:Name="myTextBox" Text="{Binding Path=Current.SystemDemand, Mode=TwoWay, StringFormat='\{0} gpm'}" />

A: What the question author's approach and the accepted answer have in common is that they mix up the (editable) value and the (non-editable) unit.
Why not place an ordinary TextBlock containing the unit near the end of your TextBox?
You can even use a Grid to have the unit appear "inside" the TextBox.
<Grid>
    <TextBox Text="{Binding...StringToNumberConverter...etc}" Padding="0,0,24,0"/>
    <TextBlock Text="gpm" HorizontalAlignment="Right" IsHitTestVisible="false"/>
</Grid>


text:
Q: MySQL still holding memory after I shut it down? I used this command to shutdown MySQL, however it seems the amount of free memory on my box has not changed?
That seems to odd.
/usr/local/webserver/mysql/bin/mysqladmin -u ${mysql_username} -p${mysql_password} -S /data0/mysql/mysql.sock shutdown
Does anyone know why the free memory might not change very much after unloading MySQL?

A: Memory management is a complex beast. If you are on a linux or similar platform, you might be seeing differences because of the page cache. This is a good writeup of what the page cache is.

A: Linux systems always try to use a much ram as available for various functions like caching of executables our even just page reads from disk. That's what you bought your fast RAM for after all.
You can find out more about your system by doing a
cat /proc/meminfo

More info in this helpful blog post
If you find out a lot is used in cache then you don't have to worry about the system. Like Kormoc says the difference is no doubt the fact that certain pages on disk are still cached and will stay cached for a while until the system needs memory or some other settings deem it unnecessary to cache for read-access anymore.


text:
Q: C# How can I run an msi installation package as a different user I need to be able to install crystal reports on end user computers, but the network security wont allow it on a normal user login, so it has to be 'run as a different user' to install on each desktop.
I am trying to create a small application which will allow any user to install crystal reports..  so far I have:
        Process p = new Process();
        p.StartInfo.FileName =   @"C:\cabs\CRRuntime_32bit_13_0_5.msi";
        p.StartInfo.Arguments = "/i \"C:\\Application.msi\"/qn";
        p.StartInfo.UserName = uname;
        p.StartInfo.Password = pword;
        p.StartInfo.Domain = domain;
        p.StartInfo.UseShellExecute = false;

        try
        {
            p.Start();
        }
        catch(Exception er)
        {
            MessageBox.Show(er.Message);
        }

When I try to run this code, I see the message "The specified executable is not a valid application for this OS platform"
did I miss something out?
CHeers

A: MSI is not a executable file in windows. You should call msiexec with you msi file as parameter
Process p = new Process();
p.StartInfo.FileName =   @"C:\Windows\System32\msiexec.exe";
p.StartInfo.Arguments = @"C:\cabs\CRRuntime_32bit_13_0_5.msi";
p.StartInfo.UserName = uname;
p.StartInfo.Password = pword;
p.StartInfo.Domain = domain;
p.StartInfo.UseShellExecute = false;


text:
Q: print readable variables with golang How to print a map, struct or whatever in a readable way?
With PHP you can to this
echo '
';
print_r($var);
echo '
';

or
header('content-type: text/plain');
print_r($var);

A: You can use fmt.Println() to print. You will need to import the "fmt" package (see the example below). Many data types can be printed out of the box. If you want to get a human-readable print for custom types, you'll need to define a String() string method for that type.
To try the following example, click here: http://play.golang.org/p/M6_KnRJ3Da
package main

import "fmt"

// No `String()` method
type UnstringablePerson struct {
    Age int
    Name string
}

// Has a `String()` method
type StringablePerson struct {
    Age int
    Name string
}

// Let's define a String() method for StringablePerson, so any instances
// of StringablePerson can be printed how we like
func (p *StringablePerson) String() string {
    return fmt.Sprintf("%s, age %d", p.Name, p.Age)
}

func main() {
    // Bobby's type is UnstringablePerson; there is no String() method
    // defined for this type, so his printout will not be very friendly
    bobby := &UnstringablePerson{
        Age: 10,
        Name: "Bobby",
    }

    // Ralph's type is StringablePerson; there *is* a String() method
    // defined for this type, so his printout *will* be very friendly
    ralph := &StringablePerson{
        Age: 12,
        Name: "Ralph",
    }
    fmt.Println(bobby) // prints: &{10 Bobby}
    fmt.Println(ralph) // prints: Ralph, age 12
}

A: https://github.com/davecgh/go-spew

Go-spew implements a deep pretty printer for Go data structures to aid in debugging.

A: fmt.Printf("%v", whatever)

In Go is like print_r(), var_dump(), var_export() in PHP. (The %v is the important part.)
Good Luck

A: Use the Go fmt package. For example,
package main

import "fmt"

func main() {
    variable := "var"
    fmt.Println(variable)
    fmt.Printf("%#v\n", variable)
    header := map[string]string{"content-type": "text/plain"}
    fmt.Println(header)
    fmt.Printf("%#v\n", header)
}

Output:
var
"var"
map[content-type:text/plain]
map[string]string{"content-type":"text/plain"}

Package fmt
import "fmt"

Overview
Package fmt implements formatted I/O with functions analogous to C's
  printf and scanf. The format 'verbs' are derived from C's but are
  simpler.

A: I think in many cases, using "%v" is concise enough:
fmt.Printf("%v", myVar)

From the fmt package's documentation page:

%v    the value in a default format.
        when printing structs, the plus flag (%+v) adds field names
%#v   a Go-syntax representation of the value

Here is an example:
package main

import "fmt"

func main() {
    // Define a struct, slice and map
    type Employee struct {
        id   int
        name string
        age  int
    }
    var eSlice []Employee
    var eMap map[int]Employee

    e1 := Employee{1, "Alex", 20}
    e2 := Employee{2, "Jack", 30}
    fmt.Printf("%v\n", e1)
    // output: {1 Alex 20}
    fmt.Printf("%+v\n", e1)
    // output: {id:1 name:Alex age:20}
    fmt.Printf("%#v\n", e1)
    // output: main.Employee{id:1, name:"Alex", age:20}

    eSlice = append(eSlice, e1, e2)
    fmt.Printf("%v\n", eSlice)
    // output: [{1 Alex 20} {2 Jack 30}]
    fmt.Printf("%#v\n", eSlice)
    // output: []main.Employee{main.Employee{id:1, name:"Alex", age:20}, main.Employee{id:2, name:"Jack", age:30}}

    eMap = make(map[int]Employee)
    eMap[1] = e1
    eMap[2] = e2
    fmt.Printf("%v\n", eMap)
    // output: map[1:{1 Alex 20} 2:{2 Jack 30}]
    fmt.Printf("%#v\n", eMap)
    // output: map[int]main.Employee{1:main.Employee{id:1, name:"Alex", age:20}, 2:main.Employee{id:2, name:"Jack", age:30}}
}

A: For debugging I use this:
func printVars(w io.Writer, writePre bool, vars ...interface{}) {
    if writePre {
        io.WriteString(w, "
\n")
    }
    for i, v := range vars {
        fmt.Fprintf(w, "» item %d type %T:\n", i, v)
        j, err := json.MarshalIndent(v, "", "    ")
        switch {
        case err != nil:
            fmt.Fprintf(w, "error: %v", err)
        case len(j) < 3: // {}, empty struct maybe or empty string, usually mean unexported struct fields
            w.Write([]byte(html.EscapeString(fmt.Sprintf("%+v", v))))
        default:
            w.Write(j)
        }
        w.Write([]byte("\n\n"))
    }
    if writePre {
        io.WriteString(w, "
\n")
    }
}

playground


text:
Q: SSO: Azure AD idp + external API Callout from Apex? Question:

*

*When a user is signed into SF with Azure AD identity provider (SSO), we want to send the current identity (in the form of a Saml assertion, bearer token, etc?) along with the external API callout request, to auth the API call.  Do you have any advice, guidance, or tips based on your experience?

Background:

*

*We have watched https://www.pluralsight.com/courses/play-by-play-salesforce-understanding-single-sign-on

*We have read numerous, numerous tutorials and documentation pages in Salesforce, Azure, and various blogs.

*We have successfully implemented SSO with Azure AD (SAML based).

*We are in the process of figuring out how to set up Auth Provider to Azure AD as well, as another approach option.

*We are also building the external API - the API could accept OpenID or SAML based auth info - we're in control.  We're posting data in the outbound callout to this external API (SF -> API).

Problems:

*

*The issue we're facing is trying to figure out how to send the auth (either Saml assertion or Oauth token from user's session) along with the external API callout request.

*There is no clear how-to documentation or example code on how to do this.

Possible approaches we've brainstormed / we're exploring:

*

*Saml to SSO user into SF.  This is our fallback approach if none of the others below work.  All the code would be in Apex.  We would use "client credential" flow to establish machine-to-machine connection between SF and the External API. This does not use the signed in user's credentials though so it's not really achieving the use case of leveraging the current user's logged in session (api call audit trail..).  But maybe it's the only way we can make the external callout work?

*Saml to SSO user into SF.  Then all API external calls happen in a Lightning Web Component (LWC)? There is little or no Apex code here.  This would be let the browser and javascript handle saml redirects when invoking the API with a post.  This option is all theory at this point and I don't actually know how it would work and I cannot find any sample code.

*Saml to SSO user into SF.  Then exchange a saml assertion for oauth token: https://feedback.azure.com/forums/169401-azure-active-directory/suggestions/19728688-support-for-oauth-2-0-saml-bearer-assertion-flow  The code would all be in Apex. I cannot find any sample code to support this approach.  And I'm not even sure how to access or build a Saml assertion when in Apex code.

*Named credential approach.  Could use either Saml SSO or Azure AD Auth Provider (using Open ID Connect) to sign user into SF.  Or have both where Saml handles SSO and Auth Provider handles API auth.  The Named credential would pass the auth info to external API?  I know you can reference an Auth Provider in the Named Credential but I cannot find how to configure Named Credentials with Saml SSO only.  Apex code would reference the Named Credential and "Just work"?  I cannot find example Apex code though, other than something like this. . . but how is auth set?

    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('callout:MY_API_URL/');
    request.setMethod('POST');
    request.setHeader('Content-Type', 'application/json;charset=UTF-8');
    request.setBody(JSON.serialize(orderPayload));
    HttpResponse response = http.send(request);
    return response;

A: We went with SAML SSO, Azure App registration (when publishing API), Auth Provider in SF (to get token for use with API), and Named Creds (to tie it all together):
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
https://help.salesforce.com/articleView?id=sso_provider_microsoft.htm&type=5

A: You don't need to do anything custom. If you use open ID connect then the authentication provider will store the access token and the refresh token in the platform for you so that when you want to call out to your third party system you can simply use Apex to retrieve those tokens. Note that the refreshing of the token is also handled for you.
That said this only applies if you use open ID connect to begin with

A: Have you considered using a custom login flow? https://help.salesforce.com/articleView?id=security_login_flow_examples.htm&type=5
This would execute as part of the user authentication process.
You can use an APEX class in your login flow to call your external web service / API endpoint.
Re: named credential in APEX, please refer to the ff. link: https://help.salesforce.com/articleView?id=named_credentials_about.htm&type=5


text:
Q: Processing sketch crashes on PVector set I've been working on a game in Processing and I came upon this problem: I'm trying to make a background with stars flying past and I have this class:
public class Star {
  PVector position;
  float speed;

  void draw() {
    fill(255);
    ellipse(position.x, position.y, speed, speed);

    position.x -= speed;
  }

  public Star() {
    speed = random(5);
    position.set(width+speed,random(height));
  }
}

I have an ArrayList for Stars called stars:
ArrayList<Star> stars = new ArrayList<Star>();

I call the constructor in a function drawBg():
if(random(12) < 1) {
  stars.add(new Star());
}

But when drawBg is called and it creates a new Star(), the sketch crashes and it points to:
position.set(width+speed,random(height));

The IDE says "Could not run the sketch", and the console says:

Could not run the sketch (Target VM failed to initialize). For more
  information, read revisions.txt and Help ? Troubleshooting.

Please help! Thank you!

A: By default, your position variable is null, meaning it doesn't point to an instance of PVector yet.
You never initialize that variable (using the new keyword to create a new instance of PVector), so it's still null when you call position.set() in the Star constructor. That causes an error, since you can't call a function on a null variable.
To fix this, just use the new keyword to create a new instance of PVector:
public Star() {
    speed = random(5);
    position = new PVector(width+speed,random(height));
}


text:
Q: How to get last matching value using multiple criteria I'm trying to do a lookup based on 2 criteria to match on another sheet and return a value from the last match that it finds.
I've been able to get this logic working with a single criteria:
=INDEX('Rank History'!B:E, MAX(filter(ROW('Rank History'!E:E), 'Rank History'!E:E=C3)),3)
and I've been able to do it with multiple criteria:
=INDEX('Rank History'!D:D, MATCH(1, (B3='Rank History'!B:B) * (C3='Rank History'!E:E), 0))
How do I tie these two approaches together?

A: Try this:
=INDEX('Rank History'!D:D, MATCH(2, 1 / ((B3='Rank History'!B:B) * (C3='Rank History'!E:E))))


text:
Q: install php70-gd on ubuntu Recently the new php7 has been released. However, when I am trying to install the gd package, the library can not be found.
I have tried through
sudo apt-get install php70-gd

and
sudo apt-get install php70-php-gd

Does anybody have an idea if gd is available for php 7?

A: my php version is 7.1
sudo apt-get install php7.1-gd

this command is work for me

A: just try
sudo apt-get install php7.0-gd

i got it working that way.
Greetings.

A: PHP7 packages for Ubuntu including php7.0-gd can be installed via PPA for PHP by Ondřej Surý:
sudo add-apt-repository ppa:ondrej/php
sudo apt-get update

Next, install the desired version:
sudo apt-get install php7.0-gd
# or
sudo apt-get install php7.1-gd
# or
sudo apt-get install php7.2-gd
# or
sudo apt-get install php7.3-gd
# or
sudo apt-get install php7.4-gd

EDIT:
As MacroMan stated, under Ubuntu 16.04 you don't need to add the repository any more. Simply issuing sudo apt-get install php7.0-gd works.

A: In 2018, there is an alias package for this:
sudo apt-get install php-gd
Use this to retrieve the last version.

A: For
Ubuntu 16.04.4 LTS
this is the command:
sudo apt-get install php7.0-gd

A: check php verison first using
php -v

It will give version number suppose your version is 7.0.1 then use this command to install GD Library
 sudo yum install php70-gd

OR use this command depending upon server specification
sudo apt-get install php7.0-gd


text:
Q: Clarification on purpose of style resets Do CSS resets operate above or beneath subsequent CSS styling changes? In other words, a random example:
If a reset normalizes the  to being Times New Roman and size 12 font across all browsers, but I then apply a custom CSS that makes all of  tags within  bold.
Thus the purpose of a CSS reset is really to impose consistency across browsers on elements that you do not custom style? Please let me know if I'm understanding this correctly.
Thanks in advance for all answers!

A: The purpose of the CSS reset is to help make your page look consistent across all browsers.  Here is a very detailed article on the subject by Eric Meyer.
Basically all browsers have different defaults for their CSS presentation, but these defaults are not the same.  The CSS reset file attempts to create a consistent baseline across all the browsers.

A: The CSS resets are to standardize the rendering of the HTML elements across different browsers as much as possible. It creates a common ground onto which you can build various styles. The resets are placed before every other stylesheet so the custom style takes effect. However, chances are that the custom styles you have does not cover every single attribute the browser default has on the element, and results in browser inconsistencies.
In your example you have "bold tags", so instead of having just "Times New Roman and size 12 font", you have text in bold, but you haven't specify the margin or line-height of the element. In the event that different browsers have different interpretation on those styles that are not covered, and you haven't used a CSS reset, you will see the inconsistencies affecting your layout and style.

A: You pretty much answered your own question.  Moreso than resetting fonts like in your example, it also resets margins and paddings to 0.  This helps in structuring your layout as having margins and paddings left over from not using a reset style sheet can throw your layout off etc.
It is there to normalize every element in preparation for your custom styling.  If you do not plan on custom styling then you shouldn't use it.
There is also a newer way of doing this called normalize.css.  It is an alternative to reset stylesheets.  Instead of resetting eveything to 0, it pre-styles everything to a standard that most people in the industry follow to an extent.
To summarize and correct your statement above: "Thus the purpose of a CSS reset is really to impose consistency across browsers on all elements in preparation for custom styling."


text:
Q: Open HFT Chronicle Map , Class Not Found Exception on Websphere I am trying to use OpenHFT ChronicleMap , the code runs in Tomcat, but fails in Websphere with the following error (below)
Note : This does not happen in Tomcat , only with Websphere.
code :
private ChronicleMap<String,RepositoryItem> repositoryMap;

repositoryMap=
            ChronicleMapBuilder
            .of(String.class, RepositoryItem.class).averageKeySize(KEY_SAMPLE.getBytes("UTF-8").length)
            .entries((long) (MAX_ENTRIES))
            .averageValueSize(1600)
            .create();

public void removeAllModified() {
    // This removes all the modified data from the repository
    Iterator iter=repositoryMap.values().iterator();
    // build a list of all the objects in the repository except the removed items
    while (iter.hasNext()){
        RepositoryItem repoItem=(RepositoryItem)iter.next();
        DataObject d = repoItem.getModified();
        if (d != null) {
            removeModified(repoItem);
        }
    }
}

Can anyone help me on how to resolve this error.
SystemErr     R     at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
[5/30/16 12:45:03:236 IST] 0000007a SystemErr     R Caused by: java.lang.ClassNotFoundException: java.lang.AbstractStringBuilder
[5/30/16 12:45:03:236 IST] 0000007a SystemErr     R     at java.lang.Class.forName(Class.java:182)
[5/30/16 12:45:03:236 IST] 0000007a SystemErr     R     at net.openhft.lang.io.StringBuilderUtils.<clinit>(StringBuilderUtils.java:36)
[5/30/16 12:45:03:236 IST] 0000007a SystemErr     R     ... 81 more
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R java.lang.NoClassDefFoundError: net.openhft.lang.io.StringBuilderUtils (initialization failure)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at java.lang.J9VMInternals.initialize(J9VMInternals.java:176)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.lang.io.NativeBytes.readUTF1(NativeBytes.java:173)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.lang.io.NativeBytes.readUTF0(NativeBytes.java:164)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.chronicle.hash.serialization.internal.CharSequenceReader.read(CharSequenceReader.java:67)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.chronicle.hash.serialization.internal.CharSequenceReader.read(CharSequenceReader.java:31)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.chronicle.map.VanillaChronicleMap$Segment.getEntry(VanillaChronicleMap.java:3042)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.chronicle.map.VanillaChronicleMap$EntryIterator.next(VanillaChronicleMap.java:3150)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at net.openhft.chronicle.map.VanillaChronicleMap$EntryIterator.next(VanillaChronicleMap.java:3097)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at java.util.AbstractMap$2$1.next(AbstractMap.java:396)
[5/30/16 12:45:03:267 IST] 0000007a SystemErr     R     at com.csc.fs.om.ObjectRepositoryChronicleImpl.removeAllModified(ObjectRepositoryChronicleImpl.java:1335)

A: Chronicle Map currently doesn't support the IBM JVM, on which Websphere runs. From your message it's indeed evident, that Chronicle Map 2 fails on the IBM JVM because it occasionally use some classes which are persent in OpenJDK/OracleJDK but absent in the IBM JDK.
Chronicle Map 3 might not have this issue, so potential solution could be to upgrade to Java 8 and Chronicle Map 3. However this would be an incidental property of Chronicle Map 3 and it also could stop working with IBM JVM in any subsequent release.
The releavant discussion in the Chronicle mailing list: https://groups.google.com/forum/#!topic/java-chronicle/cAHVQZLASaE


text:
Q: Pass objects from javascript to Chart.JS through EJS I have an object (data) coming from a js file.
router.get('/participant-module',(req,res)=>{

    let sql = dbModel.participant_per_module;
    db.query(sql, (err, result)=>{
        if(err) throw err;
        res.render('dashboard', {title:'Get', data:result});
        console.log(result);
    });
});

data contains two arrays; emp_id and module_id;
I wanted to pass this variable data to Chart JS data in ejs.
  let pchart = new Chart(myChart, {
            type:'bar',
            data:{
              labels: '<%=data.emp_id%>',
                datasets:[{
                    label:'p',
                    data:[123,234,533,232]
                }]
            }
        })

But it returns null (i.e. labels = '')
Am I missing something? I have tried different ejs tag like <%- but it returns the same.
Kind regards,
D

A: Data is an array of objects. You can access the emp_id in following manner using backtick:
labels: `<%= data[0].emp_id %>`, `<%= data[1].emp_id %>`, ... , `<%= data[n].emp_id %>`

you can also push the emp_ids into another array and then use that array as labels.
var Data = JSON.parse(`<%- JSON.stringify(data) %>`);
var labelsData = [];
for(var i = 0; i < Data.length; i++){
   labelsData.push(Data[i].emp_id);
}

let pchart = new Chart(myChart, {
    type:'bar',
    data:{
      labels: labelsData,
      datasets:[{
        label:'p',
        data:[123,234,533,232]
      }]
    }
})


text:
Q: Recursive equation implementation issue I was given an assignment a few months ago that had a handful of random components. One was a recursive function that had a lot of fluff to it but shouldn't have been too hard. However, I couldn't figure out how to write it. I've gone back to it and I still can't quite figure it out. You can see the full assignment here if you'd like: http://www.cs.fsu.edu/~asriniva/courses/DS14/projs/proj2.html
I'm only dealing with the section called main.cpp:
This is a program to evaluate a recursive function. It has nothing to do with the previous part of the assignment. The command: ./recurse N1 C1 A1 M1 M2 M3 M4 D1 D2 S1 S2 Arg Op will cause the function given below to be evaluated recursively and the answer output. The function is defined as follows.
f(N) = 0, if N < N1

f(N1) = C1

f(N)= A1 + M1*f(M2*N/D1 - S1) Op M3*f(M4*N/D2 - S2), if N > N1

Here, f(Arg) needs to be evaluated. N1 C1 A1 M1 M2 M3 M4 D1 D2 S1 S2, Arg are integers and Op is either + or -. The division performed is the usual integer division with truncation.
I got a semi working program but, first, it uses some global variable, second, I get a warning "recurse.cpp:37: warning: control reaches end of non-void function", and, most importantly, it doesn't actually work. I gives a result that is incorrect but its better than my original attempt that couldn't actually give a result. Please help me understand how to get this thing working, I've spent more time than I'd like trying to by myself.
This is supposed to run on a unix machine with an executable call followed by command line arguments. Like so: Prompt> ./recurse 2 3 2 1 2 0 1 3 6 0 0 18 +
13 (program output)
#include <iostream>
#include <cstdlib>
using namespace std;

char * Op;
int N1;
int C1;
int A1;
int M1;
int M2;
int M3;
int M4;
int D1;
int D2;
int S1;
int S2;

int recurse(int N){

if (N < N1){
    return 0;
}
if (N == N1){
    return C1;
}
if (N > N1){

    if (*Op == '+')
        return (A1 + M1 * recurse((M2*N / D1 - S1)) + M3 *
            recurse((M4*N / D2 - S2)));
    else
        return (A1 + M1 * recurse((M2*N / D1 - S1)) - M3 *
            recurse((M4*N / D2 - S2)));
}
}

int main(int argc, char* argv[]){

N1 = atoi(argv[1]);
C1 = atoi(argv[2]);
A1 = atoi(argv[3]);
M1 = atoi(argv[4]);
M2 = atoi(argv[5]);
M3 = atoi(argv[6]);
M4 = atoi(argv[7]);
D1 = atoi(argv[8]);
D2 = atoi(argv[9]);
S1 = atoi(argv[10]);
S2 = atoi(argv[11]);
Op = argv[12];

int val;
if (*Op == '+')
    val = ( ( A1 + M1 * recurse(M2 / D1 - S1) + M3 *
        recurse(M4 / D2 - S2) ) );
else
    val = ( ( A1 + M1 * recurse(M2 / D1 - S1) - M3 *
        recurse(M4 / D2 - S2) ) );

cout << val << endl;

return 0;
}

Thanks for the help!

A: You main problem is that you don't provide the first N to your function. You're initializing 12 variables:
N1 = atoi(argv[1]);
C1 = atoi(argv[2]);
A1 = atoi(argv[3]);
M1 = atoi(argv[4]);
M2 = atoi(argv[5]);
M3 = atoi(argv[6]);
M4 = atoi(argv[7]);
D1 = atoi(argv[8]);
D2 = atoi(argv[9]);
S1 = atoi(argv[10]);
S2 = atoi(argv[11]);
Op = argv[12];

However you pass 13 arguments to the command: N1 C1 A1 M1 M2 M3 M4 D1 D2 S1 S2 Arg Op. So you are not collecting the value of Arg wich I guess has to be stored in N.
On the other hand, is not good practice to use global variables. You could write better code using a functor.
struct Recurse
{
    Recurse(){}
    int N1, C1, A1, M1, M2, M3, M4, D1, D2, S1, S2;
    string Op; // Since you're using C++ you can use string instead char *.
    int operator()(int N);
};

int Recurse::operator()(int N)
{
    if (N < N1)
        return 0;

    if (N == N1)
        return C1;

    if (N > N1)
    {
        if (Op == "+")
        {
            return (A1 + M1 * this->operator()((M2*N / D1 - S1)) + M3 * this->operator()((M4*N / D2 - S2)));
        }
        else
        {
            return (A1 + M1 * this->operator()((M2*N / D1 - S1)) - M3 * this->operator()((M4*N / D2 - S2)));
        }
    }

}

Usage:
int main(int argc, char *argv[])
{

    int N; // It seems you missed this.

    Recurse recurse;
    recurse.N1 = atoi(argv[1]);
    recurse.C1 = atoi(argv[2]);
    recurse.A1 = atoi(argv[3]);
    recurse.M1 = atoi(argv[4]);
    recurse.M2 = atoi(argv[5]);
    recurse.M3 = atoi(argv[6]);
    recurse.M4 = atoi(argv[7]);
    recurse.D1 = atoi(argv[8]);
    recurse.D2 = atoi(argv[9]);
    recurse.S1 = atoi(argv[10]);
    recurse.S2 = atoi(argv[11]);

    N = atoi(argv[12]);    // Again, you forgot this.

    recurse.Op = string(argv[13]);

    cout << recurse(N) << endl;
    return 0;
}

With the input data you're providing the output is 13.


text:
Q: How to configure g:form for nested resource i would like to use the nested resource url mapping stuff, that was introduced in Grails 2.3. I have trouble with getting <g:form /> working with something like this:
"/books"(resources:'book') {
  "/author"(resource:"author")
}

In this case i use a single resource for author. If i would like to have a form in /books/1/author/edit, which updates the author of the corresponding book.
My question is, how can <g:form /> can be configured, so that it will use the url /books/1/author as the action? According to the docs on g:form, there is no option to set a resource attribute like it can be done in g:link. Are there any other possibilities, or is the use of an form within this whole grails REST stuff not a first class citizen? Another thing that let me think it would work this way is the Grails 2.3 REST Improvements proposal wiki article, where these lines of code brought me into this direction:
// nested resources
<g:form resource="book/author" bookId="1" id="2" method="DELETE"> -> /books/1/authors/2
<g:form resource="book/author" bookId="1" id="2" method="PUT"> -> /books/1/authors/2
<g:link resource="book/author" action="edit" bookId="1" id="2"> -> /books/1/authors/edit/1

A: I'm running grails 2.4 and this works for me:
<g:form resource="author" params="[bookId: 1] action="save">
  <input type="hidden" id="2" />
</g:form>


text:
Q: How to properly handle inflated views inside a RecyclerView ViewHolder? I have multiple layout that will be inflated in my RecyclerView ViewHolder, the views are inflated depending on the dataset that is being pass to the ViewHolder, I know how to use getItemViewType() but in my case it is not applicable, so for example the dataset contain 1,2,3 it will inflate all the view to the ViewHolder container(LinearLayout).
My ViewHolder with a LinearLayout Container :
    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardBackgroundColor="@android:color/white"
        card_view:cardCornerRadius="2dp"
        card_view:cardElevation="2dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <include layout="@layout/layout_header" />
                    <LinearLayout
                        android:id="@+id/lnr_container"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
                    </LinearLayout>
                <include layout="@layout/layout_footer" />
            </LinearLayout>
</android.support.v7.widget.CardView>

ViewHolder1 :
Here I created a reference of the view with the variable and if the view is recycled I will just check if the variable is not null so for example the recyclerView I will just reset the data.
    private class ViewHolder1 extends RecyclerView.ViewHolder{
    @BindView(R.id.lnr_container)
    LinearLayout mLnrContainer;

    private RecyclerView mRecyclerView;
    private ImageView mImageView;
    private LinearLayout mLayout;

    public ViewHolder1(View itemView) {
        super(itemView);
        ButterKnife.bind(this,itemView);
    }

    public void setData(JSONObject data){
        mLnrContainer.removeAllViews();

        if (data.has("1")){
            if (mRecyclerView == null){
                mRecyclerView  = new RecyclerView(itemView.getContext());
                // other implementation
                mRecyclerView.setAdapter(new SomeAdapter(itemView.getContext(),data));
            }else {
                mRecyclerView.getAdapter().setData(data);
            }

            addView(mRecyclerView);
        }
        if (data.has("2")){
            mImageView  = new ImageView(itemView.getContext());
            addView(mImageView);
        }
        if (data.has("3")){
            mLayout = LayoutInflater.from(itemView.getContext()).inflate(R.layout.custom_layout,mLnrContainer,false);
            addView(mLayout);
        }
    }

    private void addView(View view){
        mLnrContainer.addView(view);
    }
}

ViewHolder2 :
private class ViewHolder2 extends RecyclerView.ViewHolder{
    @BindView(R.id.lnr_container)
    LinearLayout mLnrContainer;

    public ViewHolder2(View itemView) {
        super(itemView);
        ButterKnife.bind(this,itemView);
    }

    public void setData(JSONObject data){
        mLnrContainer.removeAllViews();

        if (data.has("1")){
            RecyclerView mRecyclerView  = new RecyclerView(itemView.getContext(),data);
            addView(mRecyclerView);
        }
        if (data.has("2")){
            ImageView mImageView  = new ImageView(itemView.getContext());
            addView(mImageView);
        }
        if (data.has("3")){
            LinearLayout  mLayout = LayoutInflater.from(itemView.getContext()).inflate(R.layout.custom_layout,mLnrContainer,false);
            addView(mLayout);
        }
    }

    private void addView(View view){
        mLnrContainer.addView(view);
    }
}

I am wondering and confused which of this ViewHolders should be implemented in my code, Is there a difference that might affect if the ViewHolder is recycled? Thank you for your answer and suggestion.

A: ViewHolder was made specifically to prevent excessive inflation, doing so in onBind will result in very poor performance.
I would use multiple itemViewTypes and inflate the layouts accordingly, just to have at least something to recycle. If those "1, 2, 3" are not mutually exclusive, that gives 8 different layout combinations.
Modify your RecyclerView.Adapter to reflect possible combinations:
private static final int VIEWTYPE_FLAG_HAS_RECYCLER = 1;
private static final int VIEWTYPE_FLAG_HAS_IMAGEVIEW = 1 << 1;
private static final int VIEWTYPE_FLAG_HAS_LINEAR = 1 << 2;
// shared view pool
private final RecyclerView.RecycledViewPool adapterSharedRecycledViewPool = new RecyclerView.RecycledViewPool();

@Override
public int getItemViewType(int position) {
    JSONObject data = dataList.get(position);
    int viewType = 0;
    // each type is a flag in viewType int, this returns values from 0 to 7
    if(data.has("1"))
        viewType = VIEWTYPE_FLAG_HAS_RECYCLER;
    if(data.has("2"))
        viewType |= VIEWTYPE_FLAG_HAS_IMAGEVIEW;
    if(data.has("3"))
        viewType |= VIEWTYPE_FLAG_HAS_LINEAR;
    return viewType;
}

Then check the flags when creating viewholder (for example pass viewType as constructor argument):
private class ViewHolder3 extends RecyclerView.ViewHolder{
    @BindView(R.id.lnr_container)
    LinearLayout mLnrContainer;

    private RecyclerView mRecyclerView;
    private ImageView mImageView;
    private LinearLayout mLayout;

    public ViewHolder3(View itemView, int viewType) {
        super(itemView);
        ButterKnife.bind(this,itemView);

        // only need to inflate extra views once
        if((viewType & VIEWTYPE_FLAG_HAS_RECYCLER) > 0){
            mRecyclerView  = new RecyclerView(itemView.getContext());
            // adapter must handle empty dataset
            mRecyclerView.setAdapter(new SomeAdapter(itemView.getContext(), null));
            // optimization to share views between other items
            mRecyclerView.setRecycledViewPool(adapterSharedRecycledViewPool);
            addView(mRecyclerView);
        }
        if((viewType & VIEWTYPE_FLAG_HAS_IMAGEVIEW) > 0){
            mImageView  = new ImageView(itemView.getContext());
            addView(mImageView);
        }
        if((viewType & VIEWTYPE_FLAG_HAS_LINEAR) > 0){
            mLayout = LayoutInflater.from(itemView.getContext()).inflate(R.layout.custom_layout,mLnrContainer,false);
            addView(mLayout);
        }
    }

    public void setData(JSONObject data){
        // views must be ready now
        if (data.has("1")){
            mRecyclerView.getAdapter().setData(data);
        }
        if (data.has("2")){
            // bind image view if needed
        }
        if (data.has("3")){
            // bind data to linear layout as needed
        }
    }

    private void addView(View view){
        mLnrContainer.addView(view);
    }
}

Notice the setRecycledViewPool: this allows nested recyclerViews to share the views created by other nested recyclerViews. This will increase the performance but ViewHolders created by someAdapter must be a static class (not an inner class of an adapter) since this allows ViewHolders to traverse between different RecyclerViews / Adapters.


text:
Q: Grid thumbnail expanding to fullscreen on click and transitioning to new page I'm trying to understand how this website achieves this effect where if I click on a thumbnail, the text disappears and the thumbnail expands to fit the screen and display a post.
I've been trying to google a variety of combinations on how to describe the effect - grid, thumbnail, zoom, magnify, click, expand, fullscreen, etc. - but I've had no luck in finding tutorials.
I also tried using the Chrome DevTools animations / elements inspector to try to understand exactly what elements are changing but I can't seem to figure it out. I can see that the post content goes into a div with class "feed" that originally has 0px but I don't see where the actual animation is happening, when the thumbnail actually expands in size.
Any help with how to implement this transition effect on a very general level or just how to use the developer tools to figure this out would be much appreciated.

A: There are many ways to achieve this effect.
But of you use Chrome Devtools and inspect the website you can see it uses 3D-transforms on many elements.
My guess is that the website uses some Javascript in combination with 3D-transforms. You can achieve very powerfull animations with just using CSS.
You can see a quick and dirty example demonstrating a simple transform down below.

$(document).ready(function(){
 $('.scale-div').click(function(){
  $(this).addClass('active');
 });

});
html,body{
margin:0;
padding:0;
}

div{
height:100px;
width:200px;
background-color:red;
transition:transform .5s ease;
}

.active{
  transform:scale(3);
  transition:transform .5s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scale-div">
</div>


text:
Q: What is the right statistical test, to test differences in group relations The setup is a group of 4 animals that can choose to spend time together - or not. This continues for several days and afterwards the data is the time of each animal spent with each other.
So 6 possible pairings: A1+A2, A1+A3, A1+A4, A2+A3, A2+A4, A3+A4.
And for each day a percentage of time spent together for each pairing. (6*40 values)
The Question is now if certain animal pairs spend more or less time together than other pairs.
What I gathered the first step should be to look for normal distribution which then decides which test for multiple, dependent groups is right. But I'm not shure if shapiro is the right choice and if this should be done pairing by pairing or the whole dataset as certain pairings can of course influence other pairings.


text:
Q: How to get only the specific value from series or list I have a data of over 600 employees' attendance over a period of month.
Table Sample
I have to get the count of absents of each employee and write it to another excel sheet.
So I initiated a for loop as shown below:
Code Sample
Im storing the value counts in a list and that includes the count of all variables in the row named status in picture 1.
How do I store only the count value of A(absent) in a list so I could use it accordingly.
Note: I know that status.loc['A'] gives the count of absent but when I try to use it in the loop it says key error.
Status.loc['A']
If I can't get the value of A from status.loc , is there a way to extract it from the list i stored it in named absent?
Please help me out!
Thanks in advance!!

A: You should just do error handeling:
try:
    absent.append(status.loc['A'])
except:
    <rest of code here>


text:
Q: Read CSV File in php Can we Read  and  remove single quote , double quote and semicolons  from csv file each columns so that you can upload csv file to mysql without any errors
 if (isset($_POST['submit'])) {
    if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
        echo "
" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "
";
        echo "
Displaying contents:
";
        readfile($_FILES['filename']['tmp_name']);
    }

    //Import uploaded file to Database
    $handle = fopen($_FILES['filename']['tmp_name'], "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $import="INSERT IGNORE INTO brokers (id,btype,bname,bphone,bmobphone,bfax,bemail,bwebsite,bcompany,bintrowho,bcurrentwho,bintrowhat,baddress,bjobtitle,bregion,bcity,bstate,bzip,bsweetspot1,bsweetspot2,bsweetspot3,bsweetspot4,bsweetspot5,bsweetspot6,bsweetspot7,bsweetspot8,bsweetspot9,bsweetspot10,bsweetspot11,bsweetspot12,bsweetspot13,bsweetspot14,bsweetspot15,baltphone,bdepartment,bitr,bvrr,bskype,bhangouts,bcomments) VALUES ('','$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]')";

        mysql_query($import) or die(mysql_error());
    }

    fclose($handle);

    print "Import done";
 $import=header("location:User_option.php");
    //view upload form
}

A: What you are getting here is SQL injection. It is a security venerability.
In basic terms, you should put mysql_real_escape_string around the data[N] refs you are using. Example:
"INSERT IGNORE INTO brokers (id,btype) VALUES ('','mysql_real_escape_string($data[0])')"

Please read this and this for more information.


text:
Q: Heroku: unable to connect to chromedriver 127.0.0.1:9515 when using Watir/Selenium This runs locally (without specifying driver_path), but not on Heroku.
Code:
Selenium::WebDriver::Chrome.driver_path = ENV['GOOGLE_CHROME_SHIM']
browser = Watir::Browser.new :chrome

I've confirmed below values in heroku rails console
ENV['GOOGLE_CHROME_BIN'] => "/app/.apt/opt/google/chrome/chrome"
ENV['GOOGLE_CHROME_SHIM'] => "/app/.apt/usr/bin/google-chrome-stable"

Installed Buildpacks:
https://github.com/heroku/heroku-buildpack-chromedriver
https://github.com/heroku/heroku-buildpack-google-chrome

Current Error:

Selenium::WebDriver::Error::WebDriverError: unable to connect to
  chromedriver 127.0.0.1:9515

Searching unable to connect to chromedriver 127.0.0.1:9515 on SO returns a bunch of results but none mention heroku.

Also:
I considered phantomjs. Someone else got it working here,
Using a headless browser with Heroku Rails Unicorn stack
But its deprecated. Below error when running it locally.

Selenium support for PhantomJS is deprecated. Use headless
  Chrome/Firefox or HTMLUnit instead.

Also Tried:
For transparency, I also tried the following.
Changing browser = Watir::Browser.new :chrome
To browser = Watir::Browser.new :chrome, headless: true
Though I didn't expect this to work.

Also Also Tried:
Removing:
https://github.com/heroku/heroku-buildpack-chromedriver
Adding:
https://github.com/heroku/heroku-buildpack-xvfb-google-chrome.
Adding headless gem.
And running the below script given in the watir gem page, http://watir.com/guides/headless/.
require 'watir'
require 'headless'
headless = Headless.new
headless.start
b = Watir::Browser.start 'www.google.com'
puts b.title
b.close
headless.destroy

Error:

Selenium::WebDriver::Error::UnknownError: unknown error: cannot find
  Chrome binary

I assume this failed because I didn't specify location of the chrome binary/shim. Couldn't find how to specify this when using headless in the docs.

Tried Per Suggestion:
heroku run /usr/bin/chromedriver --app app-name

Running /usr/bin/chromedriver on ⬢ app-name... up, run.2151
(Hobby) bash: /usr/bin/chromedriver: No such file or directory

Also see below logs that mention chrome when deploying to heroku:
remote: -----> chromedriver app detected
remote: -----> Looking up latest chromedriver version...
remote: -----> Downloading chromedriver v2.33...
remote: Archive:  /tmp/chromedriver.zip
remote:   inflating: /tmp/build_cd35072c5b766edaa2b565cbff57e5d6/.chromedriver/bin/chromedriver
remote: -----> Creating chromedriver export scripts...
remote: -----> Google Chrome app detected
...
remote: -----> Fetching https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
remote: -----> Installing google-chrome-stable_current_amd64.deb
...
remote: -----> Creating google-chrome shims

Some Progress:
If I ssh into the heroku server,
heroku run bash --app app-name
And search for files with the name chrome,
find /app/ -name "*chrome*"
/app/.profile.d/chromedriver.sh
/app/.profile.d/010_google-chrome.sh
/app/.apt/etc/cron.daily/google-chrome
/app/.apt/opt/google/chrome
/app/.apt/opt/google/chrome/chrome
/app/.apt/opt/google/chrome/chrome_100_percent.pak
/app/.apt/opt/google/chrome/chrome-sandbox
/app/.apt/opt/google/chrome/chrome_200_percent.pak
/app/.apt/opt/google/chrome/google-chrome
/app/.apt/opt/google/chrome/cron/google-chrome
/app/.apt/usr/bin/google-chrome-stable
/app/.apt/usr/bin/google-chrome
/app/.apt/usr/share/menu/google-chrome.menu
/app/.apt/usr/share/doc/google-chrome-stable
/app/.apt/usr/share/applications/google-chrome.desktop
/app/.apt/usr/share/gnome-control-center/default-apps/google-chrome.xml
/app/.apt/usr/share/man/man1/google-chrome.1
/app/.apt/usr/share/appdata/google-chrome.appdata.xml
/app/vendor/bundle/ruby/2.4.0/gems/selenium-webdriver-3.7.0/lib/selenium/webdriver/chrome
/app/vendor/bundle/ruby/2.4.0/gems/selenium-webdriver-3.7.0/lib/selenium/webdriver/chrome.rb
/app/vendor/bundle/ruby/2.4.0/gems/browser-2.4.0/test/unit/chrome_test.rb
/app/vendor/bundle/ruby/2.4.0/gems/browser-2.4.0/lib/browser/platform/chrome_os.rb
/app/vendor/bundle/ruby/2.4.0/gems/browser-2.4.0/lib/browser/chrome.rb
/app/.chromedriver
/app/.chromedriver/bin/chromedriver

I can see chromedriver binary at /app/.chromedriver/bin/chromedriver.
So I tried
heroku run /app/.chromedriver/bin/chromedriver --app app-name
Result:
Running /app/.chromedriver/bin/chromedriver on ⬢ app-name... up, run.2067 (Hobby)
Starting ChromeDriver 2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4) on port 9515
Only local connections are allowed.

But then running heroku run rake selenium_namespace:task_one --app app-name gives the same result.

Selenium::WebDriver::Error::WebDriverError: unable to connect to
  chromedriver 127.0.0.1:9515 ...
  /app/vendor/ruby-2.4.1/lib/ruby/2.4.0/net/http.rb:906:in `rescue in
  block in connect': Failed to open TCP connection to 127.0.0.1:9515
  (Connection refused - connect(2) for "127.0.0.1" port 9515)
  (Errno::ECONNREFUSED) ...

A: This is possible on Heroku.

Confusing chrome and chromedriver
Your configuration is mixing up chromedriver and Chrome. GOOGLE_CHROME_SHIM points to the Chrome executable google-chrome-stable, not to chromedriver. The line below results in Selenium executing the wrong binary, which results in the misleading error message.
Selenium::WebDriver::Chrome.driver_path = ENV['GOOGLE_CHROME_SHIM'] # WRONG!

As of writing this (Jan '18) the chromedriver build pack automatically adds /app/.chromedriver/bin to the $PATH variable. If you delete the above line Selenium should again be able to find chromedriver automatically.
And then?
You probably added the line above to fix Selenium not being able to find the Chrome binary.  The error message for that would have looked something like:

Selenium::WebDriver::Error::UnknownError: unknown error: cannot find
  Chrome binary

You can fix this by telling Selenium where the Chrome binary is located using Selenium::WebDriver::Chrome::Options. The following code should accomplish that.
options = Selenium::WebDriver::Chrome::Options.new
chrome_bin_path = ENV.fetch('GOOGLE_CHROME_SHIM', nil)
options.binary = chrome_bin_path if chrome_bin_path # only use custom path on heroku
options.add_argument('--headless') # this may be optional
driver = Selenium::WebDriver.for :chrome, options: options
driver.navigate.to "https://stackoverflow.com"

Buildpacks
This should all be possible with the standard chrome and chromedriver build packs:
https://github.com/heroku/heroku-buildpack-google-chrome.git
https://github.com/heroku/heroku-buildpack-chromedriver.git
You may need heroku-buildpack-xvfb-google-chrome instead of vanilla chrome if you're automating clicks in the browser, but that should not be required just to get headless chrome running.

A: I am quoting Ilya Vassilevsky from this post

ChromeDriver is just a driver for Chrome. It needs the actual Chrome browser installed on the same machine to actually work.
Heroku doesn't have Chrome installed on its dynos by default. You need to use a buildpack that installs Chrome. For example:
https://github.com/dwayhs/heroku-buildpack-chrome
You can see how it fetches Chrome:
https://github.com/dwayhs/heroku-buildpack-chrome/blob/master/bin/compile#L36-38

Then I read their discussion in the comments:
Petr Gazarov says

I tried this buildpack and it didn't work. I'm suspecting installing google chrome (or any browser) on heroku might be more involved.

Ilya Vassilevsky replies

Yes, Heroku is a very opinionated and closed platform. It should be much easier to set up Chrome with ChromeDriver on your own VM on AWS, Linode, or DigitalOcean.

Petr Gazarov replies

Thanks for your answer Ilya. I ended up re-writing with Watir with phantomjs because I couldn't get Heroku to install Chrome.

You can read more info in that question.
If something comes to my mind, I will post it.

A: This worked for me. I replaced the line below:
Selenium::WebDriver::Chrome.driver_path = ENV['GOOGLE_CHROME_SHIM']

for this:
Selenium::WebDriver::Chrome::Service.driver_path = "/app/.chromedriver/bin/chromedriver"

A: I've been struggling with this one for more than a few hours ....
It has been very frustrating to try to debug on Heroku CI. This ticket has helped me a lot to find a solution.
I had this piece of code in the spec_helper.rb that was causing trouble (for if it helps someone):
config.before(:each, type: :system, js: true) do
  driven_by :selenium_chrome_headless
end

It was bypassing all the capybara setup...