问:
Angular slide a div on swipe similar to archive in gmail or outlook
So am trying to slide a div on swipe using angular.(The swipe functionality on a row in iOS)
I have tried a couple of libraries but it doesn't to achieve what I need.

ngswipeitem

awesome-angular-swipe

swipe-li

I need to show div containing archive on swipe similar to the archive in outlook

```<code><div ng-repeat="item in items">
    <div>{{item.Subject}}</div>
    <div>Archive</div> <!--this div is hidden and I need to show it on swipe-->
</div>
</code>```

答:
I ended up using Hammerjs and Angular Hammer.
My problem was in the ng-repeater.I had to loop all the divs.

Html:

```<code><div class="Swiper" ng-repeat="item in items">
    <div>{{item.Subject}}</div>
    <div class="Page">Archive</div>
</div>
</code>```

Css:

```<code>.Page,
.Swiper {
    position: relative;
    height: 100%;
}

.Swiper {

    overflow: hidden;
}

    .Swiper.animate > .Page {
        transition: all .3s;
        -webkit-transition: all .3s;
    }

.Page {
    position: absolute;
    top: 0;
    left: 0;

    padding: 0 10px;
 width:100%;
 height:100%;

    padding-top: 10%;

}
</code>```

The problem:

```<code> var div = document.querySelector('.Swiper');
 var outer = new HammerCarousel(div, Hammer.DIRECTION_HORIZONTAL, docId);
</code>```

The Solution:

```<code>  var divs = document.querySelectorAll('.Swiper');
            for (i = 0; i < divs.length; ++i) {
                var outer = new HammerCarousel(divs[i], Hammer.DIRECTION_HORIZONTAL, docId);
            }
</code>```

Body:
So am trying to slide a div on swipe using angular.(The swipe functionality on a row in iOS)
I have tried a couple of libraries but it doesn't to achieve what I need.

ngswipeitem

awesome-angular-swipe

swipe-li

I need to show div containing archive on swipe similar to the archive in outlook

{{item.Subject}}

Archive

Body:
I ended up using Hammerjs and Angular Hammer.
My problem was in the ng-repeater.I had to loop all the divs.

Html:

<div class="Swiper" ng-repeat="item in items">
    <div>{{item.Subject}}</div>
    <div class="Page">Archive</div>
</div>

Css:

.Page,
.Swiper {
    position: relative;
    height: 100%;
}

.Swiper {

    overflow: hidden;
}

    .Swiper.animate > .Page {
        transition: all .3s;
        -webkit-transition: all .3s;
    }

.Page {
    position: absolute;
    top: 0;
    left: 0;

    padding: 0 10px;
 width:100%;
 height:100%;

    padding-top: 10%;

}

The problem:

 var div = document.querySelector('.Swiper');
 var outer = new HammerCarousel(div, Hammer.DIRECTION_HORIZONTAL, docId);

The Solution:

  var divs = document.querySelectorAll('.Swiper');
            for (i = 0; i < divs.length; ++i) {
                var outer = new HammerCarousel(divs[i], Hammer.DIRECTION_HORIZONTAL, docId);
            }


来源: stackexchange

问:
How do I prevent the loading of duplicate rows in to an Oracle table?
I have some large tables (millions of rows).  I constantly receive files containing new rows to add in to those tables - up to 50 million rows per day.  Around 0.1% of the rows I receive are duplicates of rows I have already loaded (or are duplicates within the files).  I would like to prevent those rows being loaded in to the table.

I currently use SQLLoader in order to have sufficient performance to cope with my large data volume.  If I take the obvious step and add a unique index on the columns which goven whether or not a row is a duplicate, SQLLoader will start to fail the entire file which contains the duplicate row - whereas I only want to prevent the duplicate row itself being loaded.

I know that in SQL Server and Sybase I can create a unique index with the 'Ignore Duplicates' property and that if I then use BCP the duplicate rows (as defined by that index) will simply not be loaded.

Is there some way to achieve the same effect in Oracle?

I do not want to remove the duplicate rows once they have been loaded - it's important to me that they should never be loaded in the first place.

答:
use below option, if you will get this much error 9999999 after that your sqlldr will terminate.

```<code>OPTIONS (ERRORS=9999999, DIRECT=FALSE )
LOAD DATA
</code>```

you will get duplicate records in bad file.

```<code>sqlldr user/password@schema CONTROL=file.ctl, LOG=file.log, BAD=file.bad
</code>```

ContentLicense: CC BY-SA 2.5

Body:
use below option, if you will get this much error 9999999 after that your sqlldr will terminate.

OPTIONS (ERRORS=9999999, DIRECT=FALSE )
LOAD DATA

you will get duplicate records in bad file.

sqlldr user/password@schema CONTROL=file.ctl, LOG=file.log, BAD=file.bad

ContentLicense: CC BY-SA 3.0


问:
Android studio Action call to run USSD codes
By using an app I want to run a USSD code, but the problem is it doesn't recognize the "#" symbol.
If I want to run "*100#" it recognize the input only as "*100". How to add the "#". and what is the reason to not recognize that?

Here is my code ...

```<code>  checkBalance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(Intent.ACTION_CALL);

            i.setData(Uri.parse("tel:"+"*100#"));

            if (ActivityCompat.checkSelfPermission(mobitelPage.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(i);

        }
    });
</code>```

答:
You need to use Uri.encode("YOUR USSD CODE") in Uri.Parse().

Example:

```<code>Uri.parse("tel:"+ Uri.encode("*100#"));
</code>```

Body:
By using an app I want to run a USSD code, but the problem is it doesn't recognize the "#" symbol.
If I want to run "*100#" it recognize the input only as "*100". How to add the "#". and what is the reason to not recognize that?

Here is my code ...

  checkBalance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i = new Intent(Intent.ACTION_CALL);

            i.setData(Uri.parse("tel:"+"*100#"));

            if (ActivityCompat.checkSelfPermission(mobitelPage.this,
                    Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            startActivity(i);

        }
    });

Body:
You need to use Uri.encode("YOUR USSD CODE") in Uri.Parse().

Example:

Uri.parse("tel:"+ Uri.encode("*100#"));


问:
Simple word replacement in output from SQL
I'm running PostgreSQL 9.4.

Is there a replace string function which can take an array of words, or other similar function?

Ex.

```<code>SELECT REPLACE(my_column, ['blue', 'red'], ['ColorBlue', 'ColorRed']);
</code>```

So blue becomes ColorBlue, and red becomes ColorRed?
It's not only such simple replacements, but for the example I'm using this.

答:
I agree with @OtoShavadze that you can write your own function.

Here is my solution:

I use generate_subscripts(array anyarray, dim int) function as suggested in Searching in Arrays documentation.

```<code>CREATE OR REPLACE FUNCTION translate(string text, from_array text[], to_array text[])
  RETURNS text AS
$BODY$
DECLARE
    output  text;
BEGIN
    SELECT INTO output
        to_array[idx]
    FROM
        generate_subscripts(from_array, 1) AS idx
    WHERE
        from_array[idx] = string;       -- here you can change the search condition

    IF FOUND THEN
        RETURN output;
    ELSE
        RETURN string;
    END IF;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;
</code>```

It finds and replaces whole words but you can change it (line marked in the code) to find only a substring, match case-insensitive, etc...

You should also add parameter checking: arrays should not be null, multidimensional nor differ in size:

```<code>IF from_array IS NULL OR to_array IS NULL THEN
    RAISE EXCEPTION 'NULL parameters';
END IF;

IF array_ndims(from_array) != 1 OR array_ndims(to_array) != 1 THEN
    RAISE EXCEPTION 'Multidimensional parameters';
END IF;

IF array_length(from_array, 1) != array_length(to_array, 1) THEN
    RAISE EXCEPTION 'Parameters size differ';
END IF;
</code>```

```<code>SELECT translate('red', ARRAY['blue', 'red'], ARRAY['ColorBlue', 'ColorRed']);
</code>```

returns

```<code>ColorRed
</code>```

Body:
I'm running PostgreSQL 9.4.

Is there a replace string function which can take an array of words, or other similar function?

Ex.

SELECT REPLACE(my_column, ['blue', 'red'], ['ColorBlue', 'ColorRed']);

So blue becomes ColorBlue, and red becomes ColorRed?
It's not only such simple replacements, but for the example I'm using this.

Body:
I agree with @OtoShavadze that you can write your own function.

Here is my solution:

I use generate_subscripts(array anyarray, dim int) function as suggested in Searching in Arrays documentation.

CREATE OR REPLACE FUNCTION translate(string text, from_array text[], to_array text[])
  RETURNS text AS
$BODY$
DECLARE
    output  text;
BEGIN
    SELECT INTO output
        to_array[idx]
    FROM
        generate_subscripts(from_array, 1) AS idx
    WHERE
        from_array[idx] = string;       -- here you can change the search condition

    IF FOUND THEN
        RETURN output;
    ELSE
        RETURN string;
    END IF;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE;

It finds and replaces whole words but you can change it (line marked in the code) to find only a substring, match case-insensitive, etc...

You should also add parameter checking: arrays should not be null, multidimensional nor differ in size:

IF from_array IS NULL OR to_array IS NULL THEN
    RAISE EXCEPTION 'NULL parameters';
END IF;

IF array_ndims(from_array) != 1 OR array_ndims(to_array) != 1 THEN
    RAISE EXCEPTION 'Multidimensional parameters';
END IF;

IF array_length(from_array, 1) != array_length(to_array, 1) THEN
    RAISE EXCEPTION 'Parameters size differ';
END IF;

SELECT translate('red', ARRAY['blue', 'red'], ARRAY['ColorBlue', 'ColorRed']);

returns

ColorRed


问:
Does JW player support HTTP2?
I am currently working on a project where we are using JW Player 7.11.1, we are planning to support http2 for our website, could you please help me understand, Does JW player support HTTP2?</p>

答:
You will not have problems, HTTP2 maintains high-level compatibility with HTTP 1.1.

doc: https://http2.github.io/faq/

we can work on new mechanisms that are version-independent, as long as
  they’re backwards-compatible with the existing Web

I'm using JwPLyer 7.x with HTTP2 without problems.

Title: Does JW player support HTTP2?


问:
How do I hide the speechRecogniser activity behind the main activity?
I am trying to hide the speech recogniser dialog that shows up saying "speak now" and written google as the title ,whenever i call it for passing some voice command. I don't want it to show up. Instead I want it to work in teh background so that the user cannot see it. What should be the correct way to do it?

```<code>public void getSpeechInput(View view) {

    getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, 10);
    } else {
        Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 10:
            if (resultCode == RESULT_OK && data != null) {
                ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txvResult.setText(result.get(0));
                String str = txvResult.getText().toString();

                if(str.equals("lights on")){
                    Toast.makeText(MainActivity.this,
                            "matched", Toast.LENGTH_LONG).show();
                    count[0]=1;
                    turnOnFlash();
                }
                else if(str.equals("lights off")){
                    Toast.makeText(MainActivity.this,
                           "didnt", Toast.LENGTH_LONG).show();
                    count[0]=0;
                    turnOffFlash();
                }
            }
            break;
    }
}
</code>```

I tried using this but it didn't work:-

```<code>getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
</code>```

答:
Try this. This listener catches the events and you can process them accordingly.

```<code>SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener()
{

//Do whatever you want

});
</code>```

Body:
I am trying to hide the speech recogniser dialog that shows up saying "speak now" and written google as the title ,whenever i call it for passing some voice command. I don't want it to show up. Instead I want it to work in teh background so that the user cannot see it. What should be the correct way to do it?

public void getSpeechInput(View view) {

    getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(intent, 10);
    } else {
        Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
    }
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 10:
            if (resultCode == RESULT_OK && data != null) {
                ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txvResult.setText(result.get(0));
                String str = txvResult.getText().toString();

                if(str.equals("lights on")){
                    Toast.makeText(MainActivity.this,
                            "matched", Toast.LENGTH_LONG).show();
                    count[0]=1;
                    turnOnFlash();
                }
                else if(str.equals("lights off")){
                    Toast.makeText(MainActivity.this,
                           "didnt", Toast.LENGTH_LONG).show();
                    count[0]=0;
                    turnOffFlash();
                }
            }
            break;
    }
}

I tried using this but it didn't work:-

getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);

Body:
Try this. This listener catches the events and you can process them accordingly.

SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener()
{

//Do whatever you want

});


问:
File system path for images
I'm writing a custom helper that extends HtmlHelper and overriding the \HtmlHelper::image() method to calculate the image dimensions and add them as HTML attributes. What I have so far works fine for regular pictures:

```<code>public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}
</code>```

… but has these flaws:

Pictures from plug-ins can't be located on disk (and they should), e.g.:

```<code>echo $this->Html->image('/debug_kit/img/cake.icon.png', array('alt' => 'CakePHP'));
</code>```

… produces this file system path:

```<code>…\src\webroot/debug_kit/img/cake.icon.png
</code>```

… thus getimagesize() fails because actual location is:

```<code>…\src\Plugin\DebugKit\webroot\img\cake.icon.png"
</code>```

External pictures (which should be ignored) go through the full process:

```<code>echo $this->Html->image('http://placekitten.com/200/300');
…\src\webroothttp://placekitten.com/200/300
</code>```

I've been looking for a builtin method to convert a CakePHP picture URL (in any format accepted by \HtmlHelper::image() into a file system path (o something like null when doesn't apply) but I couldn't find any. Native features that need a disk path, such as \Helper::assetTimestamp() are wrapped in tons of non-reusable code.

Is there an elegant solution?

答:
Try using DS rather than using \ or /, they sometime can cause problems with the OS.
DS is directory separator provided by cakephp Short for PHP’s DIRECTORY_SEPARATOR, which is / on Linux and \ on Windows.
Check the doc</p>

Title: File system path for images

Body:
I'm writing a custom helper that extends HtmlHelper and overriding the \HtmlHelper::image() method to calculate the image dimensions and add them as HTML attributes. What I have so far works fine for regular pictures:

public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}

… but has these flaws:

Pictures from plug-ins can't be located on disk (and they should), e.g.:

echo $this->Html->image('/debug_kit/img/cake.icon.png', array('alt' => 'CakePHP'));

… produces this file system path:

…\src\webroot/debug_kit/img/cake.icon.png

… thus getimagesize() fails because actual location is:

…\src\Plugin\DebugKit\webroot\img\cake.icon.png"

External pictures (which should be ignored) go through the full process:

echo $this->Html->image('http://placekitten.com/200/300');
…\src\webroothttp://placekitten.com/200/300

I've been looking for a builtin method to convert a CakePHP picture URL (in any format accepted by \HtmlHelper::image() into a file system path (o something like null when doesn't apply) but I couldn't find any. Native features that need a disk path, such as \Helper::assetTimestamp() are wrapped in tons of non-reusable code.

Is there an elegant solution?


问:
body-parser request.body is empty
I use axios.get() send data to server nodejs, i use request.body to use but request.body return {} for me.

in server.js file

```<code>const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const setting = {
  port : 20101
}

app.set('port', (process.env.PORT || setting.port));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(req, res, next){
  res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

app.get('/search', function(req, res){
   if(!req.body) return res.sendStatus(400);
   console.log(req.body, ' <--- req.body'); // return {} <--- req.body
});

app.listen(setting.port, function() {
   console.log('listening on port : ' + setting.port);
});
</code>```

and api file

```<code> axios.get(apiPath('/search'),{
    keyword
  })
  .then(function(response){
    console.log(response, '<--- response');
  })
  .catch(function(error){
    console.log(error, '<--- error');
  })
</code>```

Please suggest how I should solve the problem.

答:
You used Get method..Change it to Post method</p>

```<code>app.post('/search', function{});
</code>```

Title: body-parser request.body is empty

Body:
I use axios.get() send data to server nodejs, i use request.body to use but request.body return {} for me.

in server.js file

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

const setting = {
  port : 20101
}

app.set('port', (process.env.PORT || setting.port));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(function(req, res, next){
  res.setHeader('Access-Control-Allow-Origin','*');
  res.setHeader('Cache-Control', 'no-cache');
  next();
});

app.get('/search', function(req, res){
   if(!req.body) return res.sendStatus(400);
   console.log(req.body, ' <--- req.body'); // return {} <--- req.body
});

app.listen(setting.port, function() {
   console.log('listening on port : ' + setting.port);
});

and api file

 axios.get(apiPath('/search'),{
    keyword
  })
  .then(function(response){
    console.log(response, '<--- response');
  })
  .catch(function(error){
    console.log(error, '<--- error');
  })

Please suggest how I should solve the problem.

Body:
You used Get method..Change it to Post method

app.post('/search', function{});


问:
Garbage Collection in Delphi
Does Delphi have Garbage Collection?</p>

答:
In the usual sense of garbage collection, where the runtime detects unreferenced objects and destroys them or otherwise reclaims unused resources, no, Delphi does not have garbage collection.

If you use native Win32 Delphi, then the closest you have to garbage collection is the various reference-counted types, including strings, interfaces, variants, and dynamic arrays. Those types will get cleaned up automatically when your program determines that they are no longer being used, but it does that by keeping a reference count as those objects enter and leave the current scope. You also have the concept of ownership, which will destroy owned components when the owner is destroyed.

If you use Delphi for .Net, then you implicitly have the garbage collection of the underlying runtime.

ContentLicense: CC BY-SA 4.0

Title: Garbage Collection in Delphi

Body: Does Delphi have Garbage Collection?


问:
Matplotlib: IndexError: too many indices for array
I m trying to plot the numpy array with scatter function. Below is the code:
at line mtp.scatter, i get the index error.

numpy array is [ 1.   1.   3.   3.   1.1  1.1  1.3  1.3]

Corresponding color is ['red', 'green', 'red', 'red']

Error message:
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])

IndexError: too many indices for array

```<code>X_traintest=np.array([[]])
X_traintest=np.append(X_traintest, X_trainset)

num1=len(X_trainset)
num2=len(X_testset)
for i in range (num2):
    X_traintest=np.append(X_traintest,X_testset[i], axis=0)
    emptarray=np.zeros(num1)
    for j in range (num1):
        emptarray[j]=mindist(X_testset[i], X_trainset[j])

        print emptarray
    min_index=np.argmin(emptarray)

    Y_colorset.append(Y_colorset[min_index])
    print X_traintest
    print Y_colorset

mtp.figure()
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])
mtp.show()
</code>```

答: It looks like X_traintest is a one-dimensional array, and you're trying to provide more than one dimensional index. (Namely two: [:, 0])

Body:
I m trying to plot the numpy array with scatter function. Below is the code:
at line mtp.scatter, i get the index error.

numpy array is [ 1.   1.   3.   3.   1.1  1.1  1.3  1.3]

Corresponding color is ['red', 'green', 'red', 'red']

Error message:
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])

IndexError: too many indices for array

X_traintest=np.array([[]])
X_traintest=np.append(X_traintest, X_trainset)

num1=len(X_trainset)
num2=len(X_testset)
for i in range (num2):
    X_traintest=np.append(X_traintest,X_testset[i], axis=0)
    emptarray=np.zeros(num1)
    for j in range (num1):
        emptarray[j]=mindist(X_testset[i], X_trainset[j])

        print emptarray
    min_index=np.argmin(emptarray)

    Y_colorset.append(Y_colorset[min_index])
    print X_traintest
    print Y_colorset

mtp.figure()
mtp.scatter(X_traintest[:,0],X_traintest[:,1],s=170,c=Y_colorset[:])
mtp.show()


问:
How to add multiple column Unique key in mySQL
I want to add the unique constarint I am using the following query but it gives me an error of SQL syntax

ALTER TABLE user_device ADD CONSTRAINT UKnfrn6f2pu3tqcwhqen0d6cq7u (owner,push_notification_id);

where is the mistake :|
it highlighted the mistake in push_notification_id

答:
Do Like this.</p>

```<code>ALTER TABLE user_device ADD unique index UKnfrn6f2pu3tqcwhqen0d6cq7u (owner,push_notification_id);
</code>```

Body:
Do Like this.

ALTER TABLE user_device ADD unique index UKnfrn6f2pu3tqcwhqen0d6cq7u (owner,push_notification_id);


答:
```<code>ALTER TABLE user_device ADD CONSTRAINT UKnfrn6f2pu3tqcwhqen0d6cq7u UNIQUE KEY  (owner,push_notification_id);
</code>```

Try above code.
You didn't mention which type of key you want to make on that combination of column.
So i had mention that using UNIQUE KEY keyword.

Hope this will helps you.

Title: How to add multiple column Unique key in mySQL

Body:
I want to add the unique constarint I am using the following query but it gives me an error of SQL syntax

ALTER TABLE user_device ADD CONSTRAINT UKnfrn6f2pu3tqcwhqen0d6cq7u (owner,push_notification_id);

where is the mistake :|
it highlighted the mistake in push_notification_id

Body:
ALTER TABLE user_device ADD CONSTRAINT UKnfrn6f2pu3tqcwhqen0d6cq7u UNIQUE KEY  (owner,push_notification_id);

Try above code.
You didn't mention which type of key you want to make on that combination of column.
So i had mention that using UNIQUE KEY keyword.

Hope this will helps you.


问:
How can I remove a byte of type []byte
I have a variable cmd that returns [50 48 ... 50 53 10]

It's possible to remove any bytes of this var? In my case, I want to remove the last byte [10] == LF (Line Feed) to obtain: [50 48 ... 50 53]

P.S.: I have not found any similar question because the function bytes.Trim(cmd, "\x10") does not work for me, or maybe, I don't use it fine...

答:
There is no such built-in method to do this, but you can still do it like this:</p>

```<code>cmd := []int{1, 2, 3, 3, 5, 6, 7, 8}
expected := cmd[:len(cmd)-1])
</code>```

Title: How can I remove a byte of type []byte

Body:
There is no such built-in method to do this, but you can still do it like this:

cmd := []int{1, 2, 3, 3, 5, 6, 7, 8}
expected := cmd[:len(cmd)-1])


问:
Pass a parameter to a Modal data
I am working with c# in ASP.NET and I had the following doubt:

I want pass "ContentID" (when i click in button "Details") to Modal Window.

@model IEnumerable<SoftIdeiaProject.Models.DB.Content>

@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Details

@Html.ActionLink("Create New", "CreateContent", Url.RequestContext.RouteData.Values)

            @Html.DisplayNameFor(model => model.Name)

    @foreach (var _item in Model)

    {

                @Html.DisplayFor(modelItem => _item.Name)

                @if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Delete", "DeleteContent", new { id = _item.ContentID }) </button>
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Edit", "AddVideo", new { id = _item.ContentID }) </button>
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Add Video", "AddVideo", new { id = _item.ContentID }) </button>
                }
                <button type="button" class="btn btn-default" data-toggle="modal"  data-target="#myModal" data-id="content_id_value">Details</button>

    }

@foreach (var _item in Model)
{

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

@Html.DisplayFor(modelItem => _item.Name)

@Html.DisplayFor(modelItem => _item.Description)

<video width="400" src="~/video/@_item.VideoID" controls/>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

}

 ```

For be more specific:
enter image description here

When i Click in "Details" of "Last" i want that the data on Modal be diferente that the "Pesquisa Rápida", but i can't do that.

答:
Say You have a ContentId field in your Model , generate unique buttons for each row  i.e.  instead of data-target="#myModal" make it  data-target="#myModal_@item.ContentId"

Details button should look like :

```<code><button type="button" class="btn btn-default" data-toggle="modal"  data-target="#myModal_@_item.ContentId"   data-id="@_item.ContentId">Details</button>
</code>```

Now In your second foreach Loop ,instead of

```<code><div class="modal fade" id="myModal" role="dialog">
</code>```

Make it unique

```<code><div class="modal fade" id="myModal_@_item.ContentId" role="dialog">
</code>```

Now you know the ContentId in each PopupId.

NOTE : I would strongly suggest having a single popup and just modifying the data inside that on details button click. you may also use ajax to get the data from server & bind it onSuccess.

Refer here for a Way to achieve modal popup in MVC

Title: Pass a parameter to a Modal data

Body:
I am working with c# in ASP.NET and I had the following doubt:

I want pass "ContentID" (when i click in button "Details") to Modal Window.

@model IEnumerable<SoftIdeiaProject.Models.DB.Content>

@{
    ViewBag.Title = "Details";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Details

@Html.ActionLink("Create New", "CreateContent", Url.RequestContext.RouteData.Values)

            @Html.DisplayNameFor(model => model.Name)

    @foreach (var _item in Model)

    {

                @Html.DisplayFor(modelItem => _item.Name)

                @if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Delete", "DeleteContent", new { id = _item.ContentID }) </button>
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Edit", "AddVideo", new { id = _item.ContentID }) </button>
                    <button type="button" class="btn btn-default"> @Html.ActionLink("Add Video", "AddVideo", new { id = _item.ContentID }) </button>
                }
                <button type="button" class="btn btn-default" data-toggle="modal"  data-target="#myModal" data-id="content_id_value">Details</button>

    }

@foreach (var _item in Model)
{

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

@Html.DisplayFor(modelItem => _item.Name)

@Html.DisplayFor(modelItem => _item.Description)

<video width="400" src="~/video/@_item.VideoID" controls/>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

}

For be more specific:
enter image description here

When i Click in "Details" of "Last" i want that the data on Modal be diferente that the "Pesquisa Rápida", but i can't do that.

Body:
Say You have a ContentId field in your Model , generate unique buttons for each row  i.e.  instead of data-target="#myModal" make it  data-target="#myModal_@item.ContentId"

Details button should look like :

<button type="button" class="btn btn-default" data-toggle="modal"  data-target="#myModal_@_item.ContentId"   data-id="@_item.ContentId">Details</button>

Now In your second foreach Loop ,instead of

<div class="modal fade" id="myModal" role="dialog">

Make it unique

<div class="modal fade" id="myModal_@_item.ContentId" role="dialog">

Now you know the ContentId in each PopupId.

NOTE : I would strongly suggest having a single popup and just modifying the data inside that on details button click. you may also use ajax to get the data from server & bind it onSuccess.

Refer here for a Way to achieve modal popup in MVC


问:
String copy using character pointers
Consider the following code, which works fine asusual for copying string

```<code>#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}
</code>```

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

```<code>char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2
</code>```

I tried to copy pointer values as shown below

```<code>void strcp(char *s1, char *s2) {

s1=s2;
}
</code>```

But it didn't work.

答:
```<code>void strcp(char **s1, char **s2) {

*s1=*s2;
}
</code>```

but it does not copy anything. After this s1 & s2 in main will point to the same memory location.

Title: String copy using character pointers

Body:
Consider the following code, which works fine asusual for copying string

#include<stdio.h>

void strcp(char *s1, char *s2);

int main() {

    char s1[]="Hai, I am a good boy";                   //1
    char s2[]="Really I am a good boy";                 //2

    strcp(s1,s2);

    printf("%s",s1);
    return 0;
}

void strcp(char *s1, char *s2) {

    while(*s1++=*s2++);
}

What changes I have to made if I want to declare s1, s2 as pointers to char inside main()?

char *s1="Hai, I am a good boy";                   //1
char *s2="Really I am a good boy";                 //2

I tried to copy pointer values as shown below

void strcp(char *s1, char *s2) {

s1=s2;
}

But it didn't work.

Body:
void strcp(char **s1, char **s2) {

*s1=*s2;
}

but it does not copy anything. After this s1 & s2 in main will point to the same memory location.


问:
How to update OpenGL on Arch Linux?
```<code>[yudhajit@yudhajit-pc ~]$ lspci | grep VGA

00:02.0 VGA compatible controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 07)

[yudhajit@yudhajit-pc ~]$ glxinfo | grep OpenGL

OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Mobile Intel® GM45 Express Chipset
OpenGL version string: 2.1 Mesa 17.1.1
OpenGL shading language version string: 1.20
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 2.0 Mesa 17.1.1
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 1.0.16
OpenGL ES profile extensions:
</code>```

I want to update OpenGL to 3.3, tried googling much nothing worked

答:
Mesa DRI Mobile Intel® GM45 Express Chipset

That only supports up to OpenGL 2.1. You may have some luck setting the LIBGL_ALWAYS_SOFTWARE environment variable to 1, however that wont use your graphics card.

Title: How to update OpenGL on Arch Linux?

Body:
[yudhajit@yudhajit-pc ~]$ lspci | grep VGA

00:02.0 VGA compatible controller: Intel Corporation Mobile 4 Series Chipset Integrated Graphics Controller (rev 07)

[yudhajit@yudhajit-pc ~]$ glxinfo | grep OpenGL

OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Mobile Intel® GM45 Express Chipset
OpenGL version string: 2.1 Mesa 17.1.1
OpenGL shading language version string: 1.20
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 2.0 Mesa 17.1.1
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 1.0.16
OpenGL ES profile extensions:

I want to update OpenGL to 3.3, tried googling much nothing worked


问:
Concurrent creation of sagas
When creating a sagapersister I have to implement ISagaStorage which defines:

Task<ISagaData> Find(Type sagaDataType, string propertyName, object propertyValue);
Task Insert(ISagaData sagaData, IEnumerable<ISagaCorrelationProperty> correlationProperties);
Task Update(ISagaData sagaData, IEnumerable<ISagaCorrelationProperty> correlationProperties);
 Task Delete(ISagaData sagaData);

When implementing insert the ISagaData.Id can be used for handling concurrent inserts (if this is a case). When implementing update the ISagaData.Revision can be used for handling concurrent updates on the same saga.

After writing some tests with highly concurrent configuration(both workers and parallellism) I can se that multiple sagas are created when I would expect only one to be created. This is probably beacause the following flow executes concurrent for multiple incoming messages without any "readlock":

Handle message - Check if saga exists (based on correlation properties)

No saga found - Create saga

I have read through different implementations of ISagaStore (MongoDb, RavenDb) but havent been able to find any mechanism which prevents creation of multiple "identical" sagas caused by concurrent handling of incoming messages.

Long story short:
Is there any mechanism or pattern in Rebus that could be used to prevent creation of multiple "identical" sagas caused by concurrent handling of messages?

One possible solution is to to check for identical correlation properties/values on insert?

(or maybe my understanding of the whole concept is wrong - In that case I would appreciate any help understanding this)

答:
Is there any mechanism or pattern in Rebus that could be used to prevent creation of multiple "identical" sagas caused by concurrent handling of messages?

Yes!

A saga persister – at least one that adheres to Rebus' contract tests – should enforce uniqueness of all correlation properties.

This would cause concurrent insert operations to result in rollbacks for all but the first.

Title: Concurrent creation of sagas


问:
Angular 2 nested forms with child components and validation
I'm trying achieve a nested form with validation in Angular 2, I've seen posts and followed the documentation but I'm really struggling, hope you can point me in the right direction.

What I am trying to achieve is having a validated form with multiple children components. These children components are a bit complex, some of them have more children components, but for the sake of the question I think we can attack the problem having a parent and a children.

What am I trying to accomplish

Having a form that works like this:

```<code><div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div>
        <label>Dummy</label>
        <input formControlName="dummyInput">
    </div>
</div>
</code>```

This requires having a class like this:

```<code>private userForm: FormGroup;
constructor(private fb: FormBuilder){
    this.createForm();
}
private createForm(): void{
    this.userForm = this.fb.group({
        userId: ["", Validators.required],
        dummyInput: "", Validators.required]
    });
}
</code>```

This works as expected, but now I want to decouple the code, and put the "dummyInput" functionality in a separate, different component. This is where I get lost. This is what I tried, I think I'm not far from getting the answer, but I'm really out of ideas, I'm fairly new to the scene:

parent.component.html

```<code><div [formGroup]="userForm" novalidate>
    <div>
        <label>User Id</label>
        <input formControlName="userId">
    </div>
    <div>
        <dummy></dummy>
    </div>
</div>
</code>```

parent.component.ts

```<code>private createForm(): void{
    this.userForm = this.fb.group({
    userId: ["", Validators.required],
    dummy: this.fb.group({
        dummyInput: ["", Validators.required]
    })
});
</code>```

children.component.html

```<code><div [formGroup]="dummyGroup">
    <label>Dummy Input: </label>
    <input formControlName="dummyInput">
</div>
</code>```

children.component.ts

```<code>private dummyGroup: FormGroup;
</code>```

I know something is not right with the code, but I'm really in a roadblock. Any help would be aprreciated.

Thanks.

答:
Not going to lie, don't know how I didn't find this post earlier.

Angular 2: Form containing child component

The solution is to bind the children component to the same formGroup, by passing the formGroup from the parent to the children as an Input.

If anyone shares a piece of code to solve the problem in other way, I'll gladly accept it.

Body:
I'm trying achieve a nested form with validation in Angular 2, I've seen posts and followed the documentation but I'm really struggling, hope you can point me in the right direction.

What I am trying to achieve is having a validated form with multiple children components. These children components are a bit complex, some of them have more children components, but for the sake of the question I think we can attack the problem having a parent and a children.

What am I trying to accomplish

Having a form that works like this:

        User Id
        <input formControlName="userId">

        Dummy
        <input formControlName="dummyInput">

This requires having a class like this:

private userForm: FormGroup;
constructor(private fb: FormBuilder){
    this.createForm();
}
private createForm(): void{
    this.userForm = this.fb.group({
        userId: ["", Validators.required],
        dummyInput: "", Validators.required]
    });
}

This works as expected, but now I want to decouple the code, and put the "dummyInput" functionality in a separate, different component. This is where I get lost. This is what I tried, I think I'm not far from getting the answer, but I'm really out of ideas, I'm fairly new to the scene:

parent.component.html

        User Id
        <input formControlName="userId">

        <dummy></dummy>

parent.component.ts

private createForm(): void{
    this.userForm = this.fb.group({
    userId: ["", Validators.required],
    dummy: this.fb.group({
        dummyInput: ["", Validators.required]
    })
});

children.component.html

    Dummy Input:
    <input formControlName="dummyInput">

children.component.ts

private dummyGroup: FormGroup;

I know something is not right with the code, but I'm really in a roadblock. Any help would be aprreciated.

Thanks.


问:
Sorting a Google Query with Select and Where
This is my google sheet query:

```<code>=QUERY('Form responses 1'!A:AG,"select C,E,D+F,AF,I+J+K+O,M where toDate(B)= date '"&text(today()-1,"yyyy-mm-dd")&"' ",1)
</code>```

How do I sort the above by column C? I have tried both SORT BY and ORDER BY but it comes up with #Value!

Also, I would like to have the result of D+F-AF in a column. Again it comes up with #Value!

What am I doing wrong?

答:
From what I can see, you query looks fine apart from one thing.

Instead of where toDate(B), try using just where B.

We can't see your spreadsheet so it's hard to tell if that's exactly the problem, but it looks like it to me.

I've set up a similar spreadsheet to test, and this works just fine:

```<code>=QUERY('Form Responses 1'!A:D,"select A,B,C,D WHERE B = date '"&text(today()-1,"yyyy-mm-dd")&"' ORDER BY B",1)
</code>```

Body:
This is my google sheet query:

=QUERY('Form responses 1'!A:AG,"select C,E,D+F,AF,I+J+K+O,M where toDate(B)= date '"&text(today()-1,"yyyy-mm-dd")&"' ",1)

How do I sort the above by column C? I have tried both SORT BY and ORDER BY but it comes up with #Value!

Also, I would like to have the result of D+F-AF in a column. Again it comes up with #Value!

What am I doing wrong?

Body:
From what I can see, you query looks fine apart from one thing.

Instead of where toDate(B), try using just where B.

We can't see your spreadsheet so it's hard to tell if that's exactly the problem, but it looks like it to me.

I've set up a similar spreadsheet to test, and this works just fine:

=QUERY('Form Responses 1'!A:D,"select A,B,C,D WHERE B = date '"&text(today()-1,"yyyy-mm-dd")&"' ORDER BY B",1)


问:
Get URL As Shown In Address Bar
I'm using some URL rewriting, on top of the URL rewriting that Wordpress does natively.

The basic idea is that I use a category page with an address that appears like it belongs somewhere else, so /blog/type/kids is the true category in WP. I rewrite this with a .htaccess file in /kids/ to make the category look like its actually a page called /kids/programs with this code in the kids folder:

```<code>RewriteEngine on
RewriteRule ^programs$ /blog/type/kids/ [P]
</code>```

This happens in two different locations in the site, but the both load the same WP page behind the scenes. This all works fine.

What I need to do now, is set a variable based on which location it is being loaded from, to ensure that the navigation highlights the proper section of the site, and shows the proper subnav. The problem is that I can't access the new, rewritten URL that the user sees.

Ideally, I'm looking for something like this:

```<code>if(strpos($_SERVER['PHP_SELF'],'kids//programs')) {
    $top_nav_item_id = 'kids';
} else {
    $top_nav_item_id = 'programs';
    $subnav_item_id = 'kids';
}
</code>```

PHP_SELF resolves to /blog/index.php and REQUEST_URI shows /blog/type/kids. So neither are showing me the /kids/programs location that is truly being displayed.

Any ideas how to get this? Maybe WP has a built in tag for this?

Cheers!

答:
The WordPress get_permalink() function is fully described at http://codex.wordpress.org/Function_Reference/get_permalink. Here is the usage:

```<code><?php echo get_permalink( $id ); ?>
</code>```

Since you are operating outside the loop, as you mentioned, you cannot just call get_permalink(), you have to pass the $id to the function. You could set the value of $id from inside the loop, and then use ISSET($id) — to be safe — before calling get_permalink($id).

If there are any issues after trying that with get_permalink (I was able to test it outside the loop, but I don't have a setup with your mod_rewrite rules), you could use still set $id from inside the loop and then manually construct the URL with the category using something like this, concatenated after 'http://yourservername/':

```<code><?php if(ISSET($specpostid)) {
  $catarray = get_the_category($id);
  echo $catarray[0]->cat_name; } ?>
</code>```

Title: Get URL As Shown In Address Bar

Body:
I'm using some URL rewriting, on top of the URL rewriting that Wordpress does natively.

The basic idea is that I use a category page with an address that appears like it belongs somewhere else, so /blog/type/kids is the true category in WP. I rewrite this with a .htaccess file in /kids/ to make the category look like its actually a page called /kids/programs with this code in the kids folder:

RewriteEngine on
RewriteRule ^programs$ /blog/type/kids/ [P]

This happens in two different locations in the site, but the both load the same WP page behind the scenes. This all works fine.

What I need to do now, is set a variable based on which location it is being loaded from, to ensure that the navigation highlights the proper section of the site, and shows the proper subnav. The problem is that I can't access the new, rewritten URL that the user sees.

Ideally, I'm looking for something like this:

if(strpos($_SERVER['PHP_SELF'],'kids//programs')) {
    $top_nav_item_id = 'kids';
} else {
    $top_nav_item_id = 'programs';
    $subnav_item_id = 'kids';
}

PHP_SELF resolves to /blog/index.php and REQUEST_URI shows /blog/type/kids. So neither are showing me the /kids/programs location that is truly being displayed.

Any ideas how to get this? Maybe WP has a built in tag for this?

Cheers!

Body:
The WordPress get_permalink() function is fully described at http://codex.wordpress.org/Function_Reference/get_permalink. Here is the usage:

<?php echo get_permalink( $id ); ?>

Since you are operating outside the loop, as you mentioned, you cannot just call get_permalink(), you have to pass the $id to the function. You could set the value of $id from inside the loop, and then use ISSET($id) — to be safe — before calling get_permalink($id).

If there are any issues after trying that with get_permalink (I was able to test it outside the loop, but I don't have a setup with your mod_rewrite rules), you could use still set $id from inside the loop and then manually construct the URL with the category using something like this, concatenated after 'http://yourservername/':

<?php if(ISSET($specpostid)) {
  $catarray = get_the_category($id);
  echo $catarray[0]->cat_name; } ?>


问:
xlsread in Matlab returns NaN even there is no data in Excel
I use xlsread to read a xlsx file. I expect the rawdata will return a 34x3 cell array.

```<code>[raw_num raw_txt rawdata]=xlsread('file.xlsx');
</code>```

The raw_num and raw_txt return correct value, 34x1 cell array and 34x2 cell array.

However, when I check rawdata, it returns 139x6 cell array. It contains not only data in excel file but also NaN element. For the NaN element, there is no data in excel file. I can only assume that I might type something before and then I delete it. But why matlab read it?

The rawdata looks like this:

'a' 'b' 'c' NaN NaN

'd' 'e' 'f' NaN NaN

NaN NaN NaN NaN NaN

How can I avoid this when I use xlsread?

Or how can I remove NaN after I got this matrix?

Thanks for help

答:
If NaN elements are only at the edges of the matrix like shown in your example, you could first remove rows with all NaN, then remove the columns with all NaN.

```<code>% test data
A = {NaN, NaN, NaN, NaN; NaN, NaN, NaN, NaN; NaN, NaN, NaN, NaN};
A{1, 1} = 'a';
A{1, 2} = 'b';
A{2, 1} = 'c';
A{2, 2} = 'd';

fh = @(x) all(isnan(x));
% remove rows with all NaN
A(all(cellfun(fh, A),2),:) = [];
% remove columns with all NaN
A(:,all(cellfun(fh, A),1)) = [];
</code>```

The reason you have to do it this way is because cellfun does not preserve dimensions, so you have to run it on each dimension individually. Alternatively, you could write a for loop.

Body:
I use xlsread to read a xlsx file. I expect the rawdata will return a 34x3 cell array.

[raw_num raw_txt rawdata]=xlsread('file.xlsx');

The raw_num and raw_txt return correct value, 34x1 cell array and 34x2 cell array.

However, when I check rawdata, it returns 139x6 cell array. It contains not only data in excel file but also NaN element. For the NaN element, there is no data in excel file. I can only assume that I might type something before and then I delete it. But why matlab read it?

The rawdata looks like this:

'a' 'b' 'c' NaN NaN

'd' 'e' 'f' NaN NaN

NaN NaN NaN NaN NaN

How can I avoid this when I use xlsread?

Or how can I remove NaN after I got this matrix?

Thanks for help

Body:
If NaN elements are only at the edges of the matrix like shown in your example, you could first remove rows with all NaN, then remove the columns with all NaN.

% test data
A = {NaN, NaN, NaN, NaN; NaN, NaN, NaN, NaN; NaN, NaN, NaN, NaN};
A{1, 1} = 'a';
A{1, 2} = 'b';
A{2, 1} = 'c';
A{2, 2} = 'd';

fh = @(x) all(isnan(x));
% remove rows with all NaN
A(all(cellfun(fh, A),2),:) = [];
% remove columns with all NaN
A(:,all(cellfun(fh, A),1)) = [];

The reason you have to do it this way is because cellfun does not preserve dimensions, so you have to run it on each dimension individually. Alternatively, you could write a for loop.


问:
Angular: Disable Change Detector for an entire class (service or component)
Is there a way to completely disable Angular's change detector if events that normally cause the change detection to run (setTimeout, setInterval, browser events, ajax calls etc..), are coming from a specific class (service or component)?

Namely, it seemed totally wrong to me when I found out that the setInterval registered in my service causes the global change detection to run every second..

I'm aware I can wrap my code inside the NgZone.runOutsideAngular method's callback, but I'd prefer the solution where the change detector can be disabled for an entire class, as I have other chunks of code within the service that are needlessly running the detection too.

Thanks for your help.

答:
One possible solution might be the following @RunOutsideAngular decorator for your service:

```<code>declare let Zone: any;

export function RunOutsideAngular(target: any) {
  Object.getOwnPropertyNames(target.prototype)
    .filter(p => typeof target.prototype[p] === 'function')
    .forEach(p => {
      let originalMethod = target.prototype[p];
      target.prototype[p] = function (...args) {
        let self = this;
        Zone.root.run(() => originalMethod.apply(self, args));
      }
    });

  let ctor: any = function (...args) {
    let self = this;
    return Zone.root.run(() => target.apply(self, args));
  };
  ctor.prototype = target.prototype;
  return ctor;
}
</code>```

Plunker Example

If you want to disable only setTimeout and setInterval within some class you can patch these functions

```<code>function patchTimers(timers: any[]) {
    timers.forEach((timer) => {
        let originalMethod = window[timer];
        window[timer] = function (...args) {
            let self = this;
            if (Zone.current['__runOutsideAngular__'] === true && Zone.current.name === 'angular') {
                Zone.root.run(() => originalMethod.apply(self, args));
            } else {
                originalMethod.apply(this, arguments);
            }
        };
    })
}
patchTimers(['setTimeout', 'setInterval']);
</code>```

and create decorator like this

```<code>export function RunOutsideAngular(target: any) {
    Object.getOwnPropertyNames(target.prototype)
        .filter(p => typeof target.prototype[p] === 'function')
        .forEach(p => {
            let originalMethod = target.prototype[p];
            target.prototype[p] = function (...args) {
                Zone.current['__runOutsideAngular__'] = true;
                originalMethod.apply(this, args);
                delete Zone.current['__runOutsideAngular__'];
            }
        });

    let ctor: any = function (...args) {
        Zone.current['__runOutsideAngular__'] = true;
        let instance = target.apply(this, args);
        delete Zone.current['__runOutsideAngular__'];
        return instance;
    };
    ctor.prototype = target.prototype;
    return ctor;
}
</code>```

Then you can use it as follows

```<code>@RunOutsideAngular
export class Service {
  constructor() {
    setInterval(() => {
      console.log('ctor tick');
    }, 1000);
  }

  run() {
    setTimeout(() => {
      console.log('tick');
    }, 1000);

    setInterval(() => {
      console.log('tick interval');
    }, 1000)
  }
}
</code>```

Plunker Example

Body:
One possible solution might be the following @RunOutsideAngular decorator for your service:

declare let Zone: any;

export function RunOutsideAngular(target: any) {
  Object.getOwnPropertyNames(target.prototype)
    .filter(p => typeof target.prototype[p] === 'function')
    .forEach(p => {
      let originalMethod = target.prototype[p];
      target.prototype[p] = function (...args) {
        let self = this;
        Zone.root.run(() => originalMethod.apply(self, args));
      }
    });

  let ctor: any = function (...args) {
    let self = this;
    return Zone.root.run(() => target.apply(self, args));
  };
  ctor.prototype = target.prototype;
  return ctor;
}

Plunker Example

If you want to disable only setTimeout and setInterval within some class you can patch these functions

function patchTimers(timers: any[]) {
    timers.forEach((timer) => {
        let originalMethod = window[timer];
        window[timer] = function (...args) {
            let self = this;
            if (Zone.current['__runOutsideAngular__'] === true && Zone.current.name === 'angular') {
                Zone.root.run(() => originalMethod.apply(self, args));
            } else {
                originalMethod.apply(this, arguments);
            }
        };
    })
}
patchTimers(['setTimeout', 'setInterval']);

and create decorator like this

export function RunOutsideAngular(target: any) {
    Object.getOwnPropertyNames(target.prototype)
        .filter(p => typeof target.prototype[p] === 'function')
        .forEach(p => {
            let originalMethod = target.prototype[p];
            target.prototype[p] = function (...args) {
                Zone.current['__runOutsideAngular__'] = true;
                originalMethod.apply(this, args);
                delete Zone.current['__runOutsideAngular__'];
            }
        });

    let ctor: any = function (...args) {
        Zone.current['__runOutsideAngular__'] = true;
        let instance = target.apply(this, args);
        delete Zone.current['__runOutsideAngular__'];
        return instance;
    };
    ctor.prototype = target.prototype;
    return ctor;
}

Then you can use it as follows

@RunOutsideAngular
export class Service {
  constructor() {
    setInterval(() => {
      console.log('ctor tick');
    }, 1000);
  }

  run() {
    setTimeout(() => {
      console.log('tick');
    }, 1000);

    setInterval(() => {
      console.log('tick interval');
    }, 1000)
  }
}

Plunker Example


问:
MySQL using "-" as different
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

```<code>delete from <table> where id - 145;
</code>```

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?

答:
the minus over there acted as a "not equal" operator.

More or less. It doesn't work the same for strings.

The content of the WHERE clause is a condition. As the documentation of DELETE explains:

where_condition is an expression that evaluates to true for each row to be deleted. It is specified as described in Section 13.2.9, "SELECT Syntax".

The linked page says:

In the WHERE expression, you can use any of the functions and operators that MySQL supports, except for aggregate (summary) functions. See Section 9.5, "Expression Syntax", and Chapter 12, Functions and Operators.

id - 145 is a valid numeric expression. It evaluates to various (integer) numbers.

When it is used as WHERE condition, its value is converted to boolean.

The section 12.3.3 Logical Operators says:

MySQL evaluates any nonzero, non-NULL value to TRUE.

For all rows having id != 145, the expression id - 145 is evaluated to a nonzero, non-NULL integer number that is treated as TRUE in logical context (in a WHERE condition f.e.)

To answer your question: yes, it is supposed to happen this way. It is not a MySQL bug, it is a bug in your query (or a typo if you like it more this way).

Title: MySQL using "-" as different

Body:
It's not really a question, I already found out the answer the hard way.
The problem is with the following query.

delete from
 where id - 145;

Having minus instead of equals was clearly a typo. The database's autocommit was turned on and I ended up deleting all the entries in the table except those with the id = 145. So the minus over there acted as a "not equal" operator.

I searched for similar situations and looked for this operator in the MySQL docs and I couldn't find anything.

Is this supposed to happen this way? Is it normal or a MySQL bug?


问:
WordPress running on localhost
"An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums."
Trying to run WordPress on localhost.
WP displays above error message when trying to install new plugins, adding a new theme.
Tried

```<code> 1)Disabled all plugins and then reactivating them

 2)reinstalled WP

 3)define('WP_HTTP_BLOCK_EXTERNAL', true); in wp-config.php

 4)site URL is not left blank

 5)Validated that the filesystem allows WordPress to write to the WordPress directories.
</code>```

debug.log

答: Please refer this link for a solution on wordpress support forum. There are few alternatives to resolve this issue. It depends on the cause of an issue.</p>

Title: WordPress running on localhost

Body:
"An unexpected error occurred. Something may be wrong with WordPress.org or this server’s configuration. If you continue to have problems, please try the support forums."
Trying to run WordPress on localhost.
WP displays above error message when trying to install new plugins, adding a new theme.
Tried

 1)Disabled all plugins and then reactivating them

 2)reinstalled WP

 3)define('WP_HTTP_BLOCK_EXTERNAL', true); in wp-config.php

 4)site URL is not left blank

 5)Validated that the filesystem allows WordPress to write to the WordPress directories.

debug.log


问:
Time complexity of only accessing rows in a matrix
while accessing all elements of a matrix we can use to for loops and time complexity is O(n^2).
But, when we are only accessing rows from a 2D array, what is the time complexity? Is it O(n) when n = number of rows?
Ex:-

```<code>int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)
</code>```

The time complexity for the above lines is O(n^2).

But if we access the matrix in the following way will the time complexity still be O(n^2) or will it be O(n)

```<code>for (int rows[] : arr) - Time complexity is O(n) or O(n^2)
</code>```

答:
If you are going to iterate all cells for each row, so it still be O(n^2).
There is no real difference between those two methods when considering run time.</p>

Body:
while accessing all elements of a matrix we can use to for loops and time complexity is O(n^2).
But, when we are only accessing rows from a 2D array, what is the time complexity? Is it O(n) when n = number of rows?
Ex:-

int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < arr.length; i++)
  for (int j = 0; j < arr[0].length; j++)

The time complexity for the above lines is O(n^2).

But if we access the matrix in the following way will the time complexity still be O(n^2) or will it be O(n)

for (int rows[] : arr) - Time complexity is O(n) or O(n^2)


问:
What is more efficient in terms of data consumption. GET or POST?
Assuming we want to send the some data from a device (IOT) to our server. Small no. of variables (say 10 to 20) but updated per second.
So sent to the server a large no. of times. (Say 60 times a minute)
What should I use so that minimum of my data pack is used. (Sending using GPRS)
GET or POST?</p>

答:
Well technically and according to multiple answers in this question :
When do you use POST and when do you use GET?

GET is generally used to retrieve data from a server and POST to submit data to a server. So in your use case you might want to use POST instead of GET.

But generally POST is slower and would be bigger in size than a GET request. That is if the data send in both requests is identical.


问:
Same function name in javascript (Nested function and outside function )
I have a function as below.
My Problem is that I need to print function b() inside a function. Here function a() is parent function. and I have done it by taking c= new a() and console.log(b()) . I got the right value as I expected. But inside the parent function I have another function named test() and with same name there is another function outside the parent function. After printing function b() I call the function test() . But it return the value from the parent function. I need to get an alert as needed answer which is in outer function. Is there any way to get my expected result without changing the function name.? Both functions test() are needed.

Expected result:  function b() =  2 and function test() = needed answer

Current result :  function b() =  2 and function test() = 4

Any help will be appreciated. Thank You.

function a() {
 var val = 1;
 var otherval = 2;

        b = function() {
  return val + 1;
        }

        test = function() {
           qwerty = otherval + b();
           alert(qwerty);
        }

   return 'OK';
 }

function test(){
    alert('needed answer');
}

c = new a();
console.log(b()); //return 2
test(); //alert 4 but I needed alert needed answer```

答:
As Rajesh Pointed out, declaring a function without using var will make it a global variable. Use var before test function to get expected value. But this will make it inaccessible outside the function a(). For that, assign the functions to this object and access then as shown below.

function a() {
 var val = 1;
 var otherval = 2;
    this.b = function() {  //prepend this
     return val + 1;
    }
    this.test = function() {  //prepend this
        qwerty = otherval + b();
        alert(qwerty);
    }
    return 'OK';
}

function test(){
 alert('needed answer');
}

c = new a();
console.log(c.b()); //return 2
test(); //alert 4```


问:
Using primary keys with grid data and jQuery Templates
What is the best way to associate a primary key with a table row when using client-side templates, like jQuery Templates?

Should I do some kind of data binding or something?  Or should I embed and hide the id in the table like this:

```<code><script id="contactsTemplate" type="text/x-jquery-tmpl">
  <table class="contacts">
    <thead><tr><td class="ui-helper-hidden">Id</td><td>Name</td><td>City</td><td>State</td></tr></thead>
    <tbody>
    {{each contact}}
        {{tmpl($value) '#contactTemplate'}}
    {{/each}}
    </tbody>
  </table>
</script>

<script id="contactTemplate" type="text/x-jquery-tmpl">
    <tr><td class="ui-helper-hidden">${id}</td><td>${name}</td><td>${city}</td><td>${state}</td></tr>
</script>
</code>```

Isn't it bad to have my Ids accessible to the user, even if they are hidden?  What other options do I have?

答:
Use an HTML5 custom data attribute, like so

...

For more on HTML5 custom data attributes, see

Do HTML5 custom data attributes “work” in IE 6?

http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data-with-the-data-attributes

http://ejohn.org/blog/html-5-data-attributes/

http://html5doctor.com/html5-custom-data-attributes/

http://www.marcofolio.net/webdesign/html5_data-_attributes_are_great_and_you_know_it.html

Body:
What is the best way to associate a primary key with a table row when using client-side templates, like jQuery Templates?

Should I do some kind of data binding or something?  Or should I embed and hide the id in the table like this:

Isn't it bad to have my Ids accessible to the user, even if they are hidden?  What other options do I have?

Body:
Use an HTML5 custom data attribute, like so

<tr data-id="${id}">...</tr>

For more on HTML5 custom data attributes, see

Do HTML5 custom data attributes “work” in IE 6?

http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data-with-the-data-attributes

http://ejohn.org/blog/html-5-data-attributes/

http://html5doctor.com/html5-custom-data-attributes/

http://www.marcofolio.net/webdesign/html5_data-_attributes_are_great_and_you_know_it.html


问:
Ho to use Ubuntu's tomcat8-user package with IntelliJ Idea?
I am working with Ubuntu and would like to develop tomcat applications with IntelliJ IDEA.

I installed tomcat8-user and created an instance:

sudo apt-get install tomcat8-user
tomcat8-instance-create /home/myhome/tomcat
```

However when I try to configure tomcat in IDEA I just get the message "The selected directory is not a valid Tomcat home":

When I click "OK" nevertheless I get the error "Application server libraries not found":

What is the problem? How can I fix that?

答:
I have also encountered the same problem when I try to configure tomcat in IDEA. I tried the previous answer method, but failed.Here's my way.

The message "The selected directory is not a valid Tomcat home"
Because IDEA can not access the files in the folder,one solution is using the "chmod" command change all of subdirectories' permissions.

Go to the directory which you install the Tomcat:

cd /opt/tomcat/apache-tomcat-8.5.15

Using the command change the permissions.

sudo chmod 777 * -R

Body:
I am working with Ubuntu and would like to develop tomcat applications with IntelliJ IDEA.

I installed tomcat8-user and created an instance:

sudo apt-get install tomcat8-user
tomcat8-instance-create /home/myhome/tomcat

However when I try to configure tomcat in IDEA I just get the message "The selected directory is not a valid Tomcat home":

When I click "OK" nevertheless I get the error "Application server libraries not found":

What is the problem? How can I fix that?


问:
Import file having different format in alternate rows
I need to load 1 file using SSIS.
I am getting csv file of PIPE (|) delimited. but between every data row I am getting 1 row having only "-----------". If i try to load file as a PIPE delimited than i am not getting proper records.

I have 1 solution is I need to load entire row into single column, than i need to filter rows having "----", than i need to use transformation and split rows into columns. But it will be difficult to manage in case of changes.

Can anyone please give anyother Idea to load such files ?

答: After this , i found solution is to read file in "ragged right" format.than filter out the records starting with "--".</p>


问:
Excel formula vlookup
I need to fill in the column D using the information from column G (all in the first sheet) and the information from column A in the second sheet.

What needs to be returned to the column is the exact information found in the second sheet with the letter.

I have tried using vlookup with extract and other's but I always get N/A returned and im getting nervous.

Below are two screenshots of each sheet and at the bottom you will find an excel file uploaded with example data.

Excel file with example

答:
In 'ActiveCoupons' put in G2 : =RIGHT(A2,LEN(A2)-1)*1

In 'ActiveCoupons' put in H2 : =A2

Expand the formulas to the rest of the columns G,H

In CouponRedemptionResults put in D2: =VLOOKUP(G2,ActiveCoupons!G:H,2,0)

Expand the formula to the rest of the columns D

Title: Excel formula vlookup


问:
Web App HTML, JS + Google Apps Script: How to go back to my app after return in GAS?
I'm building a web app using HTML, CSS and JavaScript and using Google Spreadsheet as a database. I'm planning to use PhoneGap to turn my web app into a real app.

I was able to read from my Google Sheet, using the Google Visualization API, now I'm working about the writing options: I used a function set with Google Apps Script, inside the Google Spreadsheet and it works correctly.

This is how my app works and what I need:

I query my first Google Spreadsheet (Database)

If I cannot find what I need, I can make a request

I send the request: the action of the form send my data to the Google Apps Script code

The GAS writes my data in a second Google Spreadsheet (Register)

The GAS should send me back to my page

The page sends a feedback on screen

As you can understand by the bold point, I'm not able to go back to my webpages... I don't know if there's any method or function to do this. The only thing I found was using ContentServiceto make the page "write another form and send it using JavaScript", but I don't think is the best solution...

I'll post my code down here... hoping someone can help me

```<code>function doPost(e){
 var sheet = SpreadsheetApp.openById("myID").getSheetByName('SheetName');
 var column = 1;
 var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
 var maxi = Math.max.apply(Math, colArray);

  var id = maxi+1;
  var name = e.parameter['name'];
  var surname = e.parameter['surname'];
  var serial = e.parameter['serial'];
  var eMail = e.parameter['mail'];
  var text = e.parameter['text'];
  var area = e.parameter['area'];
  var date = new Date();
  var ans = ""
  var flag = "Work In Progress";

  var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];

  var sheetObj = sheet.appendRow(vals);

  // return ContentService.createTextOutput(someOutput);
</code>```

On the return line I should go back to my web app/app but I can't find a way to do it. Someone can help me or give me some advice?

Thanks a lot for your help!

S.

答:
This is the solution to your problem.

Instead of using return ContentService.createTextOutput(someOutput);

use HtmlService to return to your form

```<code>return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);
</code>```

And your HTML file should look like this,

Update: redirect.html should be in the same project as that of your app script file.

redirect.html

```<code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<title>This Is A Sample Title</title>
<script>
function test()
{
    window.location.href = "www.hostname.com";
}
</script>
</head>
<body onload="test()">
Login
</body>
</html>
</code>```

See if this works for you.

Body:
I'm building a web app using HTML, CSS and JavaScript and using Google Spreadsheet as a database. I'm planning to use PhoneGap to turn my web app into a real app.

I was able to read from my Google Sheet, using the Google Visualization API, now I'm working about the writing options: I used a function set with Google Apps Script, inside the Google Spreadsheet and it works correctly.

This is how my app works and what I need:

I query my first Google Spreadsheet (Database)

If I cannot find what I need, I can make a request

I send the request: the action of the form send my data to the Google Apps Script code

The GAS writes my data in a second Google Spreadsheet (Register)

The GAS should send me back to my page

The page sends a feedback on screen

As you can understand by the bold point, I'm not able to go back to my webpages... I don't know if there's any method or function to do this. The only thing I found was using ContentServiceto make the page "write another form and send it using JavaScript", but I don't think is the best solution...

I'll post my code down here... hoping someone can help me

function doPost(e){
 var sheet = SpreadsheetApp.openById("myID").getSheetByName('SheetName');
 var column = 1;
 var colArray = sheet.getRange(2, column, sheet.getLastRow()).getValues();
 var maxi = Math.max.apply(Math, colArray);

  var id = maxi+1;
  var name = e.parameter['name'];
  var surname = e.parameter['surname'];
  var serial = e.parameter['serial'];
  var eMail = e.parameter['mail'];
  var text = e.parameter['text'];
  var area = e.parameter['area'];
  var date = new Date();
  var ans = ""
  var flag = "Work In Progress";

  var vals = [id, date, name, surname, serial, eMail, area, text, ans, flag];

  var sheetObj = sheet.appendRow(vals);

  // return ContentService.createTextOutput(someOutput);

On the return line I should go back to my web app/app but I can't find a way to do it. Someone can help me or give me some advice?

Thanks a lot for your help!

S.

Body:
This is the solution to your problem.

Instead of using return ContentService.createTextOutput(someOutput);

use HtmlService to return to your form

return HtmlService.createHtmlOutputFromFile('redirect').setSandboxMode(HtmlService.SandboxMode.IFRAME);

And your HTML file should look like this,

Update: redirect.html should be in the same project as that of your app script file.

redirect.html

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<title>This Is A Sample Title</title>
<script>
function test()
{
    window.location.href = "www.hostname.com";
}
</script>
</head>
<body onload="test()">
Login
</body>
</html>

See if this works for you.


问:
How to get the current products in cart in Magento?

I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

```<code>    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}
</code>```

答:
For that the best way is just create API User and Password from magento admin then use below code.</p>

```<code>$userName = 'API USER';
$key = 'API KEY';
$userId = 'USER ID';

$client = new SoapClient(Mage::getBaseUrl().'api/soap/?wsdl');
$session = $client->login($userName, $key);

$customer = Mage::getModel('customer/customer')->load($userId);
$quote = Mage::getSingleton('sales/quote')->loadByCustomer($customer);
$quoteId = $quote->getId();

$cartInfo = $client->call($session, 'cart.info', $quoteId);
foreach($cartInfo['items'] as $i=>$item)
{
    echo $item['product_id'];
    echo $item['sku'];
}
</code>```

Body:
I need to get the currently products in cart to estimate how many
  products are in ? I used the below code but it gave me this error
  message
  > Fatal error: Call to undefined method
  Mage_Sales_Model_Resource_Quote_Item_Collection::getAllItems()

Code:

    <?php

      require 'app/Mage.php';
      Mage::app();

     if (!Mage::isInstalled()) {
        echo "Application is not installed yet, please complete install wizard first.";

}

     $cart =Mage::getSingleton('checkout/cart')->getQuote()->getItemsCollection();
           foreach ($cart->getAllItems() as $item) {
                   $productName = $item->getProduct()->getName();
                   $productPrice = $item->getProduct()->getPrice();

          print($item);

}

Body:
For that the best way is just create API User and Password from magento admin then use below code.

$userName = 'API USER';
$key = 'API KEY';
$userId = 'USER ID';

$client = new SoapClient(Mage::getBaseUrl().'api/soap/?wsdl');
$session = $client->login($userName, $key);

$customer = Mage::getModel('customer/customer')->load($userId);
$quote = Mage::getSingleton('sales/quote')->loadByCustomer($customer);
$quoteId = $quote->getId();

$cartInfo = $client->call($session, 'cart.info', $quoteId);
foreach($cartInfo['items'] as $i=>$item)
{
    echo $item['product_id'];
    echo $item['sku'];
}


问:
VIM: Ruby methods with ? and ! in the end
I'm trying to use VIM completion (dictionary and current buffer), but i'm running into issues with ? and ! in the end of method names. Can i somehow explain to vim that method names (words basically) can have it only in the end and only one i.e. method_name? not bull???!!shit!? or if !xyz ... (when ? and ! added iskeyword !xyz exists in completion list). Any ideas how to do that?</p>

答:
IIRC, you have to modify the iskeywordoption.

You can try set iskeyword+=?,!so that ? and ! are considered as part of words and not separator.

In your .vimrc, you can add :

autocmd BufRead,BufNewFile *.rb set iskeyword+=?,!

See :help iskeywordfor more information.

Edit : I had not seen you had already mentioned iskeyword as a possible workaround.

Alternate idea :

1. Generate ctags for your ruby code.

2. in the complete option remove everything except the t option meaning tags only.

You are only going to have suggestions coming from the tag file. The downside is that it adds a new step to use completion and you will miss some non-tag completion.


问:
Why is npm giving 500 and 503 errors: "registry error parsing json"?
Trying to do npm install steroids -g and running into lots of errors of two types:

First: 500

```<code>npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/cardinal
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/glob
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/chmodr
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/fstream
npm ERR! registry error parsing json
</code>```

when I visit those urls in the browser I get the following message:

Internal routing error

Sorry, we cannot connect to the intended server.

We have just been notified of this problem. We will correct it as soon
  as possible.

Feel free to contact us if you have any questions:
  support@iriscouch.com

Second: 503

```<code>npm http 503 https://registry.npmjs.org/forever-agent
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/cheerio
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/request
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/diff
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/tar
</code>```

When I visit those urls in the browser I get this message:

Error 503 backend read error

backend read error

Guru Meditation:

XID: 1448084160

Varnish cache server

Does this mean the npm registry is down? or do I have strange behavior on my machine?

Running node v.0.10.24 & npm v.1.3.21

答:
npm has a status page where any server incidence will (should) be reflected:

https://status.npmjs.org

Body:
Trying to do npm install steroids -g and running into lots of errors of two types:

First: 500

npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/cardinal
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/glob
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/chmodr
npm ERR! registry error parsing json
npm http 500 https://registry.npmjs.org/fstream
npm ERR! registry error parsing json

when I visit those urls in the browser I get the following message:

Internal routing error

Sorry, we cannot connect to the intended server.

We have just been notified of this problem. We will correct it as soon
  as possible.

Feel free to contact us if you have any questions:
  support@iriscouch.com

Second: 503

npm http 503 https://registry.npmjs.org/forever-agent
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/cheerio
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/request
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/diff
npm ERR! registry error parsing json
npm http 503 https://registry.npmjs.org/tar

When I visit those urls in the browser I get this message:

Error 503 backend read error

backend read error

Guru Meditation:

XID: 1448084160

Varnish cache server

Does this mean the npm registry is down? or do I have strange behavior on my machine?

Running node v.0.10.24 & npm v.1.3.21


问:
R function to filter rows that have numbers in the same decade
Having the following matrix:

```<code>      [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
 [1,]   23   14   17   10     2     6    90    45    56     25     11      9
 [2,]    1   15   18   21     2    26    35    50    81     33     61     93
 [3,]    6   19   98   23    22     7     8    25    61     54     22     38
</code>```

I want to get only the rows that have no more than 3 numbers in the same decade.
so the result must be:

```<code>[1] False
[2] True
[3] False
</code>```

so finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards, Dimitris

Body:
Having the following matrix:

      [,1] [,2] [,3] [,4]  [,5]  [,6]  [,7]  [,8]  [,9]  [,10]  [,11]  [,12]
 [1,]   23   14   17   10     2     6    90    45    56     25     11      9
 [2,]    1   15   18   21     2    26    35    50    81     33     61     93
 [3,]    6   19   98   23    22     7     8    25    61     54     22     38

I want to get only the rows that have no more than 3 numbers in the same decade.
so the result must be:

[1] False
[2] True
[3] False

so finally we get only [2] that satisfies the condition. Can you please provide an R language function which can generate this result?

Regards, Dimitris

Body:
We can use apply

m1[!apply(m1, 1, FUN = function(x) any(table(x %/%10) > 3)), , drop = FALSE ]
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
#[1,]    1   15   18   21    2   26   35   50   81    33    61    93


问:
iOS build error: Certificate doesn't match profile: The default keychain doesn't have an identity matching
I'm trying to build my app on PhoneGap Build. Build works with Development certificate but not with Distribution certificate.
I get this error:

```<code>Error - Certificate doesn't match profile: The default keychain doesn't have an identity matching
</code>```

I already tried to re-generate a new provisioning file (.mobileprovision) from my Apple Developer panel, as said here
https://forums.adobe.com/thread/2183665

but it doesn't work. I don't know how to solve. Some helps?

EDIT: here a screenshot of my certificates

答: I got the same error message. My problem was that I uploaded the Developers and not the Distribution Certificate in PhoneGap. After replacing that in PhoneGap it worked.</p>

Body:
I'm trying to build my app on PhoneGap Build. Build works with Development certificate but not with Distribution certificate.
I get this error:

Error - Certificate doesn't match profile: The default keychain doesn't have an identity matching

I already tried to re-generate a new provisioning file (.mobileprovision) from my Apple Developer panel, as said here
https://forums.adobe.com/thread/2183665

but it doesn't work. I don't know how to solve. Some helps?

EDIT: here a screenshot of my certificates


问:
cursor in EditText hint does not start from right for Arabic
I'm trying to make EditText with a hint text:
In English "password" .. the cursor is correctly set to the left.
But for Arabic for which the hint is "كلمه المرور" the cursor is always set to the left (the end of the hint) instead of the right.

```<code><EditText
        android:id="@id/ETPass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/etUsrName"
        android:layout_marginLeft="@dimen/_25sdp"
        android:layout_marginRight="@dimen/_25sdp"
        android:layout_marginTop="@dimen/_5sdp"
        android:background="@drawable/signup_edittext_input"
        android:ellipsize="start"
        android:gravity="center|right"
        android:hint="@string/Password"
        android:imeOptions="actionNext"
        android:inputType="textPassword"
        android:paddingRight="@dimen/_5sdp"
        android:singleLine="true"
        android:textColor="@color/orange"
        android:textColorHint="@color/orange" />
</code>```

This happens only for android:inputType="textPassword" . Everything works fine for a normal text inputType.

答:
For Android 17 and higher(4.2.+) its working:</p>

```<code>android:textAlignment="viewStart"
</code>```

Body:
I'm trying to make EditText with a hint text:
In English "password" .. the cursor is correctly set to the left.
But for Arabic for which the hint is "كلمه المرور" the cursor is always set to the left (the end of the hint) instead of the right.

<EditText
        android:id="@id/ETPass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/etUsrName"
        android:layout_marginLeft="@dimen/_25sdp"
        android:layout_marginRight="@dimen/_25sdp"
        android:layout_marginTop="@dimen/_5sdp"
        android:background="@drawable/signup_edittext_input"
        android:ellipsize="start"
        android:gravity="center|right"
        android:hint="@string/Password"
        android:imeOptions="actionNext"
        android:inputType="textPassword"
        android:paddingRight="@dimen/_5sdp"
        android:singleLine="true"
        android:textColor="@color/orange"
        android:textColorHint="@color/orange" />

This happens only for android:inputType="textPassword" . Everything works fine for a normal text inputType.

Body:
For Android 17 and higher(4.2.+) its working:

android:textAlignment="viewStart"


问:
Spring JDBCTemplate vs Plain JDBC for inserting large numbers of records
We have to insert 2 millions of records across multiple tables and right now we are writing into a CSV file and using db2 import to load into database.

We wanted to change this logic to some kind of JDBC. While looking into multiple options, I am confused with Spring JDBC template and plain JDBC.

Let us say I wanted to insert 1 million records into 10 tables, each of which will have 100 thousand, and all these are simple JDBC statements (not prepared statements because I don't know which table I am dealing with at runtime).

Whatever system we choose will need to handle inserting up to 15 million records for a peak request.

Which framework will be better?

答: If you're already using Spring, then you may as well use JdbcTemplate. It makes things a bit easier, and in some simple cases means you need not use the JDBC API directly yourself.  Essentially, JdbcTemplate is a very thin wrapper around JDBC that removes some of your annoying boiler-plate code.


问:
how to publish angular 2 typescript library on npm
I have created a typescript library for angular 2 which facilitates the  to access my backend service.

So far it's a private repo, but I want to upload it as an open source library to github and register it on npm.

I'm not really sure what to do now, since documentation on this subject is not easy to find.

the folder structure looks like this:

```<code>src
|--sdk.ts // entry point
|--services
   |--auth.ts
   |--database.ts
   |--5 more ts files
|--utils
   |--utils.ts
   |--interfaces.ts
|--tests (8 ..spec.ts files)
</code>```

my entry point (sdk.ts) looks like this

```<code>import { NgModule, ModuleWithProviders } from '@angular/core';
import { Injectable } from '@angular/core';
import { SelfbitsDatabase } from './services/database';
import { SelfbitsAuth } from './services/auth';
import { SelfbitsAppConfig } from './utils/interfaces';
import { SelfbitsFile } from './services/file';
import { SelfbitsUser } from './services/user';
import { SelfbitsDevice } from './services/device';
import { SelfbitsPush } from './services/push';
import { HttpModule } from '@angular/http';

@Injectable()
export class SelfbitsAngular {
    constructor(
        public auth : SelfbitsAuth,
        public database : SelfbitsDatabase,
        public file : SelfbitsFile,
        public user : SelfbitsUser,
        public device: SelfbitsDevice,
        public push : SelfbitsPush
    ){}
}

export const SELFBITS_PROVIDERS:any[] = [
    SelfbitsAngular,
    SelfbitsAuth,
    SelfbitsDatabase,
    SelfbitsFile,
    SelfbitsUser,
    SelfbitsDevice,
    SelfbitsPush
];

@NgModule({
    providers:SELFBITS_PROVIDERS,
    imports:[ HttpModule ]
})

export class SelfbitsAngularModule{
    static initializeApp(config:SelfbitsAppConfig):ModuleWithProviders{
        return {
            ngModule:SelfbitsAngularModule,
            providers:[
                { provide: 'SelfbitsConfig', useValue: config }
            ]
        }
    }
}
</code>```

and here's the webpack.config.js which doesn't really do what I want...

```<code>module.exports = {
    entry:'./src/sdk.ts',
    output:{
        path: helpers.root('dist'),
        filename:'selfbitsangular2sdk.js'
    },
    resolve: {
        extensions: ['', '.js', '.ts']
    },

    module: {
        loaders: [
            {
                test: /\.ts$/,
                exclude:'/test/',
                loaders: ['ts-loader']
            }
        ]
    }
};
</code>```

I'm not sure if webpack is even the right choice..or wether is should be bundled and minified or not. Any hints and tipps are welcome!

Cheers

答:
The publishing process itself is pretty easy:

```<code># Login with your existing npm user
npm login

# Bump library version
npm version --patch

# Publish your library
npm publish
</code>```

The hardest part is to correctly prepare the content of your package.json and  the folder that will hold you build library (one of the common way to name it is dist).

Your dist folder should contain files that are ready to be consumed by Angular JIT projects as well as by Angular AOT projects. It is also should contain your library bundle that is ready to be consumed by the browser directly (let's say via SystemJS).

In a result your dist folder should contain the following files:

index.umd.js - UMD bundle that is ready for SystemJS consumption

index.umd.min.js - minified version of the bundle to save user's traffic

index.umd.js.map, index.umd.min.js.map - for debugging purpose

*.js — [produced by tsc, remember that ngc is a wrapper] compiled JavaScript representation of the component or service *.ts files of your library.

*.d.ts — [produced by tsc, remember that ngc is a wrapper] declaration files. Since *.ts files with types are being transpiled to *.js files that don’t support typings the TypeScript Compiler needs to put all types information to separate *.d.ts files in order to be able to use those *.js files in TypeScript projects later. By the way, there is a DefinitelyTyped project with a lot of type definitions that have been already contributed for a plenty of JS non-TypeScript libraries.

*.metadata.json — metadata associated with the current component (or NgModule). It is kind of JSON representation of the objects we pass to the @Component, @NgModule decorators. This file contains the information that project’s (not library’s) NGC will need that was in the original library *.ts files but was not included in the *.d.ts files.

In this case your package.json should be notified about your build files via main, module and typings fields:

```<code> {
   ...
   "main": "./dist/index.umd.js",
   "module": "./dist/index.js",
   "typings": "./dist/index.d.ts",
   ...
 }
</code>```

You may find more detailed description of what files should be in dist folder and how to compile them in How to create AOT/JIT compatible Angular 4 library with external SCSS/HTML templates article

Body:
I have created a typescript library for angular 2 which facilitates the  to access my backend service.

So far it's a private repo, but I want to upload it as an open source library to github and register it on npm.

I'm not really sure what to do now, since documentation on this subject is not easy to find.

the folder structure looks like this:

src
|--sdk.ts // entry point
|--services
   |--auth.ts
   |--database.ts
   |--5 more ts files
|--utils
   |--utils.ts
   |--interfaces.ts
|--tests (8 ..spec.ts files)

my entry point (sdk.ts) looks like this

import { NgModule, ModuleWithProviders } from '@angular/core';
import { Injectable } from '@angular/core';
import { SelfbitsDatabase } from './services/database';
import { SelfbitsAuth } from './services/auth';
import { SelfbitsAppConfig } from './utils/interfaces';
import { SelfbitsFile } from './services/file';
import { SelfbitsUser } from './services/user';
import { SelfbitsDevice } from './services/device';
import { SelfbitsPush } from './services/push';
import { HttpModule } from '@angular/http';

@Injectable()
export class SelfbitsAngular {
    constructor(
        public auth : SelfbitsAuth,
        public database : SelfbitsDatabase,
        public file : SelfbitsFile,
        public user : SelfbitsUser,
        public device: SelfbitsDevice,
        public push : SelfbitsPush
    ){}
}

export const SELFBITS_PROVIDERS:any[] = [
    SelfbitsAngular,
    SelfbitsAuth,
    SelfbitsDatabase,
    SelfbitsFile,
    SelfbitsUser,
    SelfbitsDevice,
    SelfbitsPush
];

@NgModule({
    providers:SELFBITS_PROVIDERS,
    imports:[ HttpModule ]
})

export class SelfbitsAngularModule{
    static initializeApp(config:SelfbitsAppConfig):ModuleWithProviders{
        return {
            ngModule:SelfbitsAngularModule,
            providers:[
                { provide: 'SelfbitsConfig', useValue: config }
            ]
        }
    }
}

and here's the webpack.config.js which doesn't really do what I want...

module.exports = {
    entry:'./src/sdk.ts',
    output:{
        path: helpers.root('dist'),
        filename:'selfbitsangular2sdk.js'
    },
    resolve: {
        extensions: ['', '.js', '.ts']
    },

    module: {
        loaders: [
            {
                test: /\.ts$/,
                exclude:'/test/',
                loaders: ['ts-loader']
            }
        ]
    }
};

I'm not sure if webpack is even the right choice..or wether is should be bundled and minified or not. Any hints and tipps are welcome!

Cheers

Body:
The publishing process itself is pretty easy:

# Login with your existing npm user
npm login

# Bump library version
npm version --patch

# Publish your library
npm publish

The hardest part is to correctly prepare the content of your package.json and  the folder that will hold you build library (one of the common way to name it is dist).

Your dist folder should contain files that are ready to be consumed by Angular JIT projects as well as by Angular AOT projects. It is also should contain your library bundle that is ready to be consumed by the browser directly (let's say via SystemJS).

In a result your dist folder should contain the following files:

index.umd.js - UMD bundle that is ready for SystemJS consumption

index.umd.min.js - minified version of the bundle to save user's traffic

index.umd.js.map, index.umd.min.js.map - for debugging purpose

*.js — [produced by tsc, remember that ngc is a wrapper] compiled JavaScript representation of the component or service *.ts files of your library.

*.d.ts — [produced by tsc, remember that ngc is a wrapper] declaration files. Since *.ts files with types are being transpiled to *.js files that don’t support typings the TypeScript Compiler needs to put all types information to separate *.d.ts files in order to be able to use those *.js files in TypeScript projects later. By the way, there is a DefinitelyTyped project with a lot of type definitions that have been already contributed for a plenty of JS non-TypeScript libraries.

*.metadata.json — metadata associated with the current component (or NgModule). It is kind of JSON representation of the objects we pass to the @Component, @NgModule decorators. This file contains the information that project’s (not library’s) NGC will need that was in the original library *.ts files but was not included in the *.d.ts files.

In this case your package.json should be notified about your build files via main, module and typings fields:

 {
   ...
   "main": "./dist/index.umd.js",
   "module": "./dist/index.js",
   "typings": "./dist/index.d.ts",
   ...
 }

You may find more detailed description of what files should be in dist folder and how to compile them in How to create AOT/JIT compatible Angular 4 library with external SCSS/HTML templates article