Q:

Android SearchView widget only works for Launcher Activity

I'm facing a very weird error right now. Basically, the app can search Google Places API using SearchView widget and show the results in Google Maps Android API V2, and the searchview widget is placed in action bar. I have referenced to this tutorial:
http://wptrafficanalyzer.in/blog/android-searchview-widget-with-google-places-api-using-actionbarsherlock-library/
The app works fine when the searchable activity (I name it as SearchPlace) is the main and launcher activity. However, if I try to intent to this activity from another activity, the app crash. I got NullPointerException caused by handleIntent().
 I have attached a portion of the Manifest file below SearchPlace is the name of my searchable activity.
<!-- Protect the map component of the application using application signature -->
<permission
    android:name="in.wptrafficanalyzer.locationsherlocksearchviewmapv2.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<!-- Allows to receive map -->
<uses-permission android:name="in.wptrafficanalyzer.locationsherlocksearchviewmapv2.permission.MAPS_RECEIVE" />

<!-- Used by the Google Maps Android API V2 to download map tiles from Google Maps servers -->
<uses-permission android:name="android.permission.INTERNET" />

<!-- Allows the Google Maps Android API V2 to cache map tile data in the device's external storage area -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!-- Allows the Google Maps Android API V2 to use WiFi or mobile cell data (or both) to determine the device's location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Allows the Google Maps Android API V2 to use the Global Positioning System (GPS)
to determine the device's location to within a very small area -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Allows to contact Google Serves -->
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

<!-- Google Maps Android API V2 requires OpenGL ES version 2 -->
<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Sherlock" >
    <activity
        android:name="in.wptrafficanalyzer.locationsherlocksearchviewmapv2.Home"
        android:label="@string/app_name"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>

    <activity
        android:name="in.wptrafficanalyzer.locationsherlocksearchviewmapv2.SearchPlace"
        android:label="@string/app_name"
        android:launchMode="singleTop"
       >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <!-- Points to searchable activity -->
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchPlace" />

        <!-- Points to searchable meta data -->
        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />
    </activity>
    <provider
        android:name=".PlaceProvider"
                    android:authorities="in.wptrafficanalyzer.locationsherlocksearchviewmapv2.PlaceProvider"
        android:exported="false" />

    <!-- Specifies the Android API Key, which is obtained from Google API Console -->
    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="YOUR_ANDROID_API_KEY" />
</application>

The error log is attached below. It seems like my handleIntent() caused the error.
07-31 01:49:53.685: E/AndroidRuntime(5539): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.locationsherlocksearchviewmapv2/in.wptrafficanalyzer.locationsherlocksearchviewmapv2.SearchPlace}: java.lang.NullPointerException

07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.os.Looper.loop(Looper.java:137)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at java.lang.reflect.Method.invokeNative(Native Method)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at java.lang.reflect.Method.invoke(Method.java:511)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at dalvik.system.NativeStart.main(Native Method)
07-31 01:49:53.685: E/AndroidRuntime(5539): Caused by: java.lang.NullPointerException
07-31 01:49:53.685: E/AndroidRuntime(5539):     at in.w  ptrafficanalyzer.locationsherlocksearchviewmapv2.SearchPlace.handleIntent(SearchPlace.java:473)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at in.wptrafficanalyzer.locationsherlocksearchviewmapv2.SearchPlace.onCreate(SearchPlacer.java:129)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.Activity.performCreate(Activity.java:5104)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
07-31 01:49:53.685: E/AndroidRuntime(5539):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)

My SearchPlace Activity
    @Override
protected void onCreate(Bundle savedInstanceState)
{

    super.onCreate(savedInstanceState);
    setContentView(R.layout.google_map_v2);

    handleIntent(getIntent());

}

private void handleIntent(Intent intent)
{
    if(intent.getAction().equals(Intent.ACTION_SEARCH))
    {
        doSearch(intent.getStringExtra(SearchManager.QUERY));
    }
    else if(intent.getAction().equals(Intent.ACTION_VIEW))
    {
        getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
    }
}

@Override
protected void onNewIntent(Intent intent)
{
    super.onNewIntent(intent);
    setIntent(intent);
    handleIntent(intent);
}

private void doSearch(String query)
{
    Bundle data = new Bundle();
    data.putString("query", query);
    getSupportLoaderManager().restartLoader(0, data, this);
}

private void getPlace(String query)
{
    Bundle data = new Bundle();
    data.putString("query", query);
    getSupportLoaderManager().restartLoader(1, data, this);
}

@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle query)
{
    CursorLoader cLoader = null;
    if(arg0 == 0)
        cLoader = new CursorLoader(getBaseContext(),
                PlaceProvider.SEARCH_URI, null, null, new String[]
                { query.getString("query") }, null);
    else if(arg0 == 1)
        cLoader = new CursorLoader(getBaseContext(),
                PlaceProvider.DETAILS_URI, null, null, new String[]
                { query.getString("query") }, null);
    return cLoader;

}

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c)
{
    showLocations(c);

}

@Override
public void onLoaderReset(Loader<Cursor> arg0)
{
    // TODO Auto-generated method stub
}

Can anyone help me plz ?
Thank you

A:

Problem solved, modify the handleIntent() as
if(Intent.ACTION_SEARCH.equals(intent.getAction()))
{
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
else if(Intent.ACTION_VIEW.equals(intent.getAction()))
{
getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
}


Q:

bash - extract day of week of variable

What is the syntax to extract the day of the week from a stored date variable?
The dateinfile format is always [alphanum]_YYYYMMDD.
In this pseudocode example, trying to get dayofweek to store Saturday:
#! /bin/bash

dateinfile="P_20090530"
dayofweek="$dateinfile -u +%A"

A:

[me@home]$ date --date=${dateinfile#?_} "+%A"
Saturday

Or, to put it as you've requested:
[me@home]$ dayofweek=$(date --date=${dateinfile#?_} "+%A")
[me@home]$ echo $dayofweek
Saturday

A:

date -d $(echo $dateinfile | cut -f2 -d_) -u +%A

The inner expression separates the 20090530 from P_20090530, and the outer one extracts the day of week from that date


Q:

Why is Rails class loading in development slow?

I've got a larger Rails 3.1 application.  It's getting super slow in development mode.  I've tracked down part of the problem to slow class autoloading.  I have a couple hundred models in my system and am using about 130 gems.
If my controller does nothing other than reference class names (i.e
def index
  User
  Order
  Game
  LineItem
  # and so on...
  render :text => ''
end

The load of the page can take almost one second, just for this with some of my models.  The log looks something like:
Completed 200 OK in 762ms (Views: 3.2ms | ActiveRecord: 3.9ms)

I've tested this with Ruby 1.9.2 and 1.9.3.

A:

This was largely fixed in Rails 3.2.


Q:

How to send and receive HTTP POST requests in Python

I need a simple Client-side method that can send a boolean value in a HTTP POST request, and a Server-side function that listens out for, and can save the POST content as a var.
I am having trouble finding information on how to use the httplib.
Please show me a simple example, using localhost for the http connection.

A:

For the client side, you can do all sorts of requests using this python library: requests. It is quite intuitive and easy to use/install.
For the server side, I'll recommend you to use a small web framework like Flask, Bottle or Tornado. These ones are quite easy to use, and lightweight.
For example, a small client-side code to send the post variable foo using requests would look like this:
import requests
r = requests.post("http://yoururl/post", data={'foo': 'bar'})
# And done.
print(r.text) # displays the result body.

And a server-side code to receive and use the POST request using flask would look like this:
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['POST'])
def result():
    print(request.form['foo']) # should display 'bar'
    return 'Received !' # response to your request.

This is the simplest & quickest way to send/receive a POST request using python.


Q:

Destination Goal not taking funnel into consideration

I have a very basic site goal:
When someone gets to the '/my-account' page directly from the '/component/community/ajaxregister/ajaxregister' page, it needs to count it as a conversion (Registration).
I have a custom destination goal set up:
Destination = '/my-account'
Funnel: ON
Step 1 '/component/community/ajaxregister/ajaxregister' Requires? YES
The registration counts in my db do not match the goal count and the 'Reverse Goal Path' report shows that there are conversions being registered where the 'Goal Previous - Step 1' includes pages other than the registration page.
Any ideas on how to make this goal register only when one lands on my-account from the registration page?

A:

The "required step" merely affects funnel visualization, not goal conversion. So by default there is no way not make this count only when people come from the registration page.
To solve this in code (and thus make the question on topic :-) ) you could

check the referring page on your goal conversion page, then
fire an event when the referrer is the registration pages, and
then switch to an event-based goal in the GA backend

That way you would not have a funnel (does not work with event based goals), but at least you'd have the "correct" number of conversions.


Q:

任意の辞書で「もしかして」検索機能を提供するライブラリまたはアルゴリズム

誤字を検出して正解の単語をサジェストする、いわゆる「もしかして」検索を実装しようとしています。
使用する正解の単語コーパス(以下『辞書』)を検索対象の項目ごとに切り替えて精度を上げる運用を考えています。
(例えば氏名の項目には『氏名データベース』から、注文の項目には『自社の取扱い商品名リスト』から生成した辞書をそれぞれ割り当てます)
オンプレミス環境で任意の辞書からレーベンシュタイン距離が1の誤字(挿入、置換、削除を1文字行って正解に合致する誤字)と正解を表示することが目的です。
日本語に対してこの校正用途で使用可能なライブラリまたはアルゴリズムは公開されているのでしょうか。
言語やOSは問いません。
自作のコードではgrepとループを繰り返す総当たり処理しか思いついていないため、項目数や辞書の単語数が増えてくると低速になることを懸念しております。
高速なライブラリがあれば試用したいのですがうまく見つけられないため質問させていただきました。

A:

PostgreSQLでは、拡張機能fuzzystrmatchでLevenshteinが提供されています。
https://www.postgresql.org/docs/10/static/fuzzystrmatch.html
また、Elasticsearchでも、可能と思われます。
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-fuzzy-query.html


Q:

Disable full-screen on iOS Flex 4.6 using Adobe Air 3.4

I'm creating a FLEX app for iOS and Android. To be able to use Higher Resolution icons for the app, I had to include Adobe Air 3.4 in FLEX 4.6 SDK (default is 3.1). Everything seems to work like charm exept I can't disable full-screen app on iOS.
Here is how it looks like right now:

Here is the code from configuration-app.xml file:
<initialWindow>
    <systemChrome>standard</systemChrome>
    <aspectRatio>portrait</aspectRatio>
    <autoOrients>false</autoOrients>
    <fullScreen>false</fullScreen>
    <visible>true</visible>
    <softKeyboardBehavior>none</softKeyboardBehavior>
</initialWindow>

Any idea how to solve this?
Thanks

A:

This is just the way iOS 7 works. It is a feature, not a bug. You have two options:

Create a skin for ViewNavigator that detects if it is on iOS 7+ and pushes the content area down 40px (for iPhone. Not sure if it is different on iPad).
Upgrade to Flex 4.12 which introduced a CSS style, and OS and version specific media queries to get around this.

Additionally, you are going to want to upgrade AIR. 3.4, besides being close to 2 years old, will not be accepted by the App Store. To get your app into the app store, you need to be on at least 4.0 (which added support for XCode 5, which Apple began requiring in February). For the record, AIR is currently on version 13.0 (after 4.0, the number was bumped to match the Flash Player version)


Q:

Undefined variable: content

My error:Message: Undefined variable: content
the "content"variable used in my view is apparently not defined. however, when i do var_dump($result); to test the content.. i get:

array(1) { [0]=> array(7) { ["id"]=> string(3) "148" ["description"]=>
  string(9) "33" ["date"]=> string(10) "2015-05-30" ["status"]=>
  string(1) "1" ["Title"]=> string(2) "33" ["notes"]=> string(9) "33"
  ["time"]=> string(8) "07:28:36" } }

MY CONTROLLER:
public function edit_news_form() {

   $this->load->view('edit_news_form');

    $this->load->model('users_model');
    $id = $this->uri->segment(3);
    $result=$this->users_model->get_id($id);
    $data['content']=$result;

   }

   public function edit(){
    $this->load->library('form_validation');
    $this->load->model('users_model');
    $id = $this->uri->segment(3);
    $result=$this->users_model->get_id($id);
    $data['content']=$result;

    $this->db->trans_start();

    $title = $this->input->post('title');
    $notes = $this->input->post('notes');
    $description = $this->input->post('description');
    $date = date('Y-m-d',strtotime($this->input->post('date')));
    $status = 1;
    $time = date('h:i:s',strtotime($this->input->post('time')));

    $data = array(
            'Title' => $title,
            'description' => $description,
            'date'=>$date,
            'time'=>$time,
            'status' => $status,
            'notes' => $notes,
            );
    $this->users_model->update($id,$data);
    $this->db->trans_complete();

   }

}

MY MODEL:
 function get_id($id){
        $this->db->where('id',$id);
        $query = $this->db->get('news');
        return $query->result_array();
    }

function update($id,$data){
    $this->db->where('id', $id);
    $this->db->update('news',$data);
    }

MY VIEW:
     <label>

         <?php echo form_open('resetPasswordController/edit/'.$this->uri->segment(3))?>
        <textarea name="description" rel="815"><?php echo $content[0]['description'];?></textarea>
    </div>
</label>

A:

You have to pass the $data variable in the view method. Take a look at this:
public function edit_news_form()
{
    $this->load->model('users_model');
    $id = $this->uri->segment(3);
    $result=$this->users_model->get_id($id);
    $data['content']=$result;

    $this->load->view('edit_news_form', $data);
}


Q:

Executing git commands inside a build job in Visual Studio Team Services (was VSO)

[Environment: Team Services, GIT, hosted build agent]
I'd like to create a Team Services build definition that is able to do the following:

Executing a script to generate some new files based on existing files in the repo
Commit/push those generated files back to repo

I can do #1 with no problem. But I'm not sure how I can do #2.
I discovered I was actually able to run git.exe from inside a build job. But I'm not sure how I can pass the credential to git. Based on the build logs, it's failing because it's trying to get the username from stdin.
I tried adding a step in the build definition with something like "git config --global user.name xxxx" but it still didn't help.
Is this a supported scenario at all? Any suggestions?
Thanks!

Edit
I tried the following approach in my build script:
git -c http.extraheader="AUTHORIZATION: bearer %SYSTEM_ACCESSTOKEN%" pull ...

It seemed to work for commands like pull, etc. But when I was trying to push the changes, I got the below error:
fatal: unable to access 'https://example.visualstudio.com/SampleTeam/_git/SampleRepo/': SSL read: error:00000000:lib(0):func(0):reason(0), errno 10054

Thoughts?

A:

Sorry to answer my own question here...
I just got some hint from some TFS expert, who pointed me to this article: https://www.visualstudio.com/en-us/docs/build/scripts/git-commands, which perfectly solved my problem.
I think I should share it out to help whoever might run into the same situation as I did.
Here I am quoting the key steps (reformatted a bit):

Grant version control permissions to the build service
Go to the Version Control control panel tab

Team Services: https://{your-account}.visualstudio.com/DefaultCollection/{your-team-project}/_admin/_versioncontrol

On-premises: https://{your-server}:8080/tfs/DefaultCollection/{your-team-project}/_admin/_versioncontrol

On the Version Control tab, select the repository in which you want to run Git commands, and then select Project Collection Build Service (account_name). Grant permissions needed for the Git commands you want to run. Typically you'll want to grant:

Branch creation: Allow
Contribute: Allow
Read: Inherited allow
Tag creation: Inherited allow

When you're done granting the permissions, make sure to click Save changes.
Enable your build definition to run Git.exe

On the variables tab set this variable: system.prefergit = true
On the options tab select Allow scripts to access OAuth token.

With these settings, there is no need to install the Git Build Tools extension or tweak the Credential Manager. You don't need to explicitly set the extra header for OAuth token, either. I feel it's indeed a very neat solution. :)
But really appreciate the help from Eddie and VonC!

A:

Visual Studio Team Services (VSTS) now has built in functionality to do this:

Grant the account Project Collection Build Service (account_name) access to the appropriate repository in VSTS.
In the Agent phase, check the box to Allow scripts to access OAuth token.
Now within the task you can reference the variable SYSTEM_ACCESSTOKEN to access the git repository:
git clone https://randomusername:${SYSTEM_ACCESSTOKEN}@instance.visualstudio.com/proj1/_git/repo

Ref: https://github.com/Microsoft/vsts-tasks/issues/962

A:

You can install Git Build Tools extension and then add "Allow Git remote access" task in your build definition. Make sure "Allow Scripts to Access OAuth Token" feature under "Options" tab is enabled.

Enable Git Remote Access
Certain operations require access to the remote repository from during
  a build. This task updates a remote of the Git repository on the agent
  to allow access to the upstream repository on Visual Studio Team
  Services.
Requirements
For this build task to work it is required that the Allow Scripts to
  Access OAuth Token option is set in the build definition options.
Parameters
Enable Git Remote Access
Remote name: Name of the remote which should be updated. Default is
  origin.
Related Tasks
Restore Git Remote should be called at the end of the build definition
  to restore the remote to its original value.
Known issues
Git-Lfs operations, like git lfs fetch still won't work with this. See
  this Git-Lfs issue

Add the steps for using the powershell script in the extension:

Create a power-shell script with the code in the "EnableGitRemoteAccess.ps1" script and add the script into source control.
Enable the "Allow Scripts to Access OAuth Token" option in the build definition.
Add a PowerShell task in build definition and set the script path the script to enable the git remote access.

Add another PowerShell task in build definition to commit and push the changes.

The code I use to commit and push changes:
git add .
git commit -m "changesinbuild"
git push origin master 2>&1 | Write-Host


Q:

What does $S^z$ mean for each $z\in\mathbb{C}$?

Let $S$ be a set. What does $S^z$ mean for each $z\in\mathbb{C}$?

In Set Theory numbers are sets and for any two sets $A$ and $B$, we define $B^A$ as the set of maps from $A$ to $B$. Well okay, but I don't understand what $S^z$ would mean (if anything) for $z\in\mathbb{C}\setminus\mathbb{N}$, where $0\notin\mathbb{N}$.
My Attempt.
I suppose $S^{0}=\emptyset$ would be a sensible guess.

Let $n\in\mathbb{N}$. Through Category Theory, in $\mathbf{\text{Set}}$ we can see the Cartesian product of $n$ copies of $S$ via cones in terms of commutative diagrams like so: the product is the cone $$\left(\prod_{r=1}^{n}{S}\stackrel{\pi_{i}}{\to} S\right)_{i=1}^n$$ such that for any cone $$\left(X\stackrel{p_{i}}{\to} S\right)_{i=1}^n$$ there exists a unique $u:X\to\prod_{r=1}^{n}{S}$ such that the following diagrams commute:
.
If $z\in \mathbb{R}$ and $z>0$, I suppose we could let $n$ be the integer part $[z]$
 of $z$ in the above and conjure some appropriate $\mathbf{\text{Set}}$-arrow $\pi_{\{z\}}:\prod_{z}{S}\to \bar{S}$ for the fractional part $\{z\}$ of $z$ to get something like
.

I have no idea what $\pi_{\{z\}}:\prod_{z}{S}\to \bar{S}$ should be though.

To illustrate this sketch, if I could order the elements of $S$ with some $<$ to get $S_<$, I suppose I could take the first $\{z\}$ elements of $S_<$. For example, I'd have something like $\{1, 2, 3, 4\}^{2.5}:=\{1, 2, 3, 4\}^2\times\{1, 2\}$ under the natural order.

If the above makes sense, I'd try extending this to $z\in\mathbb{R}$ & $z<0$ using coproducts like so:
.
(I hope you'll forgive me for not defining things in the diagram immediately above.)

I need $S^{-z}\times S^{z}=S^0$.

If we return to Set Theory, I suppose we'd need to specify which construction of $\mathbb{R}$ we're using first to make sense of $S^z$ for $z\in\mathbb{R}$.

I have no idea what to make of $z\in\mathbb{C}\setminus\mathbb{R}$.

Is any of this making sense?

A:

You probably don't want to read this and this is not really an answer, but your idea of defining $S^z$ for complex $z$ just doesn't make any sense. You can draw as many diagrams as you wish, this doesn't matter. Even for $z \in \mathbb{Z}$ there is no way to define $S^z$. The only invertible object in the monoidal category of sets is the one-point set, and of course $1^z=1$ is not really a discovery.


Q:

Oil pressure light on when igntion is off and goes out when key is on and engine is not running

83 Mitsu PU Diesel.  Oil light on drawing .25 amps when key is off.  Key on the light goes out.  All other lights and gauges work as they should.   Light is off when the engine is running. It is killing the battery when parked.  Where would the idiot light get power when the key is off?

A:

OP answered his own question in the comments but is not responding.
Placing the commented answer as THE answer.
OP's Answer

Found the problem. The air cleaner housing is electrically isolated by being mounted on rubber bushings. Pinched beneath it and chaffed is the main alternator wire and the oil pressure wire. They were shorted together. The Alt wire is always hot and when the key is on the idiot light is a balance circuit and is not lit. Go figure!


Q:

Why doesn't $("div[id*='\\|']") work in IE8 or IE9?

Has anyone ever had the experience where IE8 and IE9 won't work with a jQuery selector where a special character is escaped?
This is the div I want to find:

And this is the jQuery selector I'm using to find it: $("div[id*='\\|']")
The result is that it doesn't get found, and I have no idea why. It's such a simple selector, and according to http://api.jquery.com/category/selectors/, using \\ is the proper way to escape the |. This of course works fine in Firefox and Chrome.

A:

The two backslashes were actually unnecessary.


Q:

Cordova always reinstall app when using `run --device` cli

When I using cordova run android --device, Cordova always uninstall app before install the new one. I want "update" my app, not "reinstall" it because that would wipe all the data. How can I do that?
Cordova: 6.0.0
Cordova-android: 5.1.0

A:

Finally found the issue.

Due to the change in CB-9557, the application is ALWAYS uninstalled before being installed.

The solution merged but not in Cordova-android 5.1.0(the last release at this time). So we need update the files in platform/android/cordova/lib/ manually.


Q:

Function of aapt/AndroidManifest.xml in AAR

Some of my Android libraries (AAR files) contain an aapt/AndroidManifest.xml as well as the root AndroidManifest.xml. From what I could see, these two don't differ, but the one in aapt seems to be optional. I couldn't find any documentation about it though.
So what's the purpose of this second manifest? And why is it added only sometimes?

A:

@NonNull
@Override
public File getAaptFriendlyManifestOutputFile() {
    return FileUtils.join(
            globalScope.getIntermediatesDir(),
            "manifests",
            "aapt",
            getVariantConfiguration().getDirName(),
            "AndroidManifest.xml");
}


Q:

Network port not showing after running BasicOTA in ArduinoIDE for ESP8266 on Mac

I've just recently got an NodeMCUv3 ESP8266 and I've been trying to use the Arduino IDE 1.8.8 to program it on my Mac.
I've successfully installed ch340* drivers and I can flash the ESP8266 using USB wire cable.
But after flashing the BasicOTA example (modified to connect to my WiFi), I am not seeing my NodeMCU listed as a network port. I only see a list of Serial ports even after restarting ArduinoIDE and NodeMCU.
I tried Bonjour Browser to discover my NodeMCU device and I cannot see it on the net as well.
Could you please suggest any ideas what could be the problem for appearing the network port for NodeMCU device in the ArduinoIDE?

A:

The problem was solved by adding the line

MDNS.update();

into loop() function.


Q:

Greasemonkey code to put Youtube iFrames in spoiler

On a forum that I'm a member of we have a large number of threads which end up having a lot of Youtube videos embedded on, and quite a lot of people find this quite annoying when scrolling down the page. So, I would like to use Greasemonkey to wrap a spoiler each one so each video can be opened and viewed separately.
Here is code that's used for one video as an example;
<iframe src="http://www.youtube.com/embed/_IATqru7Sh8?wmode=opaque" allowfullscreen="" frameborder="0" height="300" width="500"></iframe>

And I'd like to wrap some code around it so that every video is contained in a Javascript spoiler that has a button to be clicked to show the video.
I've managed to replace simple text with Greasemonkey but this one is a bit complicated for me. Can anyone help me with this please? Thanks!

A:

This is not too hard using the awesome power of jQuery and the waitForKeyElements utility.

Use waitForKeyElements to find iframes with youtube.com in their src. waitForKeyElements is AJAX-aware.
Replace each found <iframe> with a <button>, after marking the iframe as found (using the gmSpoiledAlready class in this case).
The button also stores a copy of the iframe's source code so the the iframe can be recreated.  We don't just hide the iframe, because then it could still load things in the background -- which slows the page down.
Use jQuery's .on() to activate all of the buttons.  When clicked, each button will replace itself with it's original iframe source.

Here's a complete Greasemonkey script:
// ==UserScript==
// @name     _Hide iframed youtube videos
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/
waitForKeyElements ("iframe[src*='youtube.com']", hideYoutubeVideo);

function hideYoutubeVideo (jNode) {
    if ( ! jNode.hasClass ("gmSpoiledAlready") ) {
        jNode.addClass ("gmSpoiledAlready");

        var srcCode     = jNode[0].outerHTML;

        jNode.after ('<button class="gmYT_hide">Show YouTube video</button>');
        jNode.next ('button').data ("frmCode", srcCode);
        jNode.remove ();
    }
}

//--- Activate any and all of the spoiler buttons
$(document.body).on ("click", "button.gmYT_hide", restoreYoutubeVideo)

function restoreYoutubeVideo (evnt) {
    var jThis   = $(evnt.target);
    var frmCode = jThis.data ("frmCode");

    jThis.replaceWith (frmCode);
}


Q:

Jpegoptim caused images to disappear

I finally figured out how to get jpegoptim properly installed on my Centos 6 system and ran the command on a larger folder of images like this
jpegoptim *.jpg --strip-all

Now none of the images appear on my website! They are still in the folder and considerably compressed, but they don't appear to be accessible. I am assuming this must be a permissions issue? Has anybody experienced this?

A:

Okay, I figured this out. For some reason, jpegoptim changes the permissions on the file when you run it. After changing the permissions to 755 (-rwxr-xr-x) using the command chmod -R 755 [containing_folder] the images are now visible again.


Q:

Disable attribute on div will still fire a click event

I have a div that has an icon in it, I add disabled property to the div and the click event still fires. So I went and created a copy of the div and changed the div to a button. Both have click events, yet the button won't fire when clicked on, but the div one will fire. Why is this, and how to I stop the click event firing when I click on the div?
I know that I can check for the disabled attribute during the click event, but wondering why I would have to do that and why the disabled doesn't work on a div

$('#btn').on('click', function() {
  alert("clicked");
});

$('#btn1').on('click', function() {
  alert("clicked");
});
#btn {
  cursor: pointer;
}

#btn[disabled] {
  cursor: not-allowed;
}

#btn1 {
  cursor: pointer;
}

#btn1[disabled] {
  cursor: not-allowed;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<button id="btn1" class="fa fa-undo" disabled>
click
</button>

A:

The disabled attribute does not work on div.
If you insist on not checking for the attribute, you can use the :not() selector.
$('#btn:not(.disabled)').on('click', function() {
  alert("clicked");
});

'#btn:not(.disabled)' looks for elements with id btn and without a disabled class.


Q:

Best practices in assigning permissions to web folders

I would like to know what is the best, correct and recommended way of doing chown and chmod to website files and folders.
I recently started working on linux and I have been doing it in the site root directory like the following:
sudo chown www-data:www-data -R ./
sudo chmod 775 -R ./

I know it is not the best way. There is a protected folder which should not be accessible with browsers and should not be writable, so I did the following to protected folder:
sudo chown root:root -R protected/
sudo chmod 755 -R protected/

Is it correct? If anything can be improved please let me know.

A:

Read your command again. What you are saying is "make everything executable" below these directories. Does an HTML or gif to be executable? I don't think so.
Regarding a directory which should not be writable by the webserver. Think of what you want to do. You want to revoke the right to write a directory from the webserver and the webserver group (and everybody else anyway). So it would translate to chmod -w theDir. What you did is to tell the system "I want root to make changes to that directory which shall be readable by everybody and the root group". I highly doubt that.
So I would suggest having the directory owned by a webserver user with only minimal read access, it should belong to a group (of users, that is) which is allowed to do the necessary of the modification. The webserver does not belong to that group, as you want the outside world to be prevented from making modifications. Another option would be to hand over all the directories to root and to the editor group and modify what the webserver can do via the "others" permission group. But what to use heavily depends on your environment.
Edit:
In general, the "least rights" policy is considered good practice: give away as few rights as possible to get the job done. This means read access to static files and depending on your environment php files, read and execute rights for cgi executables and read and execute rights for directories. Execute rights for directories allow you to enter and read it. No directory in the document root should be writable by the webserver ever. It is a security risk, even though some developers of bigger CMS do not seem to care to much about that. For temporary folders I would set the user and groups to nobody:nogroup and set the sticky bit for both user and groups.


Q:

How do I use ajax to post form data

How can I use ajax to post value from user input to my web service api?
It seems that I can't append value at ajax url.
The following is my code...
 <form action="javascript:Start()">
      <input type="text" id="target" value="tar"/>
      <input type="text" id="profile" value="pro"/>
      <input type="submit" value="Submit">
 </form>

  function Start()
    {
        var target = $('#target').val();
        var profile = $('#profile').val();

        if(validateIdata())
        {
            $.ajax({
              type: 'POST',
              url: "webapi/"+ target + "/" + profile,
              data: $form.serialize(),
              success: function(){
                alert('success');
              }
            });
        }
        return false;
    }

Thanks

A:

You can solve it passing data on URL instead of data field. Try this.
Html. (add id to form in order to access later to its data)
<form id="form" action="javascript:Start()">
      <input type="text" id="target" value="tar"/>
      <input type="text" id="profile" value="pro"/>
      <input type="submit" value="Submit">
</form>

Javascript.
function Start()
    {
        var target = $('#target').val();
        var profile = $('#profile').val();

        if(validateIdata())
        {
            $.ajax({
              type: 'POST',
              url: "webapi/"+ target + "/" + profile?+$('#form').serialize(),
              success: function(){
                alert('success');
              }
            });
        }
        return false;
    }


Q:

Execute a "DESC TABLE" command in Oracle using JavaScript?

I need to find the column info for a number of Oracle views using JavaScript.  What I've tried is:
var conObj = new ActiveXObject('ADODB.Connection');
conObj.Open(conString);
sql = "DESC MyView";
rs1 = new ActiveXObject("ADODB.Recordset");

var commd = new ActiveXObject('ADODB.Command');

commd.ActiveConnection = conObj; //

commd.CommandText = sql;

commd.CommandType = 1;

rs1 = commd.Execute();

What I get is an error about the sql statement.  I know the sql works in SQL Developer.
I can't use the alternative SELECT query as that returns an empty rowset - the view isn't populated when I need to run the query.  Only the DESC returns the values.
Any ideas?

A:

DESC is a SQL*Plus command. SO, you cannot use it via JDBC/ODBC.
An alternative can be like this below.
select RPAD(COLUMN_NAME,30)||' '||DATA_TYPE||'('||DATA_LENGTH||')' as descr
FROM all_tab_cols
  WHERE TABLE_NAME = UPPER('YOUR_TABLE') and owner=UPPER('SCHEMA_NAME');

Oracle's Reference
all_tab_cols is a data dictionary table(view) which contains the table/view metadata.
Example:
SQL> create view MyView as select * from dual where 1=2;

View created.

SQL> select RPAD(COLUMN_NAME,30)||' '||DATA_TYPE||'('||DATA_LENGTH||')' as descr
  2  FROM all_tab_cols
  3   WHERE TABLE_NAME ='MYVIEW'  and owner='MYSCHEMA';

DESCR
------------------------------------------------
DUMMY                          VARCHAR2(1)

Data and DESC
SQL> select * from myview;

no rows selected

SQL> desc myview;

 Name       Null?    Type
 -----------------------------
 DUMMY               VARCHAR2(1)


Q:

Where can I download the Beta release for Ubuntu?

According to the 13.04 release schedule, the Beta 2 release for 13.04 was made available today (April 4). Does anyone know where I can download it? Thanks!

A:

For beta 2:
http://releases.ubuntu.com/13.04/
There are also ISOs for all of the other main distributions (among them Kubuntu and Xubuntu).
A few download links (more on the 13.04 wiki page):
Kubuntu: cdimage.ubuntu.com/kubuntu/releases/raring/beta-2
Lubuntu: cdimage.ubuntu.com/lubuntu/releases/raring/beta-2
Xubuntu: cdimage.ubuntu.com/xubuntu/releases/raring/beta-2

A:

Here is the Ubuntu 13.04 beta 2 : 32-bit
iso : download
torrent : download
Here is the Ubuntu 13.04 beta 2 : 64-bit
iso : download
torrent : download

A:

Here is the Ubuntu (Unity) beta 2 :
http://releases.ubuntu.com/13.04/


Q:

Complete list of sites to @include / @match into my script?

This question aims to serve as a reference list of all current Stack Exchange sites for use in scripts.

A:

You don't need to support alias domains.  They redirect to *.stackexchange.com domains, anyway.
This will match all current Stack Exchange sites.  It uses @match for smarter domain and path wildcards.  @match also works better for Chrome:
// @match       *://*.askubuntu.com/*
// @match       *://*.mathoverflow.net/*
// @match       *://*.serverfault.com/*
// @match       *://*.stackapps.com/*
// @match       *://*.stackexchange.com/*
// @match       *://*.stackoverflow.com/*
// @match       *://*.superuser.com/*

Although, for slightly better speed and to help avoid unexpected results, you should also exclude some sites (Namely: The API, the main blogs1, SEDE, and the "all sites" pages) unless you are specifically coding for them. Their structure and purpose is markedly different.
So use:
// @match       *://*.askubuntu.com/*
// @match       *://*.mathoverflow.net/*
// @match       *://*.serverfault.com/*
// @match       *://*.stackapps.com/*
// @match       *://*.stackexchange.com/*
// @match       *://*.stackoverflow.com/*
// @match       *://*.superuser.com/*
// @exclude     *://api.stackexchange.com/*
// @exclude     *://blog.*.com/*
// @exclude     *://chat.*.com/*
// @exclude     *://data.stackexchange.com/*
// @exclude     *://elections.stackexchange.com/*
// @exclude     *://openid.stackexchange.com/*
// @exclude     *://stackexchange.com/*

As a practical start for most scripts.

Note that onstartups no longer needs to be supported.
1 The "not so main" blogs are all/mostly on a separate domain: blogoverflow.com.


Q:

h2o server fails when I start a grid search

I'm doing a grid search on a classification model.  When the h20 server starts I get:
R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)

When my model enters the grid search, I get the following error message:
ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"

My R script is as follows:
rm(list=ls())
options(scipen=999) # remove E notation
ptm <- proc.time()

if (Sys.info()["sysname"] == "Windows") {
  filePath = "//bigsur/sm/Trending/model.csv"
  homedir = "c:/sm/Trending/"
  setwd("c:/sm/Trending/R")
  sink("C:/Users/Charles/Desktop/log.txt")
} else {
  filePath = "/Volumes/sm/Trending/model.csv"
  homedir = "/Volumes/sm/Trending/"
  setwd("/Volumes/sm/Trending/R")
  sink("~/Desktop/log.txt")
}

#install.packages("ggplot2")
#install.packages("dplyr")

sink.reset <- function(){
  for(i in seq_len(sink.number())){
    sink(NULL)
  }
}

printf <- function(...) print(sprintf(...))

results = function(title, best_model) {
  best_params = best_model@parameters
  best_activation            <<- best_model@parameters$activation
  best_hidden                <<- best_model@parameters$hidden
  best_l1                    <<- best_model@parameters$l1
  best_l2                    <<- best_model@parameters$l2
  best_input_dropout_ratio   <<- best_model@parameters$input_dropout_ratio
  best_hidden_dropout_ratios <<- best_model@parameters$hidden_dropout_ratios

  printf(" ")
  printf("%s", title)
  best_model
  plot(best_model)
  h2o.performance(best_model)
  h2o.performance(best_model, valid = TRUE)
  h2o.mse(best_model, valid = TRUE)

  printf("mse: %f", best_model@model$validation_metrics@metrics$MSE)
  printf("best activation: %s", best_activation)
  cat("best hidden layers: ", best_hidden, "\n")
  printf("Best l1: %f", best_l1)
  printf("Best l2: %f", best_l2)
  #printf("best_input_dropout_ratio: %f", best_input_dropout_ratio)
  #cat("Best best_hidden_dropout_ratios: ", best_hidden_dropout_ratios, "\n")

  predictions = h2o.predict(best_model, test)
  summary(predictions, exact_quantiles=TRUE)
  predicted = predictions[,1]
  test_targets = test[, 5]
  correct = predicted == test_targets
  numCorrect = as.integer(sum(correct))
  ntotal = as.integer(nrow(correct))
  percent = round(numCorrect/ntotal*100, 2)
  printf("Correct classifications on all data: %d/%d (%f)", numCorrect, ntotal, percent)

  #predicted.h2o = h2o.assign(predicted, key = "predicted.h2o")
  #correct.h2o = h2o.assign(correct, key = "correct.h2o")

  perf_test = h2o.performance(model = best_model, newdata = test)
  cat("\nPerformance on test dataset\n")
  print(perf_test)
  cat("\nConfusion matrix on test dataset\n")
  h2o.confusionMatrix(perf_test)

  # Plot Receiver Operating Characteristic (ROC) curve and find its Area Under the Curve (AUC)
  # A ROC curve is a graph of the true positive rate (recall) against the false positive
  # rate for a binary classifier.
  #plot(f1_best_model, type = "cutoffs", col = "blue")

  cm = h2o.confusionMatrix(best_model, train)
  print("Confusion Matrix: ")
  print(cm)
  true_negative = cm[1,1]
  true_positive = cm[2,2]
  false_negative = cm[2,1]
  false_positive = cm[1,2]
  total = true_negative + true_positive + false_negative + false_positive
  accuracy = (true_positive + true_negative)/total
  printf("accuracy: %f", accuracy)

  misclassification_rate = (false_positive + false_negative)/total
  printf("misclassification_rate: %f", misclassification_rate)

  cat("\nVariable importance\n")
  print(best_model@model$variable_importance)

  return_list = c(best_activation,
                  best_hidden,
                  best_l1,
                  best_l2,
                  best_input_dropout_ratio,
                  best_hidden_dropout_ratios)

  return (return_list)
}

library(h2o)
library(dplyr)
library(data.table)
library(ggplot2)

localH2O = h2o.init(ip = "localhost",
                    port = 54321,
                    startH2O = TRUE,
                    max_mem_size="24G",
                    nthreads = -1)
h2o.no_progress()
h2o.removeAll() ## clean slate - just in case the cluster was already running

print(filePath)
model.full <- read.csv(filePath, header = TRUE, sep = ",")
head(model.full)
remove = !colnames(model.full) %in% c("Date",
                                      "Symbol",
                                      "BuyIndex",
                                      "SellIndex",
                                      "BoxRatio",
                                      "Acceleration",
                                      "nPosVelo",
                                      "Gain")
model_orig = model.full[, remove]
head(model_orig)
model = model_orig[sample(nrow(model_orig)),] # shuffle the rows
head(model)

df <- as.h2o(model, destination_frame = "df")

splits <- h2o.splitFrame(df, c(0.6,0.2), seed=1234)
train  <- h2o.assign(splits[[1]], "train.hex") # 60%
valid  <- h2o.assign(splits[[2]], "valid.hex") # 20%
test   <- h2o.assign(splits[[3]], "test.hex")  # 20%

printf("train----------------------------------------")
head(train)
train
printf("valid----------------------------------------")
#head(valid)
valid
printf("test-----------------------------------------")
#head(test)
test

p1 = train$Thrust
p2 = train$Velocity
p3 = train$OnBalRun
p4 = train$vwapGain
p1d = rbind(lapply(p1, as.double))  # p1 is an environment variable, we need doubles
p2d = rbind(lapply(p2, as.double))
p3d = rbind(lapply(p3, as.double))
p4d = rbind(lapply(p4, as.double))
a = unlist(p1d)
b = unlist(p2d)
c = unlist(p3d)
d = unlist(p4d)

pairs(train[1:4], main = "Scatterplot of predictors", pch = 21, cex = 0.8, bg = c("green3", "red")[unclass(model$Altitude)])

cat("\n\n1. Summary of train dataset------------------------------------------------------\n")
summary(train, exact_quantiles=TRUE)

cat("\n\n2. Grid Search on valid data ----------------------------------------------------\n")

activation_opts = c("RectifierWithDropout","TanhWithDropout","MaxoutWithDropout")
hidden_opts = list(c(80),c(100),c(200),c(300),c(400),c(500),
                   c(80,80),c(100,100),c(200,200),c(300,300),c(400,400),c(500,500),
                   c(80,80,80,80),c(100,100,100,100),c(200,200,200,200),c(300,300,300,300),
                   c(80,80,80,80,80),c(100,100,100,100,100),c(200,200,200,200,200),
                   c(300,300,300,300,300),c(400,400,400,400,400),c(500,500,500,500,500),
                   c(80,80,80,80,80,80),c(100,100,100,100,100,100),c(200,200,200,200,200,200),
                   c(300,300,300,300,300,300),c(400,400,400,400,400,400),
                   c(500,500,500,500,500,500)
                   )
l1_opts = runif(1, 0, 0.0001)
l2_opts = runif(1, 0, 0.0001)

hyperparams = list(
  activation = activation_opts,
  hidden = hidden_opts,
  l1 = l1_opts,
  l2 = l2_opts,
  max_w2 = 10
)

search_criteria = list(strategy = "RandomDiscrete",
                       stopping_metric = "misclassification",
                       max_models = 10000,
                       max_runtime_secs = 72000,
                       stopping_tolerance = 0.00001,
                       stopping_rounds = 10)

grid_model = h2o.grid(algorithm = "deeplearning",
                      grid_id = "mygrid",
                      hyper_params = hyperparams,
                      search_criteria = search_criteria,
                      x = 1:4,
                      y = 5,
                      training_frame = train,
                      validation_frame = valid,
                      variable_importances = TRUE,
                      balance_classes=TRUE,
                      score_training_samples=1000,
                      score_validation_samples=1000,
                      score_validation_sampling="Stratified",
                      epochs = 1000000,
                      seed = 7)

cat("\n\n3. Summary of grid_model---------------------------------------------------------\n")
grid = h2o.getGrid("mygrid", sort_by="auc", decreasing=TRUE)
summary(grid)

cat("\n\n4. Performance of best_model-----------------------------------------------------\n")
best_model = h2o.getModel(grid@model_ids[[1]])

results("5.best_model", best_model)

cat("\n\n6. Performance valid dataset-----------------------------------------------------\n")
perf_valid = h2o.performance(model = best_model, newdata = valid)
perf_valid

cat("\n\n7. Performance on test dataset---------------------------------------------------\n")
perf_test = h2o.performance(model = best_model, newdata = test)
perf_test

plot(perf_test, type="roc")     # Plot the roc curve

predicted <- h2o.predict( best_model, test )
actual = test[,5]
cat("\n\n8. Mean prediction on the test set: ", 100*mean( predicted$predict == actual ), "%\n")
correct = predicted == actual
numCorrect = as.integer(sum(correct))
ntotal = as.integer(nrow(correct))
percent = round(numCorrect/ntotal*100, 2)
printf("9. Test of Mean prediction on the test set: %d/%d (%f)", numCorrect, ntotal, percent)
cat("\n\n10. The 'test' set auc is: ", h2o.auc(perf_test), "\n")

p = h2o.saveModel(best_model, path = "C:\\sm\\Trending\\h2o_model", force = TRUE)
p

minutes = (proc.time() - ptm)[1]
printf("Elapsed time: %.2f minutes", minutes)

unlink("log.txt")
sink.reset()

My log is:
 Connection successful!

R is connected to the H2O cluster:
    H2O cluster uptime:         9 minutes 35 seconds
    H2O cluster version:        3.10.4.8
    H2O cluster version age:    14 days, 4 hours and 1 minute
    H2O cluster name:           H2O_started_from_R_Charles_huu844
    H2O cluster total nodes:    1
    H2O cluster total memory:   21.31 GB
    H2O cluster total cores:    8
    H2O cluster allowed cores:  8
    H2O cluster healthy:        TRUE
    H2O Connection ip:          localhost
    H2O Connection port:        54321
    H2O Connection proxy:       NA
    H2O Internal Security:      FALSE
    R Version:                  R version 3.2.2 (2015-08-14)

[1] 0
[1] "//bigsur/sm/Trending/model.csv"
        Date Symbol BuyIndex SellIndex BoxRatio  Thrust Acceleration Velocity nPosVelo
1   4/5/2017 GBX         132       199   77.724 49.7190     107.5811   2.9236       59
2   1/5/2017 RH          216       259    4.838  4.8380     137.0574   0.3381       14
3  9/28/2016 DDS         149       444    0.150  0.4860      99.1360   0.1081       59
4 11/25/2016 JKS         132       186    0.932  0.8686      38.9931   0.6057       59
5 12/12/2016 JNUG        132       177    0.582  0.3242      87.1144   1.1274       18
6   3/7/2017 LPL         134       180    8.954  8.9540      34.1691   0.4778       59
  OnBalRun vwapGain    Gain Altitude
1  12.6378  90.0656 -0.1659       no
2   1.5157   0.9495 -0.6496       no
3   0.5476   2.2887  4.1439      yes
4   3.2719   3.8235  0.5051       no
5   2.5006  12.0472 -0.8942       no
6   2.9935   1.1234 -0.1617       no
   Thrust Velocity OnBalRun vwapGain Altitude
1 49.7190   2.9236  12.6378  90.0656       no
2  4.8380   0.3381   1.5157   0.9495       no
3  0.4860   0.1081   0.5476   2.2887      yes
4  0.8686   0.6057   3.2719   3.8235       no
5  0.3242   1.1274   2.5006  12.0472       no
6  8.9540   0.4778   2.9935   1.1234       no
     Thrust Velocity OnBalRun vwapGain Altitude
4427 0.9370   0.3176   1.2786   2.3151       no
3079 2.2060   0.9261   1.1257   1.2506       no
3952 0.0702   0.4430   1.1485   0.9928       no
7765 1.1596   1.1067   6.2563   2.1164      yes
1682 0.6708   0.4519   1.3848   2.1808       no
5145 4.5600   0.3462   1.7386   0.7722       no
[1] "train----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no
  Thrust Velocity OnBalRun vwapGain Altitude
1 2.2060   0.9261   1.1257   1.2506       no
2 0.6708   0.4519   1.3848   2.1808       no
3 4.5600   0.3462   1.7386   0.7722       no
4 3.6930   3.2778  11.4092  49.3335       no
5 0.9980   0.4035   1.6667   1.1264       no
6 0.2016   0.5627   2.4101   1.2642       no

[5548 rows x 5 columns]
[1] "valid----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 0.9370   0.3176   1.2786   2.3151       no
2 0.0702   0.4430   1.1485   0.9928       no
3 1.0230   0.3119   3.0922   0.8788       no
4 6.4100   0.9966   5.3490   2.9436      yes
5 6.9620   0.7004   3.5810   4.8905       no
6 1.6800   1.4518   5.1933   1.7955       no

[1875 rows x 5 columns]
[1] "test-----------------------------------------"
  Thrust Velocity OnBalRun vwapGain Altitude
1 1.1596   1.1067   6.2563   2.1164      yes
2 4.7010   0.5369   1.1266   7.5566       no
3 1.7110   0.9247   3.5819   3.0598       no
4 1.4620   0.3315   4.3097   0.4129       no
5 0.5610   0.4494   1.8738   1.3942       no
6 6.7255   1.7309   5.6268   4.4937      yes

[1823 rows x 5 columns]

1. Summary of train dataset------------------------------------------------------
 Thrust               Velocity          OnBalRun           vwapGain           Altitude
 Min.   :   -1.4845   Min.   :-0.1241   Min.   : -0.5299   Min.   : -4.7648    no :4875
 1st Qu.:    0.3984   1st Qu.: 0.3281   1st Qu.:  1.1468   1st Qu.:  0.8684    yes: 671
 Median :    1.0425   Median : 0.3815   Median :  1.6439   Median :  1.9954       :   2
 Mean   :   12.1332   Mean   : 0.5913   Mean   :  2.5911   Mean   :  4.8876
 3rd Qu.:    1.9723   3rd Qu.: 0.5716   3rd Qu.:  2.6507   3rd Qu.:  4.7500
 Max.   :41279.8960   Max.   :29.4449   Max.   :154.5988   Max.   :314.7143
 NA's   :2            NA's   :2         NA's   :2          NA's   :2

2. Grid Search on valid data ----------------------------------------------------

3. Summary of grid_model---------------------------------------------------------

ERROR: Unexpected HTTP Status code: 412 Precondition Failed (url = http://localhost:54321/99/Grids/mygrid?sort_by=auc&decreasing=TRUE)

water.exceptions.H2OIllegalArgumentException
 [1] "water.exceptions.H2OIllegalArgumentException: Invalid argument for sort_by specified. Must be one of: [r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error]"
 [2] "    hex.schemas.GridSchemaV99.fillFromImpl(GridSchemaV99.java:114)"
 [3] "    water.api.GridsHandler.fetch(GridsHandler.java:41)"
 [4] "    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)"
 [5] "    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)"
 [6] "    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)"
 [7] "    java.lang.reflect.Method.invoke(Method.java:498)"
 [8] "    water.api.Handler.handle(Handler.java:61)"
 [9] "    water.api.RequestServer.serve(RequestServer.java:436)"
[10] "    water.api.RequestServer.doGeneric(RequestServer.java:285)"
[11] "    water.api.RequestServer.doGet(RequestServer.java:220)"
[12] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:735)"
[13] "    javax.servlet.http.HttpServlet.service(HttpServlet.java:848)"
[14] "    org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)"
[15] "    org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)"
[16] "    org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)"
[17] "    org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:429)"
[18] "    org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)"
[19] "    org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)"
[20] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[21] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[22] "    water.JettyHTTPD$LoginHandler.handle(JettyHTTPD.java:417)"
[23] "    org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:154)"
[24] "    org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)"
[25] "    org.eclipse.jetty.server.Server.handle(Server.java:370)"
[26] "    org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:494)"
[27] "    org.eclipse.jetty.server.BlockingHttpConnection.handleRequest(BlockingHttpConnection.java:53)"
[28] "    org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:971)"
[29] "    org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:1033)"
[30] "    org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:644)"
[31] "    org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:235)"
[32] "    org.eclipse.jetty.server.BlockingHttpConnection.handle(BlockingHttpConnection.java:72)"
[33] "    org.eclipse.jetty.server.bio.SocketConnector$ConnectorEndPoint.run(SocketConnector.java:264)"
[34] "    org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)"
[35] "    org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)"
[36] "    java.lang.Thread.run(Thread.java:745)"

4. Performance of best_model-----------------------------------------------------

6. Performance valid dataset-----------------------------------------------------

7. Performance on test dataset---------------------------------------------------
Called from: sprintf(...)
[1] "Elapsed time: 85.98 minutes"

Please help.
Charles

A:

AUC is a metric for classification, you're creating a ~regression~ model from what I see therefore you cannot use auc in grid = h2o.getGrid("mygrid", sort_by="auc", decreasing=TRUE). Instead use, as the error message suggests, one of the following metrics: r2, mean_per_class_accuracy, max_per_class_error, err, total_rows, rmse, accuracy, err_count, logloss, mse, mean_per_class_error.


Q:

Send message to Telegram contact or list of contacts using API

I have a Telegram account and Now I wants to import list of contacts into my Account using Telegram API.
Is This possible to send Message to my imported contacts using Telegram API, just like normal user can send message to other user in his contacts list?
I tried Telegram bots but Telegram bot can't send message to other users, unless they started any chat with Bot. So this is not that useful.

A:

You can act as a normal user by using the Telegram MTProto API. There are many libraries that interact with that, like Python telethon or PHP MadelineProto.


Q:

Bedeutung von "soziale Einbettung"

Mit dem Begriff "alleinerziehend" werde fälschlicherweise oft mangelnde soziale Einbettung oder Erziehungsqualität assoziiert.

Was bedeutet der Ausdruck "soziale Einbettung"?

A:

Das Konzept der sozialen Einbettung zählt mittlerweile zum festen Bestandteil der Soziologie.
Soziale Einbindung (Einbettung) ist das Ausmaß, mit dem Menschen in Kontakt zu anderen Personen stehen, entweder zu privaten Freunden oder zu Kollegen am Arbeitsplatz.
Diese Einbindung (Einbettung) wird von einem selbst stärker wahrgenommen, wenn man zur jeweiligen Gruppe gut passt.
Eine gute soziale Einbindung schütz vor Stress, weil man andere um Hilfe bitten kann und etwa so seine Arbeit so schneller erledigen kann.
Mehr (notwendige) Kontakte mit vielen Personen kann aber auch mehr sozialen Stress bedeuten.


Q:

loop for tuple of list on python

I have tuple of lists. The lengths of the lists are same each other. For example:
tol = ([1,2,3], [4,5,6])

I'd like to loop all pair of two lists like:
for v1, v2 in some_operation(tol):
    print "(%f, %f)" % (v1, v2)

The above code should print (1,4)\n(2,5)\n(3,6)\n.
One (little dirty) way is use zip
for v1, v2 in zip(tol[0], tol[1]):
    print...

Could you show me more simple way?

A:

Using Zip would be simple and clean
tol = ([1,2,3], [4,5,6])

for v1, v2 in zip(*tol):
    print "(%d, %d)" % (v1, v2)

As you expect the output would be (1,4)\n(2,5)\n(3,6)\n.


Q:

understanding Jasper Reports and Hibernate and parameters

I'm sorry this is a little bit of a bad question since my problem is that I just don't understand which approach to take for this.  I've got this hibernate database that works great and I want to use JasperReports to create reports based on the data from it.  I have iReport working and connecting to the hibernate configuration and able to read fields from my queries and build a report.
However, I want to be able to have saved reports run from my application, and on certain objects, decided at runtime.  I need to be able to pass my custom persistent objects to these reports at runtime and generate reports that way.  so really they don't need a query themselves, they just need to know what kind of objects that they're going to get.
I see that I can give them parameters, but only raw objects, and also in iReport I can only make fields out of simple data types, but most of my values are rendered in the toString() of my objects so I'd like to just return those.
I would be incredibly appreciative if someone would explain some of these things to me.  Thank you so much!
Joshua

A:

I think you may need to look in
http://jasperreports.sourceforge.net/api/net/sf/jasperreports/engine/data/JRBeanCollectionDataSource.html
this is a data source collection of beans so that you can u load custom beans into the report as a datasource


Q:

DataNucleus - Plugins , L2 cache error

my project is based on GWT(2.4) and my aim is to implement ReqyestFactory (JPA, Datanucleus, Postgresql). The last problem which I have is with Level 2 cache.
I want to use EHcache but when I create my EMF I got this error :
Level 2 Cache "ehcache" is registered to use class "org.datanucleus.cache.ehcache.EhcacheLevel2Cache" yet this is not found. Please check your CLASSPATH and plugin specification.

in my /war/WEB-INF/lib I have :
datanucleus-api-jpa-3.2.0-m2.jar
datanucleus-cache-3.1.1.jar
datanucleus-core-3.2.0-m2.jar
datanucleus-rdbms-3.2.0-m2.jar
ehcache-core-2.2.0.jar
geronimo-jpa_2.0_spec-1.1.jar
geronimo-jta_1.1_spec-1.1.jar
gwt-servlet-deps.jar
gwt-servlet.jar
hibernate-validator-4.3.1.Final.jar
jboss-logging-3.1.0.GA.jar
jdo-api-3.0.1.jar
log4j-1.2.17.jar
postgresql-9.2-1002.jdbc4.jar
requestfactory-apt.jar
requestfactory-client+src.jar
requestfactory-server+src.jar
validation-api-1.0.0.GA.jar
validation-api-1.0.0.GA-sources.jar

persistence.xml
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">

<persistence-unit name="DBStorage">
    <provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
    <class>com.test.domain.Myobj</class>
    <exclude-unlisted-classes/>
    <properties>
        <property name="datanucleus.ConnectionDriverName" value="org.postgresql.Driver" />
        <property name="datanucleus.ConnectionURL" value="jdbc:postgresql://localhost:5432/test" />
        <property name="datanucleus.ConnectionUserName" value="test" />
        <property name="datanucleus.ConnectionPassword" value="123" />
        <property name="datanucleus.autoCreateTables" value="true" />
        <property name="datanucleus.identifier.case" value="LowerCase" />
        <property name="datanucleus.jmxType" value="default" />

        <property name="datanucleus.cache.level2.type" value="ehcache" />
        <property name="datanucleus.cache.level2.cacheName" value="TestEHcache" />
        <!--  property name="datanucleus.cache.level2.configurationFile" value="ehcache.xml" / -->

    </properties>
</persistence-unit>

What I have missed ? Where is my problem ?

A:

I solved the problem by adding :
slf4j-api-1.5.6.jar
slf4j-log4j12-1.5.6.jar

Now it works great.


Q:

DynamoDB: How to use a query filter to check for conditions in a MAP

I have a table and the structure looks like this:

When I do a query, I would like to be able to do a query filter on the data map; but I'm not exactly sure how to setup the query.
This is what I have so far:
HashMap<String, AttributeValue> map = new HashMap<String, AttributeValue>();
map.put("byUserId", new AttributeValue().withS("vl49uga5ljjcoln65rcaspmg8u"));

queryExpression
    .withQueryFilterEntry("data", new Condition()
        .withAttributeValueList(new AttributeValue().withM(map))
        .withComparisonOperator(ComparisonOperator.CONTAINS));

but the way I'm building the filter is not correct and I keep running into the following error:
Exception in thread "main" com.amazonaws.AmazonServiceException: One or more parameter values were invalid: ComparisonOperator CONTAINS is not valid for M AttributeValue type (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: CHIOME68L1HVGO81URD7CIOS6BVV4KQNSO5AEMVJF66Q9ASUAAJG)
    at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1077)
    at com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:725)
    at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:460)
    at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:295)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:3106)
    at com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient.query(AmazonDynamoDBClient.java:1118)

So what is a comparison operator I should be using (since IN is for list types), and how do I build the query filter such that I can specify a comparison inside of the MAP.
Thanks!

A:

Try comparing the map attribute data.byUserId instead of the entire map structure:
Table table = dynamoDB.getTable(tableName);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":x", "vl49uga5ljjcoln65rcaspmg8u");

QuerySpec spec = new QuerySpec()
    .withHashKey("HashKeyAttribute", "HashKeyAttributeValue")
    .withFilterExpression("data.byUserId = :x")
    .withValueMap(expressionAttributeValues);

ItemCollection<QueryOutcome> items = table.query(spec);

Iterator<Item> iterator = items.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}

Some important guidelines:

Make sure the variable tableName has the correct table name represented as a string.
Make sure to replace the string HashKeyAttribute with the attribute name that represents your Hash Key.
Make sure to replace the string HashKeyAttributeValue with the value that represents the Hash Key that you want to match.
Make sure the matched record has the data.byUserId with the value provided in the comparison expression. In the example the value "vl49uga5ljjcoln65rcaspmg8u" was provided.

Here is another example having the id attribute as the Hash Key:
Table table = dynamoDB.getTable(tableName);

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":x", "vl49uga5ljjcoln65rcaspmg8u");

QuerySpec spec = new QuerySpec()
    .withHashKey("id", "25g77vmummpr4mc5mb9vq36q43")
    .withFilterExpression("data.byUserId = :x")
    .withValueMap(expressionAttributeValues);

ItemCollection<QueryOutcome> items = table.query(spec);

Iterator<Item> iterator = items.iterator();

while (iterator.hasNext()) {
    System.out.println(iterator.next().toJSONPretty());
}


Q:

No Error for Undefined Variable Used in Class Methods in PHP

I spent more than 10 hours to find out the typo for debugging my PHP program. I expected PHP would produce an error when using an undefined variable. But when it is used as an object in a method, it doesn't. Is there a reason for it?
<?php

    $oClass = new MyClass;
    // $oCless->tihs('key', 'taht');    //<-- triggers the error: Notice: Undefined variable
    $oClass->tihs('key', 'taht');
    echo $oClass->arr['key'];

    class MyClass {
        public $arr = array('key' => 'foo');

        function tihs($key, $value) {
            $tihs->arr[$key] = $value;  //<-- this does not cause an error message.
        }
    }
?>

A:

Normally if the error reporting level is set to E_ALL | E_STRICT (or E_ALL as of PHP 5.4.0) it should spit out an E_STRICT error. For instance, this code:
error_reporting(E_ALL | E_STRICT);
$tihs->adrr = 453;

Produces:
Strict Standards: Creating default object from empty value in [...]

Interestingly enough, if you specifically create an array instead of an ordinary variable as a property of an object that doesn't exist, e.g.:
error_reporting(E_ALL | E_STRICT);
$tihs->adrr[25] = 453;

No strict standards error is shown! It looks like this could potentially be something PHP folks might want to fix, because I'm not aware this is documented nor I think there's a legitimate reason for this behaviour.
For the record, in both cases regardless of the error a new stdClass is being created on the fly instead, like sberry mentions in his answer.


Q:

Oracle - correlated subquery problems

I have this query:
select acc_num
from (select distinct ac_outer.acc_num, ac_outer.owner
       from ac_tab ac_outer
       where (ac_outer.owner = '1234567')
             and ac_outer.owner = (select sq.owner
                                      from (select a1.owner
                                             from ac_tab a1
                                             where a1.acc_num = ac_outer.acc_num /*This is the line that gives me problems.*/
                                             order by a1.a_date desc, a1.b_date desc, a1.c_date desc) sq
                                      where rownum = 1)
       order by dbms_random.value()) subq
order by acc_num;

The idea is to get all acc_nums (not a primary key) from ac_tab, that have an owner of 1234567.
Since an acc_num in ac_tab could have changed owners over time, I am trying to use the inner correlated subqueries to ensure that an acc_num is returned ONLY if it's most recent owner is 12345678. Naturally, it doesn't work (or I wouldn't be posting here ;) )
Oracle gives me an error: ORA-000904 ac_outer.acc_num is an invalid identifier.
I thought that ac_outer should be visible to the correlated subqueries, but for some reason it's not. Is there a way to fix the query, or do I have to resort to PL/SQL to solve this?
(Oracle verison is 10g)

A:

I'm not sure why Peter is using a Min(owner) analytic function instead of first_value(owner).  I believe the latter gives you what you need while the min(owner) is giving you the "minimum" owner.  Everything else in the query I agree with:
Select Distinct acc_num
From (
      Select
            acc_num,
            owner,
            first_value(owner) Over ( Partition By acc_num
                  Order By a_date Desc, b_date Desc, c_date Desc
                ) recent_owner
      From ac_tab
     )
Where owner = '1234567'
      And owner = recent_owner
Order By acc_num;

A:

I don't see what you need the dbms_random.value() for, but the following query using analytic functions should give you the expected result:
Select Distinct acc_num
From (
  Select
    acc_num,
    owner,
    First_Value(owner) Over ( Partition By acc_num
                              Order By a_date Desc, b_date Desc, c_date Desc
                            ) recent_owner
  From ac_tab
)
Where owner = '1234567'
  And owner = recent_owner
Order By acc_num;

The sub-query gives you the owner and the most recent owner per acc_num, which can then be compared in the outer query.


Q:

Create template class in C++ method?

How can I do the following, without having to include every class T in this file?:
// ComponentMan.h
class ComponentMan
{
public:
    template<class T>
    void CreateComponent<T>()
    {
        T* temp = new T();
    }
}

Basically, I want a generic class instantiater. How can I achieve this without including headers everywhere?

A:

You do it the other way round; you include "ComponentMan.h" everywhere you want to use it.  e.g.:
foo.h
class Foo {
    ...
};

blah.cpp
#include "foo.h"
#include "ComponentMan.h"

void bar() {
    ComponentMan man;
    man.CreateComponent<Foo>();
}


Q:

using defaultdict in a array in python 2.7

I'm trying to create a dictionary where the same key can have different values from an array. In the past i created a dictionary with positions on each list of the list, but I found a bug where the same key can have more than one value and it's breaking the main code.
ie.
my_array = [['a','b','c'],['a','e','d'],['f','g','h']]
my dict = dict([p[0], p[2]] for p in my_array)
my dict = {'a': 'c', 'f': 'h'}
What I need is:
my_dict = {'a': ['c','d'], 'f': 'h'}

I have tried with defaultdict but so far I'm getting TypeError Exception. I have tried initializing it as a string defaultdict(str) and a list defaultdict(list) with no success
my_dict = defaultdict((my_dict[p[0]].append(p[2])) for p in my_array)
or
my_dict = defaultdict(([p[0], p[2]]).append(p[2]) for p in a_array)

Always getting TypeError exception, suggestions please?

A:

You can't do this with a comprehension/generator expression. Instead, try this:
my_dict = {}
for p in my_array:
    my_dict.setdefault(p[0], []).append(p[2])

You can also do it with a defaultdict if you insist, but it seems like overkill:
my_dict = collections.defaultdict(list)
for p in my_array:
    my_dict[p[0]].append(p[2])

All your values will now be lists, even if they contain only a single item, which doesn't appear to be what you want based on your question. It probably actually is, as it's much easier to deal with values that are always the same type. But if you do want the single values outside of lists, I think the most straightforward way is to post-process after building the dictionary and convert single-item lists back to single values:
for k, v in my_dict.iteritems():  # n.b. just .items() in Python 3
    if len(v) == 1:
        my_dict[k] = v[0]

Otherwise, you end up having to check the type of each value already in the dictionary when you're adding a new one, and convert the value to a list when you go to add the second one.


Q:

Windows Phone 7 Browser Helper Objects?

Are Windows Phone 7 BHOs possible? I have a BHO for Windows Mobile that I'd like to port to Windows Phone 7.

A:

I didn't know that Windows Mobile supported BHO but I am pretty sure that Windows Phone does not support BHOs as they require the IWebBrowser2 interface and COM interop, neither of which are supported on Windows Phone. All apps in Windows Phone are built in managed code using the Silverlight runtime. You do have access to a WebBrowser control, which allows you to display simple HTML/CSS/Javascript content, but does not allow you to include plugins or extensions.


Q:

When setting up a new laptop, Setup Assistant doesn't see all the data

I'm trying to set up a new Retina MacBook Pro, which is running OS X 10.10, by transferring data from my old MacBook, which is running OS X 10.8.6, via Thunderbolt.  My old laptop is in Target Disk Mode instead of using Migration Assistant due to the OS mismatch (the new machine wouldn't let me migrate with Migration Assistant).  As far as I can tell, this all matches what Apple says should work.  However, I have ~350 GB in my home folder, and my new laptop can only see ~50 GB.  What's going on, and is there any way to fix it?
A few things:

I tried copying my data once already, but almost nothing got copied (I think even less than the ~50 GB).
I can't update my OS on my old laptop, because I don't have enough space.
I could try restoring from a Time Machine backup – it seems to see everything that way – but I don't have the right cables, so (until I can get those) I'm looking for a laptop-to-laptop solution over Thunderbolt.  (I have too much data to use Wi-Fi.)

A:

While preparing for one last Time Machine backup, I found myself restarting both my old and my new laptop – and some combination of these things fixed the problem.  I was able to restore from my old laptop overnight, and this answer is being posted from my new machine.  If anybody has any further insight, I'd welcome it, but my problem is solved!


Q:

How to provide two values in query string in LzBrowser.loadURL in openlaszlo

How can i pass two values in a query string using LzBrowser.loadURL() in openlaszlo.
My sample code:
LzBrowser.loadURL("../modules/Index.jsp?base="+ canvas.base +" id=" + canvas.Id,"fraMain");

I am getting number Format exception:
java.lang.NumberFormatException: For input string: "1 base=1"]
Please help in solving this.
Thanks,
Raj

A:

We have to provide & amp; instead of &. It worked for me.


Q:

Resizing UITableView on RootController

Is it possible to resize the UITableView on the RootController of a nav based app?  When RootViewController.xib is opened in IB, there isn't a view.  Just the UITableView.  Clicking the inspector and then the little yellow ruler, frame height is grayed out.  I'm adding a toolbar programmatically to the RootViewController:
[toolbar setFrame:rectArea];

That works fine but the bottom cell in the tableview is partially hidden because the tableview doesn't know about the toolbar.

A:

The easiest way, is to adjust the contentInset (which is inherited from UIScrollView). Resizing by setting the frame can cause crazy drawing bugs in cells.
For example, if you are trying to resize a tableview for the keyboard, do something like this:
tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 216.0, 0.0);
tableView.scrollIndicatorInsets = tableView.contentInset;

Hope that helps someone. This way worked best for me.

A:

Yes, but you need to have a ViewController (not a UITableViewController) as the root controller for the nav, and wrap the actual UITableView in the UIViewControllers view.
You can still have the UIViewController conform to the UITableViewDelgate and Datasource protocols, and use all the same methods you have now in your UITableViewController.
P.S. you'll get more responses if you use the plain "iphone" tag.


Q:

How to output two different labels on two buttons?

I have this code that shows a label when clicking the button, but I need the following:

Two buttons showing two different labels, in one of the buttons show your label below that button;
When a label is active or shown by clicking on the other button, that label is replaced by the new one.

(function() {
  $('button').on('click', function() {
    $("#action").html("button was clicked");
  });
})();

<button>Action</button>

See example: https://jsfiddle.net/fr4x32g7/

A:

(function () {
  var active = "";
  $('button').on('click', function (e) {
    var id = "#" + e.target.value;
    $(active).html("");
    active = id;
    $(id).html("button was clicked");
  });
})();

<button value="action">Action</button>

<button value="action1">Action</button>


Q:

Incorrect runtime version of NUnit referenced when installing from NuGet

I have just updated my NUnit NuGet reference and my project now appears to reference an NUnit dll built for .NET 1.1. I am running .NET 4.0 and hence this is causing compilation errors.
Why might the wrong DLL be referenced here?
I'm sorry for the lack of additional information, but this is all I have to go on at the moment. I will update the question if I find out more.

A:

This is a packaging problem with NUnit which is being fixed.


Q:

Adding Kurdish text (right to left) to image is returned separated strings

I'm using PIT to put Kurdish(sorani, arabic-like) text on an image, but the text on the image is separated from each other. Does anyone knows how to solve this problem?
font_size = 100
img = Image.open("cute cat.jpg")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("./KGoran.ttf", font_size, encoding="unic")

text = "ڕۆژتان باش ئازیزان"
reversed_text = reversed(text)

fill = (0,0,0)
font = font

string_text = ""
for i in reversed_text:
    string_text += i

draw.text((0, 0), string_text, fill, font)
img.save("added text to image.jpg")

A:

PIL can't handle shaping Arabic-like fonts, (unless they fixed it recently).  I've seen one library, like this reshaper library, which will combine characters correctly.  Other solutions include using pango or pycairo to deal with the font, see this discussion.


Q:

Trying to use matrices for Hadamard and Controlled Not gates

I have the following simple quantum circuit:

This outputs are 00 and 11 for the two qubits. Using matrices, I have applied the H gate to the first qubit (ket 0):
$\frac{1}{\sqrt{2}}\begin{pmatrix}1&1\\ 1&-1\end{pmatrix}\begin{pmatrix}1\\0\end{pmatrix}=\begin{pmatrix}\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\end{pmatrix}$
Is this right? Moreover, I don't understand how to apply the Controlled Not to to resulting matrix. I assume it's applied to a product basis state of the resulting:
$\begin{pmatrix}\frac{1}{\sqrt{2}}\\\frac{1}{\sqrt{2}}\end{pmatrix}$ and $\begin{pmatrix}0\\1\end{pmatrix}$
I would be grateful for any help on continuing this, and if anyone could point out if I am wrong with my previous calculations. I appreciate the help in advance.

A:

The application of Hadamard gate on the first qubit is correct.
Since CNOT is two qubit gate, it has to be described by matrix 4x4, so far you have only 2x2 matrix. However, there is a identity operator $I$ described by unit matrix on the second qubit. Hence the first step in you circuit can be described by matrix $H \otimes I$. Resulting matrix is of type 4x4. Now, you can apply CNOT gate.
So, first step is
$$
H \otimes I = \frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
1 & 0 & -1 & 0 \\
0 & 1 & 0 & -1 \\
\end{pmatrix}.
$$
Second step is CNOT gate
$$
CNOT=
\begin{pmatrix}
1 & 0 & 0 & 0 \\
0 & 1 & 0 & 0 \\
0 & 0 & 0 & 1 \\
0 & 0 & 1 & 0 \\
\end{pmatrix}.
$$
The whole circuit is described by matrix
$$
CNOT(H \otimes I)= \frac{1}{\sqrt{2}}
\begin{pmatrix}
1 & 0 & 1 & 0 \\
0 & 1 & 0 & 1 \\
0 & 1 & 0 & -1 \\
1 & 0 & -1 & 0 \\
\end{pmatrix}.
$$
If you apply the circuit on input $|00\rangle$ you will get state
$$
\frac{1}{\sqrt{2}}
\begin{pmatrix}
1 \\
0 \\
0 \\
1 \\
\end{pmatrix}.
$$
This is so-called Bell state $\beta_{00}$. If you set inputs  $|01\rangle$, $|10\rangle$ or $|11\rangle$, you will get different Bell states.

EDIT: a manual how to compute tensor product mechanically
Based on comments below, here is a manual how to computer tensor product:


Q:

`java.lang.NoSuchMethodError: cats.FlatMap.map2` in runtime when using `.sequence`

I'm getting the following runtime error after migrating from cats v1.1.0 to v1.4.0 (An error arises from places where .sequence (cats.Traverse) is used).
The code looks like:
import cats.implicits._
import cats.effect.IO

List(1, 2, 3).map(x => IO(...)).sequence

java.lang.NoSuchMethodError: cats.FlatMap.map2$(Lcats/FlatMap;Ljava/lang/Object;Ljava/lang/Object;Lscala/Function2;)Ljava/lang/Object;
    at cats.effect.IOLowPriorityInstances$IOEffect.map2(IO.scala:765)
...

Here is my build.sbt:
organization := "org.xxx"

name := "yyy"

version := "0.0.1"

scalaVersion := "2.12.9"

resolvers += Resolver.bintrayRepo("hseeberger", "maven")
resolvers ++= Seq("Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/")

lazy val doobieVersion = "0.5.3"
lazy val akkaHttpVersion = "10.1.1"
lazy val akkaVersion = "2.5.12"
lazy val catsVersion = "1.4.0"
lazy val circeVersion = "0.9.3"

lazy val doobieDeps = Seq(
  "org.tpolecat" %% "doobie-core"      % doobieVersion,
  "org.tpolecat" %% "doobie-postgres"  % doobieVersion,
  "org.tpolecat" %% "doobie-scalatest" % doobieVersion,
  "org.tpolecat" %% "doobie-hikari"    % doobieVersion
)

lazy val catsDeps = Seq(
  "org.typelevel" %% "cats-effect" % catsVersion,
  "org.typelevel" %% "cats-core" % catsVersion
)

lazy val otherDeps = Seq(
  "com.github.pureconfig" %% "pureconfig" % "0.9.1",
  "org.scorexfoundation" %% "scrypto" % "2.1.1",
  "de.heikoseeberger" %% "akka-http-circe" % "1.20.1",
  "org.scalaj" %% "scalaj-http" % "2.4.0",
  "org.flywaydb" % "flyway-core" % "5.1.1",
  "com.github.blemale" %% "scaffeine" % "2.5.0",
  ("org.scorexfoundation" %% "sigma-state" % "master-2b4b07a1-SNAPSHOT")
    .exclude("ch.qos.logback", "logback-classic")
    .exclude("org.scorexfoundation", "scrypto"),
)
lazy val circeDeps = Seq(
  "io.circe" %% "circe-core" % circeVersion,
  "io.circe" %% "circe-parser" % circeVersion,
  "io.circe" %% "circe-generic" % circeVersion
)

libraryDependencies ++= (otherDeps ++ doobieDeps ++ catsDeps ++ loggingDeps ++ akkaDeps ++ circeDeps ++ testDeps)

I've tried to run it different ways (idea, set run) and on different platforms - the result is always the same.
What could it be caused by?

A:

Try to change versions to
"org.typelevel" %% "cats-effect" % "1.4.0",
"org.typelevel" %% "cats-core" % "1.6.1"

Your project seems to work with them.


Q:

How to bind mouseover using knockout in a column in a table

I am trying to bind a column in a table for mouseover event, if the cursor is over the column cell (not the column header), it will make the extended details (StrTimeDesc) visible. But when I run it, it will only display the 1st column (Work Date column) then the rest is blank.
here is my view:

            Work Date
            Schedule Description

here is my knockout:
var Action =
{

    Timesheet_headers: ko.observableArray([]),
    workDate: ko.observable(),
    Schedule_description: ko.observable(),
    StrSchedDesc: ko.observable(),
    StrTimeDesc: ko.observable(),
    IsTog: ko.observable(false),

    detailsEnabled: ko.observable(false),
    enableDetails: function() {
        this.IsTog(true);
    },
    disableDetails: function() {
        this.IsTog(false);
    }
}

apply bindings are already done. I just omitted those parts because SO doesn't allow a post with a lot of codes and less details. If i remove the mouseover binding, the table runs fine. That mouseover bindings came from knockoutjs site.
UPDATE:
here is my class
public class Timesheet_header
{

    [Key]
    public System.long AUTO_ID { get; set; }
    public System.Int64 Employee_id { get; set; }
    public System.Int16 Schedule_id { get; set; }
    [Required]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime Work_date { get; set; }

    public string StrSchedDesc { get; set; }
    public string StrTimeDesc { get; set; }
    public bool IsTog { get; set; }

    public Timesheet_header()
    {
        IsTog = false;
    }
}

here is my data access (this successfully retrieves all records from the db)
public static List<Timesheet_header> GetLogs(long Employee_id, DateTime DateFrom, DateTime DateTo)
{
    var items = new List<Timesheet_header>();
    var command = new SqlCommand();
    try
    {
        command.CommandText = "GetTimeSheetHeaders";
        command.CommandType = CommandType.StoredProcedure;

        command.Parameters.AddWithValue("@Employee_id", Employee_id).Direction = ParameterDirection.Input;
        command.Parameters.AddWithValue("@DateFrom", DateFrom).Direction = ParameterDirection.Input;
        command.Parameters.AddWithValue("@DateTo", DateTo).Direction = ParameterDirection.Input;

        DataTable dt = SqlHelper.GetData(command);

        if (dt.Rows.Count <= 0) return items;

        foreach (DataRow row in dt.Rows)
        {
            Timesheet_header item = new Timesheet_header();

            item.AUTO_ID = (row["AUTO_ID"]).GetLong();

            item.Employee_id = (row["Employee_id"]).GetLong();

            item.Work_date = (row["Work_date"]).GetDbDate();

            item.StrSchedDesc = row["Schedule_description"].GetString();

            item.StrTimeDesc = " From " + row["Time_from"].GetString() + " - To " + row["Time_to"].GetString();

            items.Add(item);
        }
    }
    catch (Exception s)
    {
        return new List<Timesheet_header>();
    }

    return items;
}

I also updated my view and knockout above

A:

enableDetails and disableDetails should be prefixed with  $parent as they are inside a foreach. Otherwise knockout will look for those functions inside each Timesheet_headers object.

This still won't give you the expected result. workDate, Schedule_description, StrSchedDesc StrTimeDesc and IsTog should be properties of items in Timesheet_headers array. You don't need to have that in Action object.
There is also a typo here. O should be a lowercase in observable. Instead of
workDate: ko.Observable()

you should call
workDate: ko.observable()

Also, refer this answer and this fiddle. The question is same as yours.


Q:

any reason why an interface reference would be included before a method name on an implementing class?

Is there any reason why an interface reference would be included before a method name on an implementing class? For example, let's say you have a ReportService : IReportService and a GetReport(int reportId) method. I was reviewing some code and another developer implemented the method like this in ReportService:
Report IReportService.GetReport(int reportId)
{
  //implementation
}

I've never seen a service implementation like this before. Does it serve any purpose?

A:

This is called "explicit interface implementation". The reason for this may for example be a naming conflict.
Consider the interfaces IEnumerable and IEnumerable<T>. One declares a non-generic method
IEnumerator GetEnumerator();

and the other a generic one:
IEnumerator<T> GetEnumerator();

In C# it's not allowed to have two methods with the same name that only differ in there return type. So if you implement both interfaces, you need to declare one method explicit:
public class MyEnumerable<T> : IEnumerable, IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator()
    {
        ... // return an enumerator
    }

    // Note: no access modifiers allowed for explicit declaration
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator(); // call the generic method
    }
}

Explicitly implemented interface methods cannot be called on instance variables:
MyEnumerable<int> test = new MyEnumerable<int>();
var enumerator = test.GetEnumerator(); // will always call the generic method.

If you want to call the non-generic method, you'd need to cast test to IEnumerable:
((IEnumerable)test).GetEnumerator(); // calls the non-generic method

That also seems to be the reason why there are no access modifiers (like public or private) are allowed on explicit implementations: it's not visible on the type anyway.


Q:

Laravel 5.2 optimize making leftjoin with sum() faster

I have 5 tables which is related to a custom field which is string NOT the id.
I want to get the sum of the amount of each table related to the one I want to query.

I manage to make it work using leftjoin but it takes at least 10 sec
  to give results.

I want to optimize my query.
$raohs = Raoh::leftjoin('func','raoh.FFUNCCOD','=','func.FFUNCCOD')
            ->leftjoin('appd','raoh.FRAOCOD','=','appd.FRAOCOD')
            ->leftjoin('altd','raoh.FRAOCOD','=','altd.FRAOCOD')
            ->leftjoin('obrd','raoh.FRAOCOD','=','obrd.FRAOCOD')
            ->where(function($query) {
                $search = \Request::get('search');
                $query->where('fraodesc', 'like', '%' . $search . '%')
                    ->orWhere('fsourcod', 'like', '%' . $search . '%');
            })
            ->where('func.FFUNCCOD', 'like', '%' . trim($ffunccod) . '%')
            ->select(\DB::raw('fraodesc,fsourcod,raoh.ffunccod,raoh.FRAOCOD,func.ffunction,sum(appd.FAMOUNT) AS fapprop, sum(altd.FAMOUNT) AS fallot, sum(obrd.FAMOUNT) AS foblig'))
            ->orderBy('ffunction')
            ->groupBy('raoh.FRAOCOD')
            ->paginate(20);

A:

It seems in my question i have loaded my query which is SUM() in every record,(making it slower). In order to make it faster, I only need to leftjoin sum() once in every table during the initialization. Heres how I did it.
I just remember i have similar question a long time ago here, with pure SQL only. MySQL Make it faster,add members count to family table
$raohs = Raoh::leftjoin('func','raoh.FFUNCCOD','=','func.FFUNCCOD')
            ->leftjoin(\DB::raw('(Select FRAOCOD, sum(FAMOUNT) as FAMOUNT from appd group by FRAOCOD) as appd'),'raoh.FRAOCOD','=','appd.FRAOCOD')
            ->leftjoin(\DB::raw('(Select FRAOCOD, sum(FAMOUNT) as FAMOUNT from altd group by FRAOCOD) as altd'),'raoh.FRAOCOD','=','altd.FRAOCOD')
            ->leftjoin(\DB::raw('(Select FRAOCOD, sum(FAMOUNT) as FAMOUNT from obrd group by FRAOCOD) as obrd'),'raoh.FRAOCOD','=','obrd.FRAOCOD')
            ->where(function($query) {
                $search = \Request::get('search');
                $query->where('fraodesc', 'like', '%' . $search . '%')
                    ->orWhere('fsourcod', 'like', '%' . $search . '%');
            })
            ->where('func.FFUNCCOD', 'like', '%' . trim($ffunccod) . '%')
            ->select(\DB::raw('fraodesc,fsourcod,raoh.ffunccod, raoh.FRAOCOD, func.ffunction, appd.FAMOUNT as fapprop, altd.FAMOUNT as fallot, obrd.FAMOUNT as foblig'))
            ->orderBy('ffunction')
            ->groupBy('raoh.FRAOCOD')
            ->paginate(20);

It query now in about a sec


Q:

COM : convert 'const GUID*' to const wchar_t*

I am porting some code from VS to mingw C++ . One of the statements in my code is
CFactoryTemplate g_Templates[1] = {
    {&CLSID_SystemClock, CSystemClock::CreateInstance}
};

int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

I am getting the following error on the first statement

error: cannot convert 'const GUID* {aka const _GUID*}' to 'const
  WCHAR* {aka const wchar_t*}' in initialization

I am completely puzzled by this. I did a little investigation and noticed that
CFactoryTemplate is a class in combase.h . Also my project is UNICODE enabled if that matters. Any suggestions on how to resolve this issue ?

A:

Your code - you say you are porting is wrong, you need to provide different parameters to CFactoryTemplate, the compiler error proves that. Here you will find some sample code to init such array of instances of this class (you dont need to fill all fields):
// list of class ids and creator functions for class factory

CFactoryTemplate g_Templates[2]=
  { { L"Gargle filter"         // CFactoryTemplate.m_name

  , &CLSID_Gargle            // CFactoryTemplate.m_ClsID

  , CGargle::CreateInstance  // CFactoryTemplate.m_lpfnNew
  , NULL                     // CFactoryTemplate.m_lpfnInit
  , &sudGargle               // CFactoryTemplate.m_pAMovieSetup_Filter
                                   }
  , { L"Gargle filter property page"
  , &CLSID_GargProp
  , CGargleProperties::CreateInstance
 }
 };

int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

from https://msdn.microsoft.com/en-us/library/aa451506.aspx
also Hans Passant has given you other example


Q:

Magento getCollection , SQL injection

I installed an extension for a customer of ours and I'm just learning about SQL and SQL injection, and this extension uses all kind of AJAX calls. However, I checked the code and some of the AJAX parameters are used directly in queries. I wonder, is this code for example SQL injection safe?
    $collection = Mage::getModel('blogn/user')->getCollection();
    $collection->getSelect()->joinLeft($table, 'main_table.user_id = ' . $userId. ','profile_id');

So, the $table variable is hardset just above the code. However, the $userId directly comes from an AJAX POST.
This is just an example, but a little down further there is also a getSelect()->where part, where also the $userId is direclty inserted.
Is this safe? To me it seems not. Should the query be changed to bind variables? Does Magento support this? For example, can I make the query something like this:
$collection->getSelect()->joinLeft($table, 'main_table.user_id = ?,'profile_id',array($userId));

Assuming that binding this variable would be safer because it can be prepared statement then?

A:

Definitely not safe if anyone can change that parameter. Making an SQL injection with such code is easy as.
Magento totally supports binding here's how you should do it:
$adapter = $collection->getConnection();
$binds = $adapter->quoteInto("main_table.user_id = ?", $userId);
$collection->getSelect()->joinLeft($table, $binds, 'profile_id');


Q:

Make one view center as buttom of second view in Auto Layout - iOS

There are two views- I want to show green view of the background image with center align to the buttom of image as shown in below image

Green view height will also be dynamic.

A:

Just constrain the centerY anchor of the greenView to the bottom anchor of the image view:
greenView.centerYAnchor.constraint(equalTo: imageView.bottomAnchor).isActive = true
greenView.centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true


Q:

How get the last update of Netbeans 7

I currently use Netbeans 7.0.1. From the About Page : Product Version: NetBeans IDE 7.0.1 (Build 201107282000). I use Netbeans under Ubuntu behind a proxy.
I see on Netbeans Website that a new version 7.1.2 is available http://netbeans.org/downloads/index.html.
When I check for Update i saw : Your IDE is up to date! There are no updates available.
What is the problem ? I should download netbeans from the website and reinstall ?
Thanks

A:

in Netbeans 7.0.1 is not a simple "update", this is a new release.
"Updates" are designed to update the current release, only.
In addition, the "check for updates" button works very well - it shows updates and new releases.  You can download and install NB7.1.2 and import all the the NB7.0.1 preferences.