text:
Q: Parsing in jquery I am trying to parse what I am getting  JQuery to show data ! I am consuming data from an API , but I am getting an error .
Can I do a Loop on JQuery this way ?
$.each(data.results, function (i, item) { // on this line

    var Name = item.name;
    var Date = item.auditInfo.dateCreated;
    var Creator = item.creator.display;
    $htmlstring.append($('
').append('
Test
'));
    $htmlstring.append("
 Info : "
    Name + Date + Creator "
");

}); $('#afficher').html($htmlstring);

I am sharing code on JSFiddle (Check drug_omrsRestCall function ) :
http://jsfiddle.net/zTXyq/23/

A: As @adeneo commented on the question, the concept is right but you should be careful about what element you are appending HTML content to.
With this snippet of your code:
$htmlstring.append("
 Info : "
    Name + Date + Creator "
");

(BTW, it is missing two plus signs for a correct concatenation, I hope that's not the error you are getting).
you append a DIV to the UL and you actually want to append it to the LI, for example:
$('
').append("
Test
")
    .append("
 Info : " + Name + Date + Creator + "
")
    .appendTo($htmlstring);

Check this fiddle for a working solution of your issue:
http://jsfiddle.net/d3dcj/2/


text:
Q: How to rewriterule URL using .htaccess how to rewriterule for link like this
http://stanime.pe.hu/content.php?idf=15&link=Katsugeki--Touken+Ranbu

to http://stanime.pe.hu/15/Katsugeki--Touken+Ranbu
im encode and decode my url using Urlencode and urldecode
in database Collation im using latin1_swedish_ci
so, space will replace with + and / replace with %2f and more...
this my .htacces code
    RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+content\.php\?link=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ content.php?link=$1 [B,L,QSA]

A: First you need to add this directive in your vhost or http.conf file:
AllowEncodedSlashes On

This will allow encoded slash character i.e. %2F in URLs.
You can use these rules in your site root .htaccess:
RewriteEngine On

# external redirect from actual URL to pretty one
RewriteCond %{THE_REQUEST} \s/+content\.php\?idf=([^\s&]+)&link=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L,NE]

# internal forward from pretty URL to actual one
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/(.+)$ content.php?idf=$1&link=$2 [B,L,QSA]

A: you have to add character rules like below. Because your data is in character form not only number in url that you have defined here.
  RewriteRule    ^content/([A-Za-z0-9-_]+)/?$    content.php?link=$1 [NC,L]

redpajama_set_name: RedPajamaStackExchange


text:
Q: deleting 1st row of many files at once in vim I'm trying to edit all the files at once using vim buffers. Is it possible to delete 1st row of each file opened in buffers?

A: Check out the :bufdo command
Specifically, what you want is :bufdo! 1d

A: you can do the task with :bufdo 1d | update

A: :tabdo 1d works for me in gVim, but that's across multiple tabs. I'm not sure how buffers differ—you might need to use :bufdo instead.
Check here for more info:
http://vim.wikia.com/wiki/Run_a_command_in_multiple_buffers


text:
Q: How to query with Spring JPA on jsonb columns? I'm using spring JPA with PostgreSQL database. I have an Entity as follow:
@Entity
@TypeDef(name="json_binary", typeClass = com.vladmihalcea.hibernate.type.json.JsonBinaryType.class)
public class LiveTokens {

   @Id
   @GeneratedValue()
   private Long id;

   private String username;

   @Type(type="json_binary")
   @Column(columnDefinition = "jsonb")
   private Token token
}

and Token:
public class Token {
   private Long expireTime;
   private String accessToken;
}

For saving object to column with Hibernate, I use Hibernate Types project.
Now I want to get All LiveTokens that expired. I can't do it with Spring JPA. How do I query to posgresql jsonb column with Spring data JPA?

A: SQL JSON functions
If you want to call a SQL function that processes the JSON column, then you just need to make sure you register the function with Hibernate prior to using it.
JSON operators
For JSON operators, like the PostgreSQL ones (e.g., ->>), the only option you have is to use a native SQL query. JPQL or HQL don't support database-specific JSON operators.

A: Using EclipseLink and spring data jpa, if your data in db is something like: {"expireTime":102020230201, "accessToken":"SOMETHING" }, my first question is why to use long numbers for your dates instead of timestamps (ex '2019-09-14 12:05:00'). If you use timestamps there are also options to manage timezones (either from postgresql or from you source code).
Regarding your issue you may use the FUNC JPQL keyword of EclipseLink (Hibernate may have something similar) in order to run a database specific function. In the example below I use FUNC('jsonb_extract_path_text', lt.token, 'expireTime') to get the values of the json for token.expireTime.
PostgreSql method jsonb_extract_path_text returns text, thus you cannot do a less that condition, so I cast the output of the function using JPQL CAST keyword with (CAST -data- TO -type-).
@Repository
public interface MyRepository extends JpaRepository<LiveTokens, Integer> {

    @Query(value = "SELECT lt FROM LiveTokens lt WHERE CAST(FUNC('jsonb_extract_path_text', lt.token, 'expireTime') AS LongType) < :expirirationThreshold")
    List<LiveTokens> findByExpireTime(@Param("expirirationThreshold") Long expirirationThreshold);
}

Again, this is not tested.

A: This is how a native query using postgres JSON query operators would look like, incoorporating your example:
@Query(value="SELECT t.* FROM LiveTokens t WHERE CAST(t.token ->> 'expireTime' AS LONG) < now()", native=true)

Assuming your real tablename is LiveTokens, native queries do no longer use the JPA translations, and the tablename has to match the one in the DB. (You may also need to specify it's schema.)

A: Try it:
Service class:
Long currentTime = new Date().getTime();

Repository:
@Query("SELECT lt FROM LiveTokens lt WHERE lt.token.expireTime <= :currentTime")

List<LiveTokens> findExpiredLiveTokens(@Param("currentTime") long currentTime)


text:
Q: Facebook scores API not returning score data for 'me' We are having trouble querying scores from the Scores Graph API.
Using the Graph Explorer with an app access token, We query me/scores but the data the gets returned looks like this:
{
  "data": [
    {
      "user": {
        "name": "USER_NAME",
        "id": "APP_USER_ID"
      }
    }
  ]
}

As you can see, no score is returned.
Giving the app the publish_actions permission and submitting a new score returns successful, but still, querying scores returns the same data as before.
We have not changed anything on our end, so I'm wondering if something has changed on Facebook's side.
Any help would be appreciated.

A: Have a look at my answer to a similar question here:

*

*FBSDKGraphRequest Response Issue - Not getting scores


text:
Q: Delete public key from Private for Private key storage with GPG I'm trying to make a paper based backup of a 4092 bit secret/private PGP key using a QR code generator, but the key is just too big. I'm going to go low tech here and split it into two pieces, but perhaps I don't need to. I know that when exporting the secret key, it also exports the public key embedded within it.
Is there any way to remove the public portion of the key from that file, or prior to exporting, so that the resulting file is only the private key?
I'm not certain the resulting file will be small enough still, but it is worth a shot.
D:\Users\tharding>gpg --edit-key "04EAC14C"
gpg (GnuPG) 2.0.26; Copyright (C) 2013 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Secret key is available.

pub  4096R/04EAC14C  created: 2015-02-11  expires: never       usage: SCE
                     trust: unknown       validity: unknown
[ unknown] (1). Timothy Harding <hardingt@gmail.com>

gpg> key 1
No subkey with index 1

gpg> delkey
You must select at least one key.

gpg> delkey 0
You must select at least one key.

Update:
From what I can tell, (looking at the ASCII Armored output for both the public key and the private key) it looks like they are structured this way:

Update 2:
Looked at the files again, and this is what I've got, I haven't pulled out a hex editor yet to verify the non armored files, but I've found surprisingly little help online about how these key files are internally structured:
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version:

4    header chars ??
1517 pub key chars
4    footer chars ??
-----END PGP PUBLIC KEY BLOCK-----

and
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version:

4    different header chars from pub key ??
700  pub key chars
1772 private key chars (possibly some header/footer to do with the symmetric cipher)
817  pub key chars (same total 1517, exact same ASCII sequence if put together)
4    different footer chars from pub key ??
-----END PGP PRIVATE KEY BLOCK-----

Update 3:
Took a look at the binary pub/private keys and found that:

*

*public key is 1138 bytes

*

*4 unique bytes

*1134 bytes found in private key as well

*private key is 2467 bytes

*

*4 unique bytes

*524 of which are found verbatim in the public key

*1329 of which are unique to the private key

*38 bytes which are found verbatim in the public key (key name & Email address)

*572 bytes which are found verbatim in the public key

A: There is a program called Paperkey[1], written by David Shaw[2], that extracts only the private key information from an exported OpenPGP private key.
Excerpt from the package description:

extract just the secret information out of OpenPGP secret keys

The Paperkey page has a version already built for Windows 32bit, and provides the source to compile on Linux, Unix, *BSD and OSX.
Paperkey is also available via the package manager on some Linux/BSD distributions.
Example package manager installs -
apt (debian) -
apt-get install paperkey

yum (redhat)
yum install paperkey

pkg (bsd)
pkg install paperkey

ports (bsd)
cd /usr/ports/security/paperkey
make install clean


text:
Q: angularjs select radio with conditon Each radio button has one value. I want to add the values every time someone select a radio button. To select the right radio button 1 will be added and for wrong 0.5 will be subtracted. The final result will show in ov div.
var app = angular.module('plunker', []);

app.controller('aCtrl', function($scope) {
var v= 0 ;
$scope.cal = function(){
  $scope.rv.click();
  v +=$scope.rv;
  $scope.ov = JSON.stringify(v);
};

});

Here is my plunker link
http://plnkr.co/edit/onjtGkkG0FiK4dOCmJfX?p=preview

A: This is simple directive for your purpose:
var app = angular.module('plunker', []);

app.controller('aCtrl', function($scope) {
    $scope.v = 0;
});

app.directive('addOnCheck', function () {
  return {
    restrict: 'A',
    scope: {
      addOnCheck: '='
    },
    link: function (scope, el, attrs) {
      el.on('click', function () {
        scope.$apply(function () {
          scope.addOnCheck += attrs.value;
        });
      });
    }
  };
});

Here is plunker http://plnkr.co/edit/6vz5VXnnub5KgFxtXUAg?p=preview


text:
Q: how to use mapproxy to serve WMS from reprojected google maps tiles how to use mapproxy to serve WMS from reprojected google maps tiles, i have searched for docs, but there's no docs which describe how to add google maps as source.

A: Technically it is very simple to use Google tiles as source for WMS. You can do this with the following MapProxy config:
services:
  demo:
  tms:
  wms:
    md:
      title: MapProxy WMS Server

sources:
  gm:
    type: tile
    url: http://mt0.google.com/vt/lyrs=m@0&hl=en&x=%(x)s&y=%(y)s&z=%(z)s
    grid: gm_grid

grids:
  gm_grid:
    base: GLOBAL_MERCATOR
    origin: ul

caches:
  gm_cache:
    grids: [gm_grid]
    sources: [gm]
    cache:
      type: file
      directory_layout: tms

layers:
  - name: gm_layer
    title: Test of using GM tiles
    sources: [gm_cache]

But as mentioned above - you are allowed to access the tiles only through Google API.

A: MapProxy supports  WMS sources (1.0.0–1.3.0)& TMS/WMTS sources.
Google does not have an WMS service. It has its own tiles, and according to Google's Terms & Conditions, you are allowed to access the tiles only through their API.
This is why you cannot use MapProxy with Google Maps as a source.


text:
Q: Syntax error with asp.net link tag I am trying to load stylesheet dynamically from folder, but currently, it isn't working:
<head id="Head1" runat="server">
     <link  type="text/css" rel="styleSheet"  href="http://www.domain.com/users/'<%= UserNameVar%>'/styleSheet.css" />
</head>

UserNameVar contains string data.
Edit: This is the output when i upload it to server. but it is not loading

<link type="text/css" rel="styleSheet" href="http://www.domain.com/users/'<%= UserNameVar%>'/styleSheet.css" /></head>

A: Put all href value in <%= and %>
Try this:
<head id="Head1" runat="server">
     <link  type="text/css" rel="styleSheet"  href=<%= "http://www.domain.com/users/" + UserNameVar + "/styleSheet.css />" %>
</head>


text:
Q: JQgrid set row height I am using JqGrid with javascript.
I would set the height of each table row  but I have not understand how to do.
This is my code:
 function jobList(){
var json=doShowAll();
alert("jobList() ==> php/get_job_status.php?value="+json);
jQuery("#jobList").jqGrid({
    url:'php/get_job_status.php?value='+json,
 datatype: "xml",
    colNames:['id','title', 'start', 'stop','completed'],
    colModel:[
     {name:'id',index:'id', width:15,hidden:true, align:"center"},
     {name:'title',index:'title', width:150, align:"center"},
     {name:'start',index:'start', width:350, align:"center", sorttype:"date"},
     {name:'fine',index:'fine', width:350, align:"center", sorttype:"date"},
     {name:'completed',index:'completed', width:120, align:"center",formatter:highlight},//il solitoformatter:infractionInFormatter},
    ],
    //rowNum:8,
    //rowList:[8,10,20,30],
    pager: '#pagerJobList',
    sortname: 'id',
    viewrecords: true,
    sortorder: "desc",
 multiselect: false,
 subGrid: false,
 autowidth: true,
 height: 250,
 rowheight: 300,

 caption: "Job Progress",
  afterInsertRow: function(rowid, aData){
     jQuery("#jobList").jqGrid('setCell', rowid, 'completed', '', {
      background: 'red',
     color: 'white'
     });
  },
  onSelectRow: function(id){
        //alert(id);
        var title="";
        if (id) {
         var ret = jQuery("#jobList").jqGrid('getRowData',id);
         title=ret.id;
         //alert(title);
        }
        else {
         alert("Please select row");
        }
        var json2=doShowAll();
        subGrid(json2,title);
     }

 }
);

}
Modifying RowHeight value rows height don't change.
This is my table result

Thanks a lot.

A: This also works:
.ui-jqgrid .ui-jqgrid-htable th {
    height: 2em !important;
}
.ui-jqgrid tr.jqgrow td{
    height: 1em !important;
}

A: You can set height of individual rows of jqGrid or any other CSS property with the help of setRowData method (see this wiki article). You can do this for example in loadComplete:
$("#list").jqGrid({
    // ...
    loadComplete: function() {
        var grid = $("#list"),
            ids = grid.getDataIDs();

        for (var i = 0; i < ids.length; i++) {
            grid.setRowData(ids[i], false, { height : 20 + (i * 2) });
        }

        // grid.setGridHeight('auto');
    }
});

You can see a working example here. Here you can see that after changing the height of the rows it could be a good idea to change the height of the grid. After un-commenting the line with the setGridHeight, the results will looks like this.
UPDATE Based on the question from comment: To change the height of the header of the table with id="list" you can do the following:
$("table.ui-jqgrid-htable", $("#gview_list")).css ("height", 30);

The $("#gview_list") is a div over the grid body and the grid headers.
You can see results here.

A: In the ui.jqgrid.css file change the line in the /* body */ section to this:
.ui-jqgrid tr.jqgrow td {
    font-weight: normal;
    overflow: hidden;
    white-space: nowrap;
    height: 22px;
    padding: 0 2px 0 2px;
    border-bottom-width: 1px;
    border-bottom-color: inherit;
    border-bottom-style: solid;
}

white-space: is changed from pre to nowrap.

A: I solved this issue setting this rule in a css stylesheet:
.grid .ui-jqgrid-htable th,
.grid .ui-jqgrid-btable .jqgrow td {
    height: 3em !important;
}


text: Q: Is there any way to randomly remove element in an array created by lr_paramrr_random in loadrunner I want to randomly remove an element in an array created by the lr_paramrr_random function in loadrunner or do I have to use any string functions


text:
Q: Android Wear - java.lang.ClassNotFoundException I'm developing an Android Wear extension to an existing app. While working on Android Studio I'm getting the following every time I'm running the wear module AFTER I run the main app, and the wear app crashes on start:
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.mobile.activities.MainActivity" on path: DexPathList[[zip file "/data/app/com.example.mobile-2/base.apk"],nativeLibraryDirectories=[/data/app/com.example.mobile-2/lib/x86, /vendor/lib, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
            at android.app.ActivityThread.-wrap11(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5422)

The only solution I found for this is File > Invalidate Caches/Restart and then Build > Clean project.
After that I can run the wear module (until the next main run).
This makes my work very slow. Can someone help me here?

A: ClassNotFoundException was thrown when an application tries to load in a class through its string name using:

*

*The forName method in class Class.

*The findSystemClass method in class ClassLoader .

*The [loadClass](https://developer.android.com/reference/java/lang/ClassLoader.html#loadClass(java.lang.String, boolean)) method in class ClassLoader.
but no definition for the class with the specified name could be found.

As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The "optional exception that was raised while loading the class" that may be provided at construction time and accessed via the getException() method is now known as the cause, and may be accessed via the getCause() method, as well as the aforementioned "legacy method."
Found this SO related ticket, issue was resolved by doing steps below:

*

*Right click on your project and select Properties.

*Select Java Build Path from the menu on the left.

*Select the Order and Export tab.

*From the list make sure the libraries or external jars you added to your project are checked.

*Finally, clean your project & run.

You may also check this SO ticket: Android Activity ClassNotFoundException - tried everything


text:
Q: Placement of backbutton in navigation controller I'm using a navigation controller, and I want to replace the default back button and text, with a custom. Here is what I do:
    navigationItem.backBarButtonItem = UIBarButtonItem(title: "back", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
    navigationController?.navigationBar.backIndicatorImage = UIImage(named: "BackCarretIcon")
    navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "BackCarretIcon")

This is set in prepare for segue, before navigating away from the root view controller.
When the next view controller appears, the image appears to be in the right place, but when the push animation has completed, the back button image moves a bit down. See image of the destination view controller:

So the "BackCarretIcon" and "back" label are not vertical center alligned. How come?? and how can this be fixed.
There is no code in the view controller life cycle methods of the destination view controller, that uses the navigationcontroller or navigation items.
EDIT
I've put a breakpoint in viewWillLayoutSubviews in the destination view controller. It breaks two times, before the destination view controller appears on screen. When i continue execution after the second break, the destination view controller is pushed onto the screen(with the back carret in the right place). When it is fully pushed onto the screen, the back carret jumps a couple of points down, to the wrong position, and viewWillLayoutSubviews breaks again.
I'm not able to break, at the place where the back carret is positioned right...

A: Try this:
navigationController?.navigationItem.backBarButtonItem?.setTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -2), forBarMetrics: UIBarMetrics.Default)

A: Back button is property of the second last VC in the stack of VCs of navigation view controller.
self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"BackBack" style:UIBarButtonItemStylePlain target:nil action:nil];

Put this in a child VC in a navigation VC & push another VC on top to it. Back button will display "BackBack". So proper way to do this would be to do this for every child VC. Here user will know that last VC was about "BackBack". But try not to do this. Inform user about where back button will take them. Hacking the way back button works might not be best way & might cause some problem.
Hope this helps.


text:
Q: Is there any way to match and remove logical operator from Regular Expression I don't want to include Logical operators(and, or, not) while using Match function in Regex.
I tried below but it doesn't worked as expected. can someone please help me.
Sort of strings I am using for parsing :
Example :
1. Input -->'(Value1==6) and (Value2==0)?1:0'
Output --> ["Value1", "Value2"]

2. Input : 'Value_1'
Output -->["Value_1"]

3. Input : '(Value_1 * Value_2)'
Output : ["Value1", "Value2"]

4. Input : 'Value_Machine_Outcome==4?1:0'
Output : Value_Machine_Outcome

Nested conditions : No
Are the conditions always in brackets : No
I am evaluating them in very next step using Math.evaluate
Please have example below :

const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /([a-zA-Z]+[a-zA-Z0-9_]+)(?<!and|or|not)/g;
const found = paragraph.match(regex);

console.log(found);

// expected output: Array ["Value1", "Value2"]

A: Your updated question completely changes the nature of the inputs. If the inputs are that varied, you'll need to match just about any "word" that doesn't start with a digit that isn't and, or, or not (but that fits with your original attempt, so I guess that makes sense):
const regex = /(?!and|or|not)\b[A-Z]\w*/gi;

Live Example:

const tests = [
    {
        str: "(Value1==6) and or not (Value2==0)?1:0",
        expect: ["Value1", "Value2"]
    },
    {
        str: "Value_1",
        expect: ["Value_1"]
    },
    {
        str: "(Value_1 * Value_2)",
        expect: ["Value_1", "Value_2"]
    },
    {
        str: "Value_Machine_Outcome==4?1:0",
        expect: ["Value_Machine_Outcome"] // Note I put this in an array
    }
];

const regex = /(?!and|or|not)\b[A-Z]\w*/gi;
for (const {str, expect} of tests) {
    const result = str.match(regex);
    const good = result.length === expect.length && result.every((v, i) => v === expect[i]);
    console.log(JSON.stringify(result), good ? "Ok" : "<== ERROR");
}

That works by disallowing and, or, and not, and requiring a match at a word boundary (\b).
Note that in the tests, I changed the expected result of the Value_Machine_Outcome==4?1:0 string to be an array, not just a string, like all the others.

Original Answer before the question completely changed the inputs:
If you want to use String.prototype.match, you can use a positive look-behind (since ES2018) for a ( and match everything prior to a = following it:
const regex = /(?<=\()[^=]+/g;

Live Example:

const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /(?<=\()[^=]+/g;
const found = paragraph.match(regex);

console.log(found);

// expected output: Array ["Value1", "Value2"]

If you're okay with a loop, you can avoid the lookbehind (since they were only added in ES2018) by using a capture group:
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
    found.push(match[1]);
}

Live Example:

const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
    found.push(match[1]);
}

console.log(found);

// expected output: Array ["Value1", "Value2"]

In a comment you asked:

My expression can also contain underscore. like it could be value_1, value_2. Will it work there ?

and I said it would because both of the above match anything but a =.
Later you said:

when my structure contain 'Value_1' it ignores

Again, both of the above work just fine with Value_1 and Value_2:
First:

const paragraph = '(Value_1==6) and (Value_2==0)?1:0';
const regex = /(?<=\()[^=]+/g;
const found = paragraph.match(regex);

console.log(found);

// expected output: Array ["Value1", "Value2"]

Second:

const paragraph = '(Value_1==6) and (Value_2==0)?1:0';
const regex = /\(([^=]+)/g;
const found = [];
let match;
while (!!(match = regex.exec(paragraph))) {
    found.push(match[1]);
}

console.log(found);

// expected output: Array ["Value1", "Value2"]

A: Try this regex: ([a-zA-Z]+[a-zA-Z0-9_]+)(?<![and|or|not]). I just updated regex in your code, please test and let me know if you have any concern.

const paragraph = '(Value1==6) and (Value2==0)?1:0';
const regex = /([a-zA-Z]+[a-zA-Z0-9_]+)(?<![and|or|not])/g;
const found = paragraph.match(regex);

console.log(found);


text:
Q: How can I turn on and off the bluetooth on iphone sdk programatically? how can I tell programatically if the bluetooth is turned on or of on the device?
And in ethier case turn it off or on programatically?
thanks

A: Are you talking about the popup that appears when you run the GKTank application while bluetooth is turned off? I suspect this is a function of the PeerPicker class - I haven't seen a way to query the bluetooth status directly.
However if you attempt to make a bluetooth call when bluetooth is off you'll receive a GKSessionCannotEnableError error code (Bluetooth is not currently available).

A: There's currently no way to interface with Bluetooth unless you join the Made for iPod / Works With iPhone program for some hardware you're developing.


text:
Q: Compute spheres 2D speeds in perspective projected animations I created two animations that consist of spheres moving in a perspective projected 3D space, which means that the size and speed of the spheres vary with the distance: they increase when they are closer to the viewer (the camera) and decrease when they move farther away from the viewer. Both animations are played on a computer 2D screen.
In the Random Movement Animation, the spheres are moving randomly in different directions (GIF 1). In my code, I computed their spherical coordinates (sphere.position.xyz) with the two angles theta and Phi (see below the formulas used for the position and their derivates).
In the Optic Flow Animation, it is the camera that moves along the z-axis (camera_z -= .1) and the spheres don't move (GIF 2).
In the context of a neuroscientific experiment, I need to match the perception of speed between the two animations, thus I need to first compute the 2D speed in both animations (By 2D, I refer to the screen coordinates rather than the world coordinates). What are the respective speed formulas for each animation? Does the speed of each sphere in the optic flow calculation equal to the camera's speed?

How I generated Spheres coordinates in the Random animation:
for sphere in spheres:

        sphere.position.xy = np.random.uniform(-25, 25, size=2)
        z = np.random.uniform(near_z, far_z)

        sphere.position.z = z
        sphere.position.x *= z/-50
        sphere.position.y *= z/-50

        sphere.theta_deg = np.random.rand(1) * 360
        sphere.phi_deg = np.random.rand(1) * 360

        theta_rad = sphere.theta_deg * np.pi / 180
        phi_rad = sphere.phi_deg* np.pi / 180

        sphere.dx = speed * np.sin(-phi_rad - theta_rad) / frameRate
        sphere.dy = -speed * np.cos(phi_rad + theta_rad) / frameRate
        sphere.dz = -speed * np.cos(theta_rad) / frameRate


text:
Q: Plane surface data plot I want to generate a plot like this:

I generated this list
list = {{-1., -1, 0}, {-0.894737, -1, 0}, {-0.789474, -1, 0},
{-0.684211, -1, 0}, {-0.578947, -1, 0}, {-0.473684, -1, 0},
{-0.368421, -1, 0}, {-0.263158, -1, 0}, {-0.157895, -1, 0},
{-0.052631, -1, 0}, {0.0526316, -1, 0}, {0.1578950, -1, 0},
{0.2631580, -1, 0}, {0.3684210, -1, 0}, {0.4736840, -1, 0},
{0.5789470, -1, 0}, {0.6842110, -1, 0}, {0.7894740, -1, 0},
{0.8947370, -1, 0}, {1., -1, 0}}

and I thought that it'll fine for generate the first row, but instead, I get an empty plot using:
ListPlot3D[list]

The only way I'm getting something is taking off the third entry from every triad in the list:

But evidently that's not what i'm looking for, thanks in advance.
Edit:
Yeah, my question is not clear, sorry about that. I've generated that list with a Table. What I'm looking for is to plot the square (with 400 equal partitions) centered in the origin of a cartesian coordinates system showing the value of the point. The problem with ArrayPlot is that the axes show the position of the data in the list, and not the value of the point.

A: Is this what you want?
list2 = list[[All, 1]];
Legended[ArrayPlot[list2~Partition~5,
  ColorFunction -> "WatermelonColors", FrameTicks -> True],
 BarLegend[{"WatermelonColors", {-1, 1}}]]

Edit:
list = Table[x y, {x, -1, 1, 0.1}, {y, -1, 1, 0.1}];

Legended[ArrayPlot[list, ColorFunction -> "WatermelonColors",
  Frame -> False, Mesh -> True, MeshStyle -> Black,
  DataReversed -> True], BarLegend[{"WatermelonColors", {-1, 1}}]]

Edit 2
list = Table[x y, {x, -1, 1, 2/19}, {y, -1, 1, 2/19}];

 ArrayPlot[list, ColorFunction -> "BlueGreenYellow", Frame -> False,
 Mesh -> True, MeshStyle -> Black, DataReversed -> True,
 PlotLegends -> Automatic]

Edit 3 You can remove the GridLines
list = Table[x y, {x, -1, 1, 2/19}, {y, -1, 1, 2/19}]; p2 =
 ArrayPlot[list, ColorFunction -> "BlueGreenYellow", Mesh -> True,
  MeshStyle -> Black, ImagePadding -> None, DataReversed -> True,
  Frame -> False, ImageSize -> 95];
p1 = ListPlot[{{0, 0}}, Frame -> True, Axes -> False,
   PlotRange -> {{-4, 4.4}, {-2, 2.4}}, ImageSize -> 400,
   AspectRatio -> Full,
   FrameTicks -> {{{-2, -1, 0, 1, 2}, None}, {{-4, -2, 0, 2, 4},
      None}}, GridLines -> {{-1, 0, 1}, {-1, 0, 1}}];
Legended[Overlay[{p1, p2}, Alignment -> Center],
 BarLegend[{"BlueGreenYellow", {-1, 1}}, LegendMarkerSize -> 200,
  Ticks -> {-1, -0.5, 0, 0.5, 1}]]

Edit 4  Here is better and perfect figure.(I assume you don't insist black mesh on figure). I got the idea from here
  data = Reverse@Table[x y, {x, -1, 1, 2/19}, {y, -1, 1, 2/19}];
renderImage[array_?MatrixQ, cf_, q_Integer: 2048,
  opts : OptionsPattern[Image]] :=
 Module[{tbl},
  tbl = List @@@ Array[cf, q, {0`, 1`}] // N //
    Developer`ToPackedArray;
  Image[tbl[[# + 1]] & /@ Round[(q - 1`) array], opts]]
img = renderImage[Rescale[data], ColorData["BlueGreenYellow"]];

Legended[Graphics[Inset[img, {-1, -1}, {0, 0}, {2, 2}], Axes -> True,
  Frame -> True,
  FrameTicks -> {{{-2, -1, 0, 1, 2}, None}, {{-4, -2, 0, 2, 4},
     None}}, PlotRange -> {{-4, 4}, {-2, 2}},
  GridLines -> {{-1, 0, 1}, {-1, 0, 1}}],
 BarLegend[{"BlueGreenYellow", {-1, 1}}, LegendMarkerSize -> 200,
  Ticks -> {-1, -0.5, 0, 0.5, 1}]]

Here how you can add Mesh on plot.
data = Table[{x, y}, {x, -1, 1, 2/19}, {y, -1, 1, 2/19}];
grid = Extract[#, {{1}, {-1}}] & /@ data;
grid2 = Extract[#, {{1}, {-1}}] & /@ Transpose@data;
Legended[Graphics[{Inset[img, {-1, -1}, {0, 0}, {2, 2}], Black,
   Opacity@1, Line[#] & /@ grid1, Line[#] & /@ grid2}, Frame -> True,
  FrameTicks -> {{{-2, -1, 0, 1, 2}, None}, {{-4, -2, 0, 2, 4},
     None}}, PlotRange -> {{-4, 4}, {-2, 2}}, AspectRatio -> 1/2],
 BarLegend[{"BlueGreenYellow", {-1, 1}}, LegendMarkerSize -> 200,
  Ticks -> {-1, -0.5, 0, 0.5, 1}]]

Can someone explain why this does not work well? img should fit [-1,1]x[-1,1]
data = Table[x y, {x, -1, 1, 2/19}, {y, -1, 1, 2/19}];
img = ArrayPlot[data, ColorFunction -> "BlueGreenYellow",
  Mesh -> True, MeshStyle -> Black, DataReversed -> True,
  ImageMargins -> 0, ImagePadding -> None,
  ImageSize -> 270]; Graphics[Inset[img, {-1, -1}, {0, 0}, {2, 2}],
 Axes -> True, Frame -> True, PlotRange -> {{-4, 4}, {-2, 2}},
 FrameTicks -> {{{-2, -1, 0, 1, 2}, None}, {{-4, -2, 0, 2, 4}, None}},
  GridLines -> {{-1, 0, 1}, {-1, 0, 1}}, AspectRatio -> Automatic]

A: Here's another simple way using ListDensityPlot which is in some sense the "right" way if this data is to be interpreted as continuous.
ListDensityPlot[list = Table[x y, {x, -1, 1, 0.1}, {y, -1, 1, 0.1}],
 ColorFunction -> "BlueGreenYellow", Mesh -> True, MeshStyle -> Black]

If you want the plot legend PlotLegends -> Automatic will do that for you.


text:
Q: Dynamically add DIVs to a modal So I have a text-based exploring game where the user can type the direction and go places and appropriate images come up and so on. I have, so far, created a world with boundaries.
What I want to do now is to add items that the user can interact with -- sword, map and so on. I know I can create a div using document.createElement("div") but then, how will I add it to the modal div ?  I mean, I can add it to the body by document.appendChild() but to a div ?
Also, How do I remove it ?

So the user types inventory and the modal shows up. When the user types pick, say on a sword, there should be a new div added to it the next time user types inventory
Suggestions to improve the game are welcome

A: You should have reference to your modal window stored somewhere in variable:
// modal_div contains reference to your modal
// or to particular element inside it
var modal_div = document.getElementById("my_modal");

// later you create new element and use appendChild to add it
var new_element = document.createElement("div");
modal_div.appendChild(new_element);

A: You can use jQuery's .after(), .append(), .before(), .remove() and such to add, remove, replace elements on your page.
You can navigate the DOM quite easily with jQuery, check out their tutorials: http://try.jquery.com/
Exercises about traversing the DOM: http://try.jquery.com/levels/2/challenges/1


text:
Q: Change image onclick I want to display a different image when clicking on my image. A demo is here. When clicking on the image the image should change to an arrow pointing up instead of pointing down. How do I do that?
Here is my code:

CONTENT

JS
var toggled = false;
$("img").click(function () {
    if (!toggled) {
        $(this).css("", "url(http://i.imgur.com/YCf5zYt.png)");
        toggled = true;
    } else {
        $(this).css("", "url(http://i.imgur.com/V4fKMWS.png)");
        toggled = false;
    }

    $("p").slideToggle();
})
$(document).ready(function () {
    $("#flip").click(function () {
        $("#panel").slideToggle("slow");
    });
});

A: Here's another solution with toggleClass() and attr() function :
See this fiddle
$(document).ready(function () {
    $("img").click(function () {
        $(this).toggleClass('active');
        if($(this).hasClass('active')){
          $(this).attr("src","http://i.imgur.com/V4fKMWS.png");
        } else {
          $(this).attr("src","http://i.imgur.com/YCf5zYt.png");
        }
        $("#panel").slideToggle();
    });
});

A: There are a couple of issues with the code:
First of all, you have to attach all of the event handlers from within the document ready callback. As it stands right now, it is possible that event handler is not attached because image tag may be not yet loaded when you try to attach the handler.
You also have to modify the src attribute of the image, not the css's url style:
$(this).attr("src", "http://i.imgur.com/YCf5zYt.png");

A: you can change the attribue src.
 if (!toggled) {
            $(this).attr("src", "http://i.imgur.com/YCf5zYt.png");
            toggled = true;
        } else {
            $(this).attr("src", "http://i.imgur.com/V4fKMWS.png");
            toggled = false;
        }

Refer link: https://jsfiddle.net/sj7o9x58/2/

A: there a mistakes in your code try this
  var toggled = false;
       $("img").click(function () {
    if (!toggled) {
        $(this).attr("src", "http://i.imgur.com/YCf5zYt.png");
        toggled = true;
    } else {
        $(this).attr("src", "http://i.imgur.com/V4fKMWS.png");
        toggled = false;
    }

    $("p").slideToggle();
});

A: Try to write all your code in $(document).ready(); And you have a big mistake.
You should use .slideToggle() for $("#panel"). And this is easier way to do it(without any variables):
    $(document).ready(function(){
    $("#flip").click(function(){
        if($("#panel").css("display") === "none"){
            $("#panel").slideToggle().css("display", "block");
            $("img").attr("src", "http://i.imgur.com/V4fKMWS.png");
    }   else if($("#panel").css("display") === "block"){
            $("#panel").slideToggle();
            $("img").attr("src", "http://i.imgur.com/YCf5zYt.png");
    }
    });
});

And demo is here

A: $(document).ready(function () {
    var toggled = true;

    $("img").on('click',function () {
        if (!toggled) {
            $(this).attr("src", "http://i.imgur.com/YCf5zYt.png");
            toggled = true;
        } else {
            $(this).attr("src", "http://i.imgur.com/V4fKMWS.png");
            toggled = false;
        }

        $("#panel").slideToggle("slow");
    });
});

The updated fiddle: https://jsfiddle.net/sj7o9x58/3/
I don't know if that's the image behavior you want, if it's the oposite just change te toggled initialization to false and the image by default on the src (html).


text:
Q: Questions about the verb "coin" when coining an idea I want to say "Rieger coined the notion of deep solidarity." However, I'm not sure about several aspects of this:

*

*Can you coin a notion, or only a phrase?

*Can I say he coined the phrase, even if other people used these words with their typical meanings, but he first defined them in a technical sense different than merely "strong solidarity"? (See Rieger's definition of the phrase and others discussing it)

*How might others suggest I word this statement?

A:
coin (v.) ...General sense of "make, fabricate, invent" (words) is from 1580s; phrase coin a phrase is attested from 1940 (to coin phrases is from 1898)... [from Etymonline]

As mentioned in both of the previous answers, the phrase to coin originally meant to "make", "fabricate", or "invent" -- and ought to be reasonably applicable as well to notions (ideas), since words and phrases themselves represent ideas.

A: "To coin" did originally mean to invent but it's come more often to mean almost the opposite: "to use a well-known phrase…"
However, "more often" doesn't mean exclusively or even instead. To "first define them in a technical sense…" seems to combine both uses; perhaps to introduce a third.
https://www.phrases.org.uk/meanings/coin-a-phrase.html

A: To "coin" means to take a piece of nondescript metal and stamp it with a pattern that makes it a recognizable piece of money. In other words, create something of clear, discernible value out of raw materials. Other meanings are metaphors on that concept.

A: 1. No. To coin means to create or stamp a phrase as your own e.g. 'shall I compare thee to a summer's day? Thou art more lovely and more temperate.'-William Shakespeare or Arnold Schwarzenegger's phrase-'I'll be back'.
2. As I just said-no. It would have to be their own phrase or their catchphrase.
3. Rieger used the notion 'deeply solitary'.

A:
Can you coin a notion, or only a phrase?

You coin a phrase, not a notion.

Can I say he coined the phrase,

I wouldn't call that particular phrase novel enough for anyone to say they coined it.
You could say he developed an idea or methodology or whatever which he called deep solidarity, or he characterized an idea or methodology or whatever, and he called it deep solidarity.  The point is, the idea is what's novel, the label he put on it isn't that novel.


text:
Q: Sharepoint 2010 - web.config modification We have a farm with 2 servers.
I have applied some changes to the web.config on both servers. (I have a specific web application i.e.  I have applied the changes in the web.config of my sharepoint web application and NOT the default Sharepoint site or the central admin site)
But it seems that Sharepoint does not take into consideration these changes!
For example I added an assembly reference .... but sharepoint was still throwing an assembly reference exception. i had to add the assembly reference to each and every control.
I have also increased the execution timeout but it still gives timeouts.
This happens in the production environment only.
In the test (where there is a single server) I update the web.config and all changes work.
Is it because I should not be updating the web config. I have noticed there is an SPWebConfigModification class. Do I have to use this ? won't it do the same changes as I would have done manually.
Update ....
I have now used the SPWebConfigModification and also did an iisreset ... but the changes were simply ignored!
Update 2...
Some more details on my web.config updates
I had added an assembly reference under assemmblies sectuion, somethign like this:

This did not work as Sharepoint was still throwing an exception that the assembly cannot be found.
This problem only happens in the production environment. In dev and test, I was also receiving the exception but when I added the assembly reference above, the error disappeared.
Another thing which did not work is the executionTimeout. I have added this to the production environment but sharepoint is still giving timeouts an a long request wich we have. Again, this entry solved the problem in the test and development environments.

A: As you have pointed out, you need to make these changes using the SPWebConfigModification class. It is possible to make the changes manually, however, this usually results in random issues caused by replication issues etc ....
The SPWebConfigModification class will ensure the change is stored in the SP database and amend the web.config files on your behalf.

A: I wrote this for this for Sharepoint 2007, I think you need to modify the impersonation (RunWithElevatedPrivileges) but the rest should work:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{

  SPSecurity.RunWithElevatedPrivileges(delegate() {

  try
  {

     Trace.WriteLine("Try to modify web.config");
     SPWebApplication myWebApp = ((SPWeb)properties.Feature.Parent).Site.WebApplication;

     WebConfigModifier mod = new WebConfigModifier(myWebApp, OwnerString);

     mod.AddModification(
        "SafeControl[@Assembly='Elsni.WorldsBestProgram, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e7639c2c71f2f003']",
        "configuration/SharePoint/SafeControls",
        "<SafeControl Assembly='Elsni.WorldsBestProgram, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e7639c2c71f2f003' Namespace='GFA.UniversalListSyncSolution' TypeName='*' Safe='True' />"
     );

     mod.AddModification(
        "add[@key='PropertiesSiteUrl']",
        "configuration/appSettings",
        "<add key=\"PropertiesSiteUrl\" value=\"http://iei-developersy/sites/gfaadmin/\" />"
     );

     mod.Update();
     Trace.WriteLine("Done.");
  }
  catch (Exception ex)
  {
     Trace.WriteLine("ERROR while activating feature: " + ex.Message);
  }
}
});
}


text:
Q: Are there any ways to map the result set at sql2o as generics? I'm writing database client using sql2o library. There are a lot of data access objects in my project, so I supposed to have lot of similar functions for getting access to the tables. For example, for class Persons.
public List<Persons> getPersonsData(){
   String sql = "SELECT * FROM " + PERSONS;
   try(org.sql2o.Connection con = sql2o.open()) {
      return con.createQuery(sql).executeAndFetch(Persons.class);
   }
}

Are there any ways to optimize it? I was thinking about using generics, but as I know there no ways to get instance of generic class. Is it really  impossible to create something like this?
public class Getter<T> {
    public List<T> getGenericClass(){
        String sql = "SELECT * FROM " + T.tableName;
        try(org.sql2o.Connection con = sql2o.open()) {
            return con.createQuery(sql).executeAndFetch(T.class);
        }
    }
}

A: We managed that creating a Store class
 public class Store<T> {
    private T value;

    public void set(T object){
        value = object;
    }

    public T get(){
        return value;
   }
}

and modify your GenericClass
public class GenericClass{
     public <T> void storeGenericClass(Store<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM MYTABLE WHERE ID = 1";
            try(org.sql2o.Connection con = sql2o.open()) {
                store.set(con.createQuery(sql).executeAndFetchFirst(clazz));
            }
        }

      public <T> void storeGenericClass(List<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM " +
              clazz.getName().toUpperCase();
            try(org.sql2o.Connection con = sql2o.open()) {
                store.addAll(con.createQuery(sql).executeAndFetch(clazz));
            }
        }

}

Use the same className as tableName is not a best practice. But if you map each class with a table, you can do in this way
  public class GenericClass{
    ...
     public <T> void storeGenericClass(List<T> store, Class<T> clazz){
            String sql = "SELECT field1, field2 FROM " +
           clazz.getName().toUpperCase();
            try(org.sql2o.Connection con = sql2o.open()) {
                store.addAll(con.createQuery(sql).executeAndFetch(clazz));
            }
        }
     ...
}

To instantiate:
public class MyClass {

    public String field1, field2;
}

...
    GenericClass generic= new GenericClass(sql2o);
    Store<MyClass> store = new Store<>();
    generic.storeGenericClass(store, MyClass.class);
    MyClass retrieved = store.get();
    System.out.println("My Class fields are: "+retrieved.field1 + "-"+retrieved.field2);
...

A: I improved on @tonino code and removed the need for the Store class.  Here is the code:

public <T> List<T> list(Class<T> clazz){
    String sql = "SELECT * FROM " +
        getTablename(clazz);
    try(Connection con = sql2o.open()) {
        return con.createQuery(sql).executeAndFetch(clazz);
    }
}

public <T> T findById(Integer id, Class<T> clazz) {
    String sql = "SELECT *" +
        " FROM " + getTablename(clazz) +
        " WHERE id=:id";
    try(Connection con = sql2o.open()) {
        return con.createQuery(sql)
            .addParameter("id", id)
            .executeAndFetchFirst(clazz);
    }
}

private String getTablename(Class clazz) {
    //This can be improved later with reflection
    return clazz.getSimpleName().toUpperCase();
}


text:
Q: How many different ways are there to get the same product from a sequence of integers? Let's say we have a list of integers from 0 to  (n-1), where n > 0:
0, 1, 2, 3, 4, ..., n - 2, n-1
How many different ways are there to multiply two numbers together to produce the same product, when the order matters?
For example, let's say n=7...
Here are some examples of products which are equal to each other:
order matters:
0 * 0 = 0 * 3
0 * 0 = 3 * 0
0 * 3 = 0 * 0
3 * 0 = 0 * 0

zeros:
0 * 6 = 0 * 2
4 * 0 = 0 * 0
0 * 0 = 0 * 0

same numbers on both sides:
1 * 6 = 6 * 1
1 * 6 = 1 * 6
6 * 1 = 6 * 1
6 * 1 = 1 * 6
6 * 6 = 6 * 6

more complex products:
2 * 3 = 6 * 1
4 * 3 = 6 * 2
2 * 2 = 4 * 1

I figured out the way to calculate how many permutations involve zeros: (e.g. 0 * 5 = 3 * 0)
(A) 4n^2 - 4n + 1

Calculating how many involve the same non-zero numbers on both sides is easy too: (e.g. 1 * 6 = 6 * 1)
(B) 2n^2 - 5n + 3

The only complicated part is figuring out different ways to generate the same product when it doesn't involve a zero and doesn't have the same numbers on both sides of the equation:
For example, if n=7, these are the permutations that would be more difficult to calculate:
4's:
1 * 4 = 2 * 2
4 * 1 = 2 * 2
2 * 2 = 1 * 4
2 * 2 = 4 * 1

6's:
2 * 3 = 1 * 6
3 * 2 = 1 * 6
2 * 3 = 6 * 1
3 * 2 = 6 * 1
1 * 6 = 2 * 3
1 * 6 = 3 * 2
6 * 1 = 2 * 3
6 * 1 = 3 * 2

12's:
3 * 4 = 6 * 2
(7 other permutations involving 3/4 and 6/2 omitted)

Notice that when the product involves 3 distinct numbers (as in the case of 1 * 4 = 2 * 2), there are 4 (2^2) different permutations for the same product; and there are 8 (2^3) permutations when all 4 numbers are unique.
I started working out the first few by hand by combining formulas A and B and then manually counting how many complex product permutations there are (C):
+----+-----+-----+----+-------+----------------------------------------+
| n  |  A  |  B  | C  | Total |          Note: products added          |
+----+-----+-----+----+-------+----------------------------------------+
|  2 |   9 |   1 |  0 |    10 | -                                      |
|  3 |  25 |   6 |  0 |    31 | -                                      |
|  4 |  49 |  15 |  0 |    64 | -                                      |
|  5 |  81 |  28 |  4 |   113 | 1*4=2*2                                |
|  6 | 121 |  45 |  4 |   170 | -                                      |
|  7 | 169 |  66 | 20 |   255 | 1*6=2*3, 2*6=3*4                       |
|  8 | 225 |  91 | 20 |   336 | -                                      |
|  9 | 289 | 120 | 48 |   457 | 1*8=2*4, 2*8=3*6, 2*8=4*4, 3*8=4*6     |
| 10 | 361 | 153 | 52 |   566 | 1*9=3*3                                |
| 11 | 441 | 190 | 84 |   715 | 1*10=2*5, 2*10=4*5, 3*10=5*6, 4*10=5*8 |
+----+-----+-----+----+-------+----------------------------------------+

What I would like is a formula for calculating C, I would then be able to calculate the Total easily by combining all 3 formulas. Is there any way to create a function or pattern to calculate C?


text:
Q: Рефакторинг кода парсера URL Создаю парсер URL на C#.
Задача: вывести top-N доменов, top-N путей. Пути к файлам(input output) берутся из консоли, N из консоли в виде опционального флага (как его правильно реализовать?)
Работает, но хотелось бы знать, как написать лучше с вашей точки зрения.
И флаг, да, его тоже!
class Program
    {
        static void Main(string[] args)
        {
            int N = 0;
            if (args[0] == "-n")
                if (!Int32.TryParse(args[1], out N))
                    throw new FormatException("N is not valid");
            string input = File.ReadAllText(args[2]);
            string pattern = @"(http://|https://)(?<domen>[\da-z\.-]+)/(?<path>[[\/\w \.-]*)";
            Regex regex = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Compiled);
            MatchCollection matchCollection = regex.Matches(input);

            SortedDictionary<string, int> Domens = new SortedDictionary<string, int>();
            SortedDictionary<string, int> Paths = new SortedDictionary<string, int>();
            for (int i = 0; i < matchCollection.Count; i++)
            {
                if (Domens.ContainsKey(matchCollection[i].Groups["domen"].ToString()))
                    (Domens[matchCollection[i].Groups["domen"].ToString()])++;
                else
                    Domens.Add(matchCollection[i].Groups["domen"].ToString(), 1);
                if (Paths.ContainsKey(matchCollection[i].Groups["path"].ToString()))
                    (Paths[matchCollection[i].Groups["path"].ToString()])++;
                else
                    Paths.Add(matchCollection[i].Groups["path"].ToString(), 1);
            }
            //Domen и Path - 2 класса, содержащих поля: строку и частоту встречаемости, реализованы в другом файле
            List<Domen> SortedDomens = new List<Domen>();
            foreach (KeyValuePair<string, int> keyValue in Domens)
            {
                SortedDomens.Add(new logparser.Domen(keyValue.Key, keyValue.Value));
            }
            SortedDomens.Sort();
            List<Path> SortedPaths = new List<Path>();
            foreach (KeyValuePair<string, int> keyValue in Paths)
            {
                SortedPaths.Add(new logparser.Path(keyValue.Key, keyValue.Value));
            }
            SortedPaths.Sort();
            //Вывод сначала общей информации, затем через статический шаблонный класс информацию о доменах и путях
            //Внутри переопределен метод .ToString() в классах Domen и Path
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(args[3], true))
            {
                file.WriteLine("total URLs: {0}, domains: {1}, paths: {2}",
                                matchCollection.Count + SortedDomens.Count + SortedPaths.Count);
                file.Close();
            }
            WriteToFile<Domen>.writetofile(SortedDomens, args[3], N);
            WriteToFile<Path>.writetofile(SortedPaths, args[3], N);
        }
    }

A: Если взять готовый пакет для разбора аргументов (PowerArgs), то примерно так:
using PowerArgs;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace ConsoleApp30
{
    public class Arguments
    {
        [ArgShortcut("n")]
        public int Top { get; set; }

        [ArgPosition(0)]
        [ArgRequired(PromptIfMissing = true)]
        public string InputFileName { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var arguments = Args.Parse<Arguments>(args);

            var urls = File.ReadAllLines(arguments.InputFileName)
                .Select(l => new Uri(l))
                .ToList();

            PrintTopN(urls, "Host", u => u.Host, arguments.Top);
            PrintTopN(urls, "Path", u => u.AbsolutePath, arguments.Top);
        }

        private static void PrintTopN(List<Uri> urls, string byText, Func<Uri, string> selector, int top)
        {
            Console.WriteLine("By " + byText);

            var groups = urls
                .GroupBy(selector)
                .OrderByDescending(g => g.Count())
                .Select(g => g.Key);

            if (top > 0)
            {
                groups = groups.Take(top);
            }

            // File.WriteAllLines, если нужно вывести в файл
            foreach (var g in groups)
            {
                Console.WriteLine(g);
            }
        }
    }
}


text:
Q: How to enable FEDERATED Engine in MySQL? I installed a new instance on MySQL 5.7.6 on a Windows 7 Laptop.
I need to enable FEDERATED Engine on it.
in the [mysqld] section I added FEDERATED
but when I try to start the server I get error.
Here is what mysql error logs show that --FEDERATED is an unknown option
A note from MySQL documentation

To include the FEDERATED storage engine if you build MySQL from
  source, invoke CMake with the -DWITH_FEDERATED_STORAGE_ENGINE option.

How do I CMake with -DWITH_FEDERATED_STORAGE_ENGIN on windows?
Here is the error from MySQL error files
2015-10-27T04:15:47.031678Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2015-10-27T04:15:47.031678Z 0 [Warning] 'NO_ZERO_DATE', 'NO_ZERO_IN_DATE' and 'ERROR_FOR_DIVISION_BY_ZERO' sql modes should be used with strict mode. They will be merged with strict mode in a future release.
2015-10-27T04:15:47.034678Z 0 [Note] C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe (mysqld 5.7.9-log) starting as process 5780 ...
2015-10-27T04:15:47.046679Z 0 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
2015-10-27T04:15:47.047679Z 0 [Note] InnoDB: Uses event mutexes
2015-10-27T04:15:47.048680Z 0 [Note] InnoDB: _mm_lfence() and _mm_sfence() are used for memory barrier
2015-10-27T04:15:47.049680Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.3
2015-10-27T04:15:47.049680Z 0 [Note] InnoDB: Adjusting innodb_buffer_pool_instances from 8 to 1 since innodb_buffer_pool_size is less than 1024 MiB
2015-10-27T04:15:47.051680Z 0 [Note] InnoDB: Number of pools: 1
2015-10-27T04:15:47.052680Z 0 [Note] InnoDB: Not using CPU crc32 instructions
2015-10-27T04:15:47.089684Z 0 [Note] InnoDB: Initializing buffer pool, total size = 8M, instances = 1, chunk size = 8M
2015-10-27T04:15:47.092684Z 0 [Note] InnoDB: Completed initialization of buffer pool
2015-10-27T04:15:47.220697Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
2015-10-27T04:15:47.373712Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
2015-10-27T04:15:47.374712Z 0 [Note] InnoDB: Setting file '.\ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
2015-10-27T04:15:47.533728Z 0 [Note] InnoDB: File '.\ibtmp1' size is now 12 MB.
2015-10-27T04:15:47.541729Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
2015-10-27T04:15:47.543729Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
2015-10-27T04:15:47.546729Z 0 [Note] InnoDB: Waiting for purge to start
2015-10-27T04:15:47.597734Z 0 [Note] InnoDB: 5.7.9 started; log sequence number 2472339
2015-10-27T04:15:47.600735Z 0 [Note] InnoDB: Loading buffer pool(s) from C:\ProgramData\MySQL\MySQL Server 5.7\Data\ib_buffer_pool
2015-10-27T04:15:47.600735Z 0 [Note] Plugin 'FEDERATED' is disabled.
2015-10-27T04:15:47.600735Z 0 [Note] InnoDB: not started
2015-10-27T04:15:47.616736Z 0 [ERROR] unknown option '--FEDERATED'
2015-10-27T04:15:47.617736Z 0 [ERROR] Aborting

2015-10-27T04:15:47.618737Z 0 [Note] Binlog end
2015-10-27T04:15:47.620737Z 0 [Note] Shutting down plugin 'ngram'
2015-10-27T04:15:47.621737Z 0 [Note] Shutting down plugin 'partition'
2015-10-27T04:15:47.623737Z 0 [Note] Shutting down plugin 'BLACKHOLE'
2015-10-27T04:15:47.624737Z 0 [Note] Shutting down plugin 'ARCHIVE'
2015-10-27T04:15:47.625737Z 0 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2015-10-27T04:15:47.627737Z 0 [Note] Shutting down plugin 'MRG_MYISAM'
2015-10-27T04:15:47.629738Z 0 [Note] Shutting down plugin 'MyISAM'
2015-10-27T04:15:47.630738Z 0 [Note] Shutting down plugin 'INNODB_SYS_VIRTUAL'
2015-10-27T04:15:47.631738Z 0 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2015-10-27T04:15:47.632738Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2015-10-27T04:15:47.635738Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2015-10-27T04:15:47.636738Z 0 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2015-10-27T04:15:47.637738Z 0 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2015-10-27T04:15:47.638739Z 0 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2015-10-27T04:15:47.639739Z 0 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2015-10-27T04:15:47.640739Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2015-10-27T04:15:47.641739Z 0 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2015-10-27T04:15:47.642739Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2015-10-27T04:15:47.643739Z 0 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2015-10-27T04:15:47.644739Z 0 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2015-10-27T04:15:47.645739Z 0 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2015-10-27T04:15:47.646739Z 0 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2015-10-27T04:15:47.647739Z 0 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2015-10-27T04:15:47.647739Z 0 [Note] InnoDB: Buffer pool(s) load completed at 151026 21:15:47
2015-10-27T04:15:47.648740Z 0 [Note] Shutting down plugin 'INNODB_METRICS'
2015-10-27T04:15:47.649740Z 0 [Note] Shutting down plugin 'INNODB_TEMP_TABLE_INFO'
2015-10-27T04:15:47.650740Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2015-10-27T04:15:47.651740Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2015-10-27T04:15:47.652740Z 0 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2015-10-27T04:15:47.653740Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2015-10-27T04:15:47.654740Z 0 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2015-10-27T04:15:47.654740Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2015-10-27T04:15:47.655740Z 0 [Note] Shutting down plugin 'INNODB_CMPMEM'
2015-10-27T04:15:47.656740Z 0 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2015-10-27T04:15:47.657740Z 0 [Note] Shutting down plugin 'INNODB_CMP'
2015-10-27T04:15:47.658741Z 0 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2015-10-27T04:15:47.658741Z 0 [Note] Shutting down plugin 'INNODB_LOCKS'
2015-10-27T04:15:47.659741Z 0 [Note] Shutting down plugin 'INNODB_TRX'
2015-10-27T04:15:47.660741Z 0 [Note] Shutting down plugin 'InnoDB'
2015-10-27T04:15:47.661741Z 0 [Note] InnoDB: FTS optimize thread exiting.
2015-10-27T04:15:47.662741Z 0 [Note] InnoDB: Starting shutdown...
2015-10-27T04:15:47.763751Z 0 [Note] InnoDB: Dumping buffer pool(s) to C:\ProgramData\MySQL\MySQL Server 5.7\Data\ib_buffer_pool
2015-10-27T04:15:47.779753Z 0 [Note] InnoDB: Buffer pool(s) dump completed at 151026 21:15:47
2015-10-27T04:15:49.017876Z 0 [Note] InnoDB: Shutdown completed; log sequence number 2472358
2015-10-27T04:15:49.018877Z 0 [Note] InnoDB: Removed temporary tablespace data file: "ibtmp1"
2015-10-27T04:15:49.019877Z 0 [Note] Shutting down plugin 'MEMORY'
2015-10-27T04:15:49.020877Z 0 [Note] Shutting down plugin 'CSV'
2015-10-27T04:15:49.020877Z 0 [Note] Shutting down plugin 'sha256_password'
2015-10-27T04:15:49.021877Z 0 [Note] Shutting down plugin 'mysql_native_password'
2015-10-27T04:15:49.022877Z 0 [Note] Shutting down plugin 'binlog'
2015-10-27T04:15:49.023877Z 0 [Note] C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqld.exe: Shutdown complete

A: I figured it out.
FEDERATED should be federated in my.ini file.

A: I recently help to my co-worker to enable this,
He was using wamp in windows 7,
You should have care with my.ini file.
you probably can see a line like this:
# The MySQL server
[wampmysqld]
port        = 3306
socket      = /tmp/mysql.sock
key_buffer_size = 16M
max_allowed_packet = 1M
sort_buffer_size = 512K
net_buffer_length = 8K

You should have to add this above to enable federeted:
# Here follows entries for some specific programs
[mysqld]
federated

You final result could be something like this:
    # Here follows entries for some specific programs
    [mysqld]
    federated
    # The MySQL server
    [wampmysqld]
    port        = 3306
    socket      = /tmp/mysql.sock
    key_buffer_size = 16M
    max_allowed_packet = 1M
    sort_buffer_size = 512K
    net_buffer_length = 8K
    read_buffer_size = 256K
    read_rnd_buffer_size = 512K
    myisam_sort_buffer_size = 8M
    basedir=c:/wamp/bin/mysql/mysql5.6.17
    log-error=c:/wamp/logs/mysql.log
    datadir=c:/wamp/bin/mysql/mysql5.6.17/data

Finally you have to restart your services.
I hope this help.


text:
Q: Show loading before load data to webview in Android how can I show a loading image when this code running ?
HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet("http://www.google.com");
      try
      {
          HttpResponse response = client.execute(request);
          BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
          String line;
          StringBuilder str = new StringBuilder();
          while((line = reader.readLine()) != null) {
              str.append(line);
      }
          objwebview.loadData(str.toString(), "text/html", "UTF-8");
  }
  catch(Exception e)
  {
      e.printStackTrace();
      objwebview.loadData(e.toString(), "text/html", "UTF-8");
  }

A: Change your code as for showing loading bar using AsyncTask
private class Getdataasynktask extends AsyncTask<String, Void, String> {

ProgressDialog progressDialog = new ProgressDialog(context);

      @Override
      protected void onPostExecute(String result) {
      // show loaging bar here

    progressDialog.setMessage("Loading...");
    progressDialog.setCancelable(false);
    progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    progressDialog.setProgress(0); // set percentage completed to 0%
    progressDialog.show();

      }

      @Override
      protected String doInBackground(String... params) {
          String strdata= getdatafromserver();
            return strdata;
      }

      @Override
      protected void onPreExecute(String result) {

       objwebview.loadData(result.toString(), "text/html", "UTF-8");
       // dismiss progress bar here
       progressDialog.dismiss();
      }
 public String getdatafromserver(){
     String line;
      objwebview.loadData(str.toString(), "text/html", "UTF-8");
      HttpClient client = new DefaultHttpClient();
      HttpGet request = new HttpGet("http://www.google.com");
      try
      {
          HttpResponse response = client.execute(request);
          BufferedReader reader = new BufferedReader(new
                    InputStreamReader(response.getEntity().getContent()));

          StringBuilder str = new StringBuilder();
          while((line = reader.readLine()) != null) {
              str.append(line);
      }

  }
  catch(Exception e)
  {
      e.printStackTrace();
      line=e.toString();

  }
return line;
}
}

for executing this AsyncTask from UI Thread use
new Getdataasynktask().execute("");

and you can also use onProgressUpdate and publishProgress for showing loading bar using AsyncTask and publishing results to Ui thread . for more info see
http://developer.android.com/reference/android/os/AsyncTask.html


text:
Q: Explanation of exponent integration It has been over $5$ years since I have done integration. After doing some research I understood basic rules of integrating exponents, such as dividing by the power.
However, I am unable to understand
1) Where the "$1$" came from in the photo attached in the final solution.
Also, I assume "$n$" came from substituting "$t$" for "$n$". But could someone
2) Explain how "$t=0$" affects the solution?
photo of problem:

Thank you.

A: Your two doubts are actually linked.
\begin{align}
\int_0^n a_0 \exp(-(i-g)t) \, dt &a= a_0 \left[\frac{\exp(-(i-g)t)}{-(i-g)}\right]_\color{blue}0^n \\
&= a_0\left[\frac{\exp(-(i-g)n)}{-(i-g)} - \frac{\exp(-(i-g)\color{blue}0)}{-(i-g)} \right] \\
&=a_0\left[\frac{\exp(-(i-g)n)}{-(i-g)} - \frac{\color{red}1}{-(i-g)} \right] \\
&=a_0\left[\frac{1-\exp(-(i-g)n)}{(i-g)}\right]
\end{align}
Recall that $e^0=1$.


text:
Q: Calculate the double integral Compute $$\int^{\infty}_{-\infty}{\int^{\infty}_{0}{xe^{-x^2e^y}}}dydx$$
Since x is just a constant in the inner integral I took it out and was only left with $\int^{\infty}_{0}{}e^{-x^2e^y}dy.$ This is where I'm stuck. I cannot figure out this integral. Could somebody help me with this if I'm in the right track, or am I completely wrong? I feel like this lacks an easy solution therefore the result might be complex.

A: First notice that the exchange of the order of integration is allowed by continuity, then $$\int_{-\infty}^{+\infty}\int_{0}^{+\infty}xe^{-x^{2}e^{y}}\, dydx=\int_{0}^{+\infty}\int_{-\infty}^{+\infty}xe^{-x^{2}e^{y}}\, dxdy.$$
But if $\phi(x):=xe^{-x^{2}e^{y}}$, then $\phi(-x)=-\phi(x)$ so we have a odd function over all the interval $]-\infty,+\infty[$. Can you continue from here?

A: If we set
$$f(x)=\int_0^\infty xe^{-x^2e^y}~\mathrm{d}y,$$
then
$$f(-x)=\int_0^\infty -xe^{-(-x)^2e^y}~\mathrm{d}y=-\int_0^\infty xe^{-x^2e^y}~\mathrm{d}y=-f(x),$$
i.e. $f$ is an odd function. Now showing that your integral
$$I=\int_{-\infty}^\infty\int_0^\infty xe^{-x^2e^y}~\mathrm{d}y~\mathrm{d}x=\int_{-\infty}^\infty f(x)~\mathrm{d}x$$
converges is very straightforward, and so we can compute it as its principal value. Thus, as the integral of an odd function over a symmetric interval is $0$, we finally get that
$$I=\lim_{c\to\infty}\underbrace{\int_{-c}^c f(x)~\mathrm{d}x}_{\text{$0$ as $f$ is odd}}=0.$$

A: $$
\begin{aligned}
\int_0^{+\infty}e^{-x^2e^y}dy &= \int_0^{+\infty}\frac{e^{-x^2e^y}}{x^2e^y}x^2e^ydy = \begin{vmatrix}
u = x^2e^y & \Rightarrow & du = x^2e^ydy \\
y = 0 &\Leftrightarrow &u = x^2 \\
y = +\infty &\Leftrightarrow &u = +\infty
\end{vmatrix} = \\
&= \int_{x^2}^{+\infty}\frac{e^{-u}}{u}du = \varphi\left(x^2\right),
\end{aligned}
$$
where $\varphi(\cdot)$ is some function.
Then,
$$
\begin{aligned}
\int_{-\infty}^{+\infty}\int_0^{+\infty}xe^{-x^2e^y}dydx &= \int_{-\infty}^{+\infty}x\varphi\left(x^2\right)dx = 0,
\end{aligned}
$$
since it is an integral of an odd function $\left(x\varphi\left(x^2\right)\right)$ over the symmetric interval $(-\infty, +\infty)$.

A: HINT: The inner integral over y is the incomplete Euler $\Gamma$ function
$$\int_0^{\infty } \exp \left(-x^2 \exp (y)\right) \, dy=\fbox{$\Gamma \left(0,x^2\right)\text{ if }\Re\left(x^2\right)>0$}$$
The outer integral over x results to
$$F(x)=\int x \Gamma \left(0,x^2\right) \, dx=\frac{1}{2} x^2 \Gamma \left(0,x^2\right)-\frac{e^{-x^2}}{2}$$
Now we use the integration limits
$$\underset{x\to \infty }{\text{lim}}F(x)-\underset{x\to -\infty }{\text{lim}}F(x)=0$$


text:
Q: Only one expression can be specified when attempting to use select lists in scalar function The following procedure sets a boolean value based on the rowcounts of each of the following queries and it is then supposed to return the true(1) or false(0) value back to Access; I am currently getting the error of "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS." How can I get this to work?
 CREATE FUNCTION [dbo].[FN_chk](@pF NVARCHAR(255), @pI NVARCHAR(100),
    @pL NVARCHAR(100), @pLY NVARCHAR(100))

RETURNS INT AS
BEGIN

    DECLARE @Bool BIT
    SET @Bool = 0

    -- check allDataTemp
    If ((SELECT DISTINCT theFN, theIN, theLN, theANA FROM aDT
        WHERE theFN = @pF  and theIN = @pI
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END

    -- check allDataTemp2
    If ((SELECT theFN, theIN, theLN, theANA FROM aDT2
        GROUP BY theFN, theIN, theLN, theANA
        HAVING theFN = @pF  and theIN = @pI
        and theLN = @pL  and theANA = @pLY) > 0)
        BEGIN
            SET @Bool = 1
            RETURN @Bool
        END

    -- Return the result of the function
    RETURN @Bool

END

A: As the ERROR already explains, use EXISTS
 If (EXISTS(SELECT DISTINCT theFN FROM aDT
    WHERE theFN = @pF  and theIN = @pI
       and theLN = @pL  and theANA = @pLY))
    BEGIN
        SET @Bool = 1
        RETURN @Bool
    END

Similarly change the other IF too...
EDIT: EXISTS is used when the number of rows could be zero. Also if you SELECT just one value to compare, it should work too.

A: Your query inside the IF returns a large number of columns. Comparing this to a number is meaningless. (eg is "Coding", "Maniac" > 0?)
The quickest fix is to switch to using exists
If exists (SELECT DISTINCT theFN, theIN, theLN, theANA FROM aDT
    WHERE theFN = @pF  and theIN = @pI
    and theLN = @pL  and theANA = @pLY)
    BEGIN

More optimally, don't both with the columns at all - all you are about is that there are rows:
If exists (SELECT count(1) FROM aDT
    WHERE theFN = @pF  and theIN = @pI
    and theLN = @pL  and theANA = @pLY)
    BEGIN


text:
Q: What exactly happens in Morrok's cave? In one of the Star Trek: Voyager Episodes (I really can't remember which one), Kathy and her team meet a borderline xenophobic race, which breed by cloning

and get younger with time.

It so happens that Tuvok's shuttle crash lands on one of their sacred moons. Tuvok finds that there's some kids on the moon who appear to come from a crashed shuttle and they tell him about

Morrok and its cave. However it so happens that there's no such creature and that cave is where the 'children' reach the final stage of their lives and then vanish, which is evident from the clothes found in the caves.

In the last scene Tuvok is seen taking the girl to the cave. What exactly happens inside?

A: You're referring to the 22nd episode of Star Trek: Voyager Season 2, "Innocence".
In this episode, Tuvok is stranded on a moon with a group of humanoid aliens who look and behave like children, and so he assumes that's what they are. However, it's later revealed by other members of their species, Drayans, that they age in reverse, and one of these 'children', Tressa, is actually 96 years old, and very near the end of her natural lifespan.
It's also explained that their bodies lose cohesion after a set period of time, causing them to turn into energy. This is supported by the fact that when Tuvok went into the cave to search for the other 'children' who'd gone missing, all he found was their clothing (a fact you mentioned yourself).

JANEWAY: This child wants to live. We're going to do whatever we can to help her.
ALCIA: It is not a choice, this is her time. Tressa has reached the end of her life.
TUVOK: She has barely begun it.
ALCIA: She is ninety six years old. Tressa, these people are outsiders. They don't understand how we live. They see us as strange because their aging process is reversed. Please, you don't belong with them. I'm here to help you now.
TRESSA: No, leave me alone.
ALCIA: It's perfectly natural to be frightened. You're taking a step into the unknown. The attendants would have helped you prepare yourself. You were never meant to face this time alone.
TRESSA: We weren't alone. Tuvok was here. He stayed with us and made us feel safe. He told us there was no Morrok and that we shouldn't be afraid. He took care of us, even when we didn't behave as well as Vulcan children.
ALCIA: He was right about the Morrok. It only exists in stories. At this age they become easily confused. Their memories are clouded. Near the end of life we reach a state of complete innocence. We free ourselves from all responsibilities to this life and we leave it peacefully.
TUVOK: Tressa doesn't seem to be ready. Perhaps she needs more time.
ALCIA: That's not for you or me to decide. This is a normal biological process which begins the day we are created. The energy contained within our bodies remains cohesive for a limited number of years and then it is released. Nothing can change that.
TRESSA: Nothing?
ALCIA: No. It's the natural course of life.
JANEWAY: Why was it so important that Tressa stay here?
ALCIA: We believe this is where the very first spark of life was created. We are all compelled by a powerful instinct to return here at the end to complete the cycle and rejoin the infinite energy. Tressa, do you feel it calling to you?
Star Trek: Voyager - S02E22 - "Innocence"

After learning of all this, Tuvok accepts that Tressa has reached the end of her life, and accompanies her into the cave so he can be there to provide her comfort and reassurance in the moments before she dies and turns into energy herself.
Tressa's death of natural causes was confirmed in the Star Trek Encyclopedia.

Tressa. (Tiffany Trauberman). Drayan individual who, despite her advanced age of 96, looked and acted like what many humanoid species would consider to be a young child. In 2372, Tressa and several other elder Drayans traveled to one of the Drayan moons in order to carry out their final ritual. Their shuttle crashed on the moon, and all of their Attendants died, leaving the elders alone. Lieutenant Tuvok, whose shuttle had also crashed there, comforted and took care of the easily confused Drayans. With Tuvok's help, Tressa faced her final ritual without fear, and she died of natural causes shortly thereafter. ("Innocence" [VGR]).
Star Trek Encyclopedia

A: The episode is ST:VOY S2E22 - Innocence. Oneliner from Memory Alpha:

Tuvok is trapped on a moon with a group of alien children who are disappearing, one by one.

You can read a summary of the episode on memory alpha. A very short part is that Tuvok is contacted by the race of the children and they explain that their race "ages in reverse" and that the children were their old ones. They believed that the moon was sacred and everybody tried to go there to die and the children were, in fact, something like 90 years old.


text:
Q: Working with UTF-8 instead of windows-1255 In the past, I used to work with windows-1255. Now my new page is written in UTF-8. When I send a query to DB (MS-Access), I get no results. The query on the URL shows the same like I type in by myself, but in this case (typing) I get results. How can it happen that I see the same URL on my IE and get the results and the other (that come from UTF-8) get no data?

A: If you're using IE, try right-clicking in the page and checking the Encoding in both cases. Sometimes IE "auto detects" the encoding incorrectly, so any non-Ascii characters may be sent to the server encoded in a different way to how the server is decoding. Fiddler may be useful in comparing what's being sent back and forth in both cases.


text:
Q: Environment entry duplicated for Web module on WebSphere My ear contains one EJB module and one Web module. One singleton EJB within the EJB module has a String field annotated with @Resource:
@Resource(name = "lecmConfigServiceLookupName")
 private String lecmConfigServiceLookupName;
The META-INF/ejb-jar.xml specifies a mapping for this environment entry:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
         version="3.1">
    <enterprise-beans>
        <session id="ConfigSingleton">
            <ejb-name>ConfigSingleton</ejb-name>
            <ejb-class>ru.brbpm.custom_search_ejb.ConfigSingleton</ejb-class>
            <session-type>Singleton</session-type>
            <init-on-startup>true</init-on-startup>
            <env-entry>
                <env-entry-name>lecmConfigServiceLookupName</env-entry-name>
                <env-entry-type>java.lang.String</env-entry-type>
                <env-entry-value>ejb/lecm/common-service.jar/ConfigServiceImpl#ru.brbpm.lecm.shared.api.ConfigServiceRemote</env-entry-value>
            </env-entry>
        </session>
    </enterprise-beans>
</ejb-jar>
When I get to deploying the ear to WebSphere 8.5.5.3 I see two identical environment entries - one for the EJB module and the other for the Web module:

The entry for the web module also does not have the default value and adding an ejb-jar.xml to WEB-INF folder does not help.
How do I get rid of the environment entry for the Web module or at least provide it with a default value? As long as the entry for the Web module is not specified the application will not start.

A: Figured it out - turns out the Web module had an unnecessary transitive dependency on the ejb-client of the EJB module. WebSphere was detecting the EJBs in the the ejb-client.jar that was in the Web module's WEB-INF/lib.


text:
Q: Exporting a Keras model as a TF Estimator: trained model cannot be found I encountered the following issue when trying to export a Keras model as a TensorFlow Estimator with the purpose of serving the model. Since the same problem also popped up in an answer to this question, I will illustrate what happens on a toy example and provide my workaround solution for documentation purposes. This behaviour occurs with Tensorflow 1.12.0 and Keras 2.2.4. This happens with actual Keras as well as with tf.keras.
The problem occurs when trying to export an Estimator that was created from a Keras model with tf.keras.estimator.model_to_estimator. Upon calling estimator.export_savedmodel, either a NotFoundError or a ValueError is thrown.
The below code reproduces this for a toy example.
Create a Keras model and save it:
import keras
model = keras.Sequential()
model.add(keras.layers.Dense(units=1,
                                activation='sigmoid',
                                input_shape=(10, )))
model.compile(loss='binary_crossentropy', optimizer='sgd')
model.save('./model.h5')

Next, convert the model to an estimator with tf.keras.estimator.model_to_estimator, add an input receiver function and export it in the Savedmodel format with estimator.export_savedmodel:
# Convert keras model to TF estimator
tf_files_path = './tf'
estimator =\
    tf.keras.estimator.model_to_estimator(keras_model=model,
                                          model_dir=tf_files_path)
def serving_input_receiver_fn():
    return tf.estimator.export.build_raw_serving_input_receiver_fn(
        {model.input_names[0]: tf.placeholder(tf.float32, shape=[None, 10])})

# Export the estimator
export_path = './export'
estimator.export_savedmodel(
    export_path,
    serving_input_receiver_fn=serving_input_receiver_fn())

This will throw:
ValueError: Couldn't find trained model at ./tf.

A: My workaround solution is as follows. Inspecting the ./tf folder makes clear that the call to model_to_estimator stored the necessary files in a keras subfolder, while export_model expects those files to be in the ./tf folder directly, as this is the path we specified for the model_dir argument:
$ tree ./tf
./tf
└── keras
    ├── checkpoint
    ├── keras_model.ckpt.data-00000-of-00001
    ├── keras_model.ckpt.index
    └── keras_model.ckpt.meta

1 directory, 4 files

The simple workaround is to move these files up one folder. This can be done with Python:
import os
import shutil
from pathlib import Path

def up_one_dir(path):
    """Move all files in path up one folder, and delete the empty folder
    """
    parent_dir = str(Path(path).parents[0])
    for f in os.listdir(path):
        shutil.move(os.path.join(path, f), parent_dir)
    shutil.rmtree(path)

up_one_dir('./tf/keras')

Which will make the model_dir directory look like this:
$ tree ./tf
./tf
├── checkpoint
├── keras_model.ckpt.data-00000-of-00001
├── keras_model.ckpt.index
└── keras_model.ckpt.meta

0 directories, 4 files

Doing this manipulation in between the model_to_estimator and the export_savedmodel calls allows to export the model as desired:
export_path = './export'
estimator.export_savedmodel(
    export_path,
    serving_input_receiver_fn=serving_input_receiver_fn())

INFO:tensorflow:SavedModel written to:
  ./export/temp-b'1549796240'/saved_model.pb


text:
Q: PHPUnit Mock - Expect 1 of multiple method names to be called Im looking at mocking a logger class within a service and ensuring it attempts to logs erros. It follows psr/log interfaces so error logging can be achieved through multiple routes. Calling an error method or calling a log method with the LogLevel::error
Is there a way in PHPUnit mocking to check this.
<?php
// Create a mock logger that can be observed
$logger = $this->createMock(LoggerInterface::class);

// This fails is $logger->log(LogLevel::error, 'some message'); is called
$logger
    ->expects($this->once())
    ->method('error');

// This fail is $logger->error() is called
$logger
    ->expects($this->once())
    ->method('log')
    ->with(LogLevel::ERROR);

Both the methods above do the same thing, log errors so i'm not really bothered which one is used, as long as one is used.
Does anyone have any ideas on how this can be achieved?
I've seen there is a method called $this->logicalOr() but i dont think it's fit for purpose.
Thanks in advance everyone!

A: Got this working. Asserting that an exception is thrown and logged during a test case.
Testing for a scenario similar to this
<?php

class Service
{
    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function setLogger(\Psr\Log\LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    public function doSomething($value)
    {
        try {
            $this->handleDoingSomething($value);
        }
        catch (Exception $e) {
            $this->logger->error($e->getMessage());

            // or optionally

            $this->logger->log(\Psr\Log\LogLevel::ERROR, $e->getMessage());

            throw $e;
        }
    }

    protected function handleDoingSomething($value)
    {
        throw new Exception();
    }
}

Can be achieved by using a test case like this
<?php

class ServiceTest extends \PHPUnit\Framework\TestCase
{
    public function testDoSomething()
    {
        $loggerCalledCount = 0;
        $loggerCallback = function ($methodParameter) use (&$loggerCalledCount) {
            $loggerCalledCount++;

            return true;
        };

        $logger = $this->createMock(\Psr\Log\LoggerInterface::class);
        $logger->method('error')->with($this->callback($loggerCallback));
        $logger->method('log')->with(\Psr\Log\LogLevel::ERROR, $this->callback($loggerCallback));

        $exceptionCaught = false;
        try {
            $service = new Service();
            $value = 'this value will trigger an exception if used';
            $service->doSomething($value);
        }
        catch (Exception $e) {
            $exceptionCaught = true;
        }

        $this->assertTrue($exceptionCaught);
        $this->assertGreaterThan(0, $loggerCalledCount);
    }
}

Hope that helps people out.


text:
Q: A field initializer cannot reference the non-static field, method, or property 'SignalServer.connectionString' (CS0236) I'm trying to use SqlDependencyEx it accepts the first argument as a connection string, if I use my DB connection string directly it works but I don't want to give it directly instead I want it to grab DefaultConnection using Configuration. but I'm getting this error

A field initializer cannot reference the non-static field, method, or
  property 'SignalServer.connectionString' (CS0236)

public class SignalServer : Hub
        {
            public readonly TestController _testController;
            public IConfiguration Configuration { get; }
            string connectionString = "";

            public SignalServer(TestController testController, IConfiguration configuration)
            {
                Configuration = configuration;
                _testController = testController;
                connectionString = Configuration.GetConnectionString("DefaultConnection");
            }

            public async void NotifyConnection()
            {
                await Clients.All.SendAsync("TestBrodcasting", _testController.GetAllApps());
            }

            SqlDependencyEx sqlDependency = new SqlDependencyEx(connectionString);

        }

Update:
public class SignalServer : Hub
{
    public readonly TestController _testController;
    public IConfiguration Configuration { get; }

    public SignalServer(TestController testController, IConfiguration configuration)
    {
        Configuration = configuration;
        _testController = testController;
        SqlDependencyEx sqlDependency = new SqlDependencyEx(Configuration.GetConnectionString("DefaultConnection"), "dbName", "tablename");
    }

    public async void NotifyConnection()
    {
        await Clients.All.SendAsync("TestBrodcasting", _testController.GetAllApps());
    }

    private void RegisterNotification()
    {
        sqlDependency.TableChanged += OnDataChange;
        sqlDependency.Start();
    }

    private void UnregisterNotification()
    {
        sqlDependency.Stop();
        sqlDependency.TableChanged -= OnDataChange;
    }

    private void OnDataChange(object sender, SqlDependencyEx.TableChangedEventArgs e)
    {

    }

    private void Dispose()
    {
        UnregisterNotification();
    }
}

A: Your problem is this line:
SqlDependencyEx sqlDependency = new SqlDependencyEx(connectionString);

Move it inside the constructor instead:
SqlDependencyEx sqlDependency;
public SignalServer(TestController testController, IConfiguration configuration)
{
    Configuration = configuration;
    _testController = testController;
    connectionString = Configuration.GetConnectionString("DefaultConnection");
    //Put it here
    sqlDependency = new SqlDependencyEx(connectionString);
}

I don't know much about your design but you probably don't even need to save the connection string in the connectionString field. You might be able to just use it directly from the call to the Configuration.GetConnectionString method or the reference to the Configuration object you are storing.


text:
Q: Expose mongoose models via Node.js REST service There are following schemas:
var Quest = new Schema({
    name: { type: String, required: true }
});

var Attempt = new Schema({
    quest: { type: ObjectId, ref: 'Quest' },
    success: { type: Boolean, required: true, default: false }
});

var Person = new Schema({
    name: { type: String, required: true },
    attempts: [Attempt]
});

We have a list of quests and a list of people. Every time some person attempts to pass a quest, we create an Attempt entry.
It would be nice to expose a Person via my REST service so, that it would have a list of empty Attempts containing all attached attempts plus one attempt for every Quest that wasn't attempted.
I've ended up having something like this:
router.get('/people/:id', function(req, res) {
    return PeopleModel.findById(req.params.id, function (err, person) {
        if(!person) {
            ....
        }
        if (!err) {
            return QuestsModel.find(function (err, quests) {
                if (!err) {
                    var result = person.attempts;
                    quests.forEach(function(quest){
                        var attempt = person.attempts.find(attempt=>{attempt.quest == quest._id});
                        if(!attempt)
                        {
                          var newAttempt = {
                                quest: quest,
                                success: false
                          };
                          result.push(newAttempt);
                        }
                        else {
                          result.push(attempt);
                        }
                    });
                    person.attempts = result;
                    return res.send({ status: 'OK', person:person });
                } else {
                   ...
                }
            });
        } else {
            ...
        }
    });
});

That doesn't feel right. Is there a common practice for such situations? Maybe some kind of mapping.


text:
Q: Django ManyToManyField : how to choose its place? I have two possibilities concerning the ManyToManyField in django :
putting it in the "parent" class :
from django.db import models

class Person(models.Model):
    pass

class Group(models.Model):
    members = models.ManyToManyField(Person, related_name='group')

putting it in the "child" class
from django.db import models

class Group(models.Model):
    pass

class Person(models.Model):
    groups = models.ManyToManyField(Group, related_name='members')

What is the difference between these two options ?
Is there a reason to privilege one over the other ?


text:
Q: Concurrency in Java - wait for execution to be finished So I am currently doing some work with Multi-Threading in Java and I'm pretty stuck on a, most likely, simple thing.
I currently have a JButton that, when pressed invokes the method as follows:
private void clickTest() throws InterruptedException{
    statOrganizer.incrementHappiness();
    Thread t = new Thread(new Happiness(workspaceHappy));
    t.start();
}

and then takes around 10-30 seconds to complete. During this time however, it is still possible to re-click the JButton so that it messes with how the information is displayed.
What I want to do is during the time this particular thread is "alive", disable the button so that it is no longer possible to click it(and thus activate this thread once it's already going). Once the thread is finished, I want to re-enable the button again.
The button code just looks like this
button.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent evt) {
                if (evt.getClickCount() == 1) {
                        try {
                            clickTest();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                }
            }
        });

A: Disable the button right before starting the thread. In the thread, at the end, post an event that would re-enable the button (using invokeLater).
You may also need a cancel option, but that's a separate question.

A: The nice solution for this is to use a glass pane to capture all events and stopping them from propagating to any of your UI elements on the panel under the glass pane. Of course while you only have one or two, you can call setEnabled(false) on them manually but glass panes give you more flexibility, you'll never have to worry about adding a new element to your UI and forgetting to disable it during background processing.
Probably an overkill for one button though.
Another, unrelated thing you should consider is the use of Executors instead of launching threads for background tasks. It results in cleaner and more scalable code.

A: Try the following:
button.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            if (evt.getClickCount() == 1) {
                    try {
                        clickTest();
                        button.setEnabled(false);//this assume 'button' is final
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            }
        }
    });

Then, modify the run method of your Happiness class:
public void run()
{

 //your processing code here
 ...

 button.setEnabled(true);
 //reference to button can be passed in constructor of Happiness
 // or access using getter, ... This really depend on your implementation.

}


text:
Q: Ora-00903 invalid table name I'm trying to make a left join query and getting this error. Can someone tell me what im doing wrong?
SELECT incid,
  db_name,
  snap_time
FROM
  (SELECT incid,
    db_name,
    (TRUNC(MAX(optime),'MI')-TO_DATE('1970-01-01', 'YYYY-MM-DD')) * 86400000 SNAP_TIME
  FROM ticket_details s1
  WHERE optime BETWEEN sysdate-1 AND sysdate +6
  AND upper(db_name) = upper('EXPP')
  GROUP BY incid,
    db_name
  ) s1
LEFT OUTER JOIN
SELECT snap_time ,
  instance_name,
  cpu_used
FROM
  (SELECT (SNAP_TIME-TO_DATE('1970-01-01', 'YYYY-MM-DD')) * 86400000 SNAP_TIME,
    instance_name,
    ROUND( (
    CASE 'CPU_USED'
      WHEN 'CPU_USED'
      THEN CPU_USED
      WHEN 'REDO'
      THEN REDO
      WHEN 'TPS'
      THEN TPS
      WHEN 'PROCESS_USED'
      THEN PROCESS_USED
      WHEN 'LOGONS_PER_SEC'
      THEN LOGONS_PER_SEC
      WHEN 'LOGICAL_READS_MBPS'
      THEN LOGICAL_READS_MBPS
      WHEN 'LFS'
      THEN LFS
      WHEN 'LFPW'
      THEN LFPW
      WHEN 'SINGLE_BLOCK_READ'
      THEN SINGLE_BLOCK_READ
      WHEN 'IOPS_MBPS'
      THEN IOPS_MBPS
      WHEN 'PHY_READS'
      THEN PHY_READS
      WHEN 'PHY_WRITES'
      THEN PHY_WRITES
      WHEN 'STREAMS_IO'
      THEN STREAMS_IO
      WHEN 'RMAN_IO'
      THEN RMAN_IO
      WHEN 'NETWORK'
      THEN NETWORK
      WHEN 'CONCURRENCY_AAS'
      THEN CONCURRENCY_AAS
      WHEN 'COMMIT_AAS'
      THEN COMMIT_AAS
      WHEN 'USER_IO_AAS'
      THEN USER_IO_AAS
      WHEN 'SYSTEM_IO_AAS'
      THEN SYSTEM_IO_AAS
      WHEN 'OTHERS_AAS'
      THEN OTHERS_AAS
      WHEN 'CONFIG_AAS'
      THEN CONFIG_AAS
      WHEN 'APP_AAS'
      THEN APP_AAS
      WHEN 'CLUSTER_AAS'
      THEN CLUSTER_AAS
      WHEN 'NETWORK_AAS'
      THEN NETWORK_AAS
      WHEN 'ADMIN_AAS'
      THEN ADMIN_AAS
      WHEN 'TOTAL_AAS'
      THEN TOTAL_AAS
      WHEN 'CPU_AAS'
      THEN CPU_AAS
      WHEN 'USER_CALLS'
      THEN USER_CALLS
      WHEN 'PGA_USED'
      THEN PGA_USED
      ELSE NULL
    END), 2) CPU_USED
  FROM THIRDEYE_ORACLE_METRIC_HIST
  ) s2 ON s1.db_name = s2.instance_name
AND s1.snap_time     = s2.snap_time

A: I think you are missing a parenthesis after left join:
SELECT incid,
  db_name,
  snap_time
FROM
  (SELECT incid,
    db_name,
    (TRUNC(MAX(optime),'MI')-TO_DATE('1970-01-01', 'YYYY-MM-DD')) * 86400000 SNAP_TIME
  FROM ticket_details s1
  WHERE optime BETWEEN sysdate-1 AND sysdate +6
  AND upper(db_name) = upper('EXPP')
  GROUP BY incid,
    db_name
  ) s1
LEFT OUTER JOIN
( -- This Parenthesis
SELECT snap_time ,
  instance_name,
  cpu_used
FROM
  (SELECT (SNAP_TIME-TO_DATE('1970-01-01', 'YYYY-MM-DD')) * 86400000 SNAP_TIME,
    instance_name,
    ROUND( (
    CASE 'CPU_USED'
      WHEN 'CPU_USED'
      THEN CPU_USED
      WHEN 'REDO'
      THEN REDO
      WHEN 'TPS'
      THEN TPS
      WHEN 'PROCESS_USED'
      THEN PROCESS_USED
      WHEN 'LOGONS_PER_SEC'
      THEN LOGONS_PER_SEC
      WHEN 'LOGICAL_READS_MBPS'
      THEN LOGICAL_READS_MBPS
      WHEN 'LFS'
      THEN LFS
      WHEN 'LFPW'
      THEN LFPW
      WHEN 'SINGLE_BLOCK_READ'
      THEN SINGLE_BLOCK_READ
      WHEN 'IOPS_MBPS'
      THEN IOPS_MBPS
      WHEN 'PHY_READS'
      THEN PHY_READS
      WHEN 'PHY_WRITES'
      THEN PHY_WRITES
      WHEN 'STREAMS_IO'
      THEN STREAMS_IO
      WHEN 'RMAN_IO'
      THEN RMAN_IO
      WHEN 'NETWORK'
      THEN NETWORK
      WHEN 'CONCURRENCY_AAS'
      THEN CONCURRENCY_AAS
      WHEN 'COMMIT_AAS'
      THEN COMMIT_AAS
      WHEN 'USER_IO_AAS'
      THEN USER_IO_AAS
      WHEN 'SYSTEM_IO_AAS'
      THEN SYSTEM_IO_AAS
      WHEN 'OTHERS_AAS'
      THEN OTHERS_AAS
      WHEN 'CONFIG_AAS'
      THEN CONFIG_AAS
      WHEN 'APP_AAS'
      THEN APP_AAS
      WHEN 'CLUSTER_AAS'
      THEN CLUSTER_AAS
      WHEN 'NETWORK_AAS'
      THEN NETWORK_AAS
      WHEN 'ADMIN_AAS'
      THEN ADMIN_AAS
      WHEN 'TOTAL_AAS'
      THEN TOTAL_AAS
      WHEN 'CPU_AAS'
      THEN CPU_AAS
      WHEN 'USER_CALLS'
      THEN USER_CALLS
      WHEN 'PGA_USED'
      THEN PGA_USED
      ELSE NULL
    END), 2) CPU_USED
  FROM THIRDEYE_ORACLE_METRIC_HIST
  )
  )-- This one too
  s2 ON s1.db_name = s2.instance_name
AND s1.snap_time     = s2.snap_time

A: ...
LEFT OUTER JOIN
SELECT snap_time ,
...

You need some parenthesis here