问:
Laravel 5: Ajax Post 500 (Internal Server Error)
I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:

POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)

What's wrong with my code? Is it the javascript or the controller?

EDIT: I'm getting this in laravel.log

exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53

Route

```<code>Route::resource('articles', 'ArticlesController');
</code>```

Controller

```<code>public function store(Requests\ArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Article has been posted.',
        );
        return \Response::json($response);
    }
</code>```

jQuery

```<code>$(document).ready(function() {
    $('#frm').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/laravel-5/public/articles/create',
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                console.log(data);
            }
        });
    });
</code>```

View

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

<h1>Write a New Article</h1>

<hr>

{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
    <p>
        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}
    </p>

    <p>
        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}
    </p>

    <p>
        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
    </p>

    <p>
        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}
    </p>
{!! Form::close() !!}

<h3 id="ajaxResponse"></h3>

@if($errors->any())
    <ul>
    @foreach($errors->all() as $error)
        <li>{{ $error }}</li>
    @endforeach
    </ul>
@endif

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
</code>```

});

答:
Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,

```<code><h6>ITEMS  ORDERED:<a href="#" id="{{$post->identifier}}" onclick="getcart(this.id)">CLICK HERE</a></h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
</code>```

Now With Ajax

```<code><script type="text/javascript">
function getcart(val) {
  var alpha=val;
var token=document.getElementById('token').value;

$.ajax({
 type:'post',
 url:'/private/getcart',
 data:{'alpha':alpha,'_token': token},//this _token should be as it is
 success:function (result) {
alert(result);
 }

});

}

</script>
</code>```

In my laravel controller

```<code>public function getcart(Request $req)
{
  return response ("its");
}
</code>```

Body:
I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:

POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)

What's wrong with my code? Is it the javascript or the controller?

EDIT: I'm getting this in laravel.log

exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53

Route

Route::resource('articles', 'ArticlesController');

Controller

public function store(Requests\ArticleRequest $request)
    {

        $article = new Article($request->all());
        Auth::user()->articles()->save($article);

        $response = array(
            'status' => 'success',
            'msg' => 'Article has been posted.',
        );
        return \Response::json($response);
    }

jQuery

$(document).ready(function() {
    $('#frm').on('submit', function (e) {
        e.preventDefault();
        var title = $('#title').val();
        var body = $('#body').val();
        var published_at = $('#published_at').val();
        $.ajax({
            type: "POST",
            url: 'http://localhost/laravel-5/public/articles/create',
            dataType: 'JSON',
            data: {title: title, body: body, published_at: published_at},
            success: function( data ) {
                $("#ajaxResponse").append(data.msg);
                console.log(data);
            }
        });
    });

View

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

Write a New Article

{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}

        {!! Form::label('title', 'Title:') !!}
        {!! Form::text('title') !!}

        {!! Form::label('body', 'Body:') !!}
        {!! Form::textarea('body') !!}

        {!! Form::label('published_at', 'Date:') !!}
        {!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}

        {!! Form::submit('Submit Article', ['id' => 'submit']) !!}

{!! Form::close() !!}

@if($errors->any())

    @foreach($errors->all() as $error)

{{ $error }}

    @endforeach

@endif

});

Body:
Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,

<h6>ITEMS  ORDERED:<a href="#" id="{{$post->identifier}}" onclick="getcart(this.id)">CLICK HERE</a></h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">

Now With Ajax

<script type="text/javascript">
function getcart(val) {
  var alpha=val;
var token=document.getElementById('token').value;

$.ajax({
 type:'post',
 url:'/private/getcart',
 data:{'alpha':alpha,'_token': token},//this _token should be as it is
 success:function (result) {
alert(result);
 }

});

}

</script>

In my laravel controller

public function getcart(Request $req)
{
  return response ("its");
}


来源: stackexchange

问:
Maven: How to create a correct JDBC driver dependency, if I don't know which database the client will use?
I'm currently learning to use maven, I understood how to create a maven project using dependencies from maven repository - and now I have the following question:

If I have an application which uses a database access, for example via Hibernate, then I need to add a dependency representing the corresponding database driver, for example mysql-connector-java for MySql, ojdbc for Oracle and so on.

But what if I want the program to run on a different machine and I don't know what database engine it uses? What is the common way to solve this? Just import all possible drivers as dependencies? Or is there a more elegant way?

答:
The problem is not particularly maven bound. Whenever you move to a new database, the administrator would have to use the correct JDBC driver according to DB, and yes, it requires different jar files.

The thing is, that you don't want to bundle the database jar file with your code. It may already exist (e.g. in the application server) or you may specify a path to drop it during installation.

Assuming you are creating a webapp. If you bundle a war-file with maven, it will include all dependencies inside the war file, so you must specify that the dependency is there during compilation and testing, but not in any package. The way to do so, is by specifying it as provided

```<code><dependency>
  <groupId>some.db</groupId>
  <artifactId>jdbc-driver<artifactId>
  <scope>provided</scope>
</dependency>
</code>```

This means that the jar file will exist on the target platform, and hence, should not be packaged in a any bundle.

So the assumption I make is really, is this a web-app? Or is it standalone? Anyway, hope it helps.

ContentLicense: CC BY-SA 3.0

Body:
The problem is not particularly maven bound. Whenever you move to a new database, the administrator would have to use the correct JDBC driver according to DB, and yes, it requires different jar files.

The thing is, that you don't want to bundle the database jar file with your code. It may already exist (e.g. in the application server) or you may specify a path to drop it during installation.

Assuming you are creating a webapp. If you bundle a war-file with maven, it will include all dependencies inside the war file, so you must specify that the dependency is there during compilation and testing, but not in any package. The way to do so, is by specifying it as provided

<dependency>
  <groupId>some.db</groupId>
  <artifactId>jdbc-driver<artifactId>
  <scope>provided</scope>
</dependency>

This means that the jar file will exist on the target platform, and hence, should not be packaged in a any bundle.

So the assumption I make is really, is this a web-app? Or is it standalone? Anyway, hope it helps.


问:
Get LatLong from HashMap in Java
```<code>static final HashMap<String, LatLng> BAY_AREA_LANDMARKS = new HashMap<String, LatLng>();

static {
    // Office Location.
    BAY_AREA_LANDMARKS.put("Office", new LatLng(  31.112635, 73.114867));
    // House Location.
    BAY_AREA_LANDMARKS.put("Home", new LatLng(  31.138056, 73.108787));
    //College Location.
    BAY_AREA_LANDMARKS.put("College", new LatLng( 31.104999,73.114727));
    // Uncle's House Location.
    BAY_AREA_LANDMARKS.put("Uncle", new LatLng( 31.137073,73.105472));
    // Code Debuggers Location.
    BAY_AREA_LANDMARKS.put("Code Debuggers", new LatLng( 31.117376,73.117588));
}
</code>```

There are my Hash Locations I want LatLong Value by string("College","Home".....)

Here is code which I am trying

```<code>public void addGeofencesButtonHandler(View view) {
    if (checkPermissions()) {
        Map<String , LatLng> Loc= new HashMap<String, LatLng>();
        LatLng ff =  Loc.get("College"); // return ff = null
        Toast.makeText(MainActivity.this, ff.toString(),Toast.LENGTH_SHORT).show();
    }
}
</code>```

How can I get Lat and Long value and show them?

答:
You're declaring a new map then attempting to get a value from it. You've just created it so it's empty.

```<code>Map<String , LatLng> Loc= new HashMap<String, LatLng>();
LatLng ff =  Loc.get("College"); // return ff = null
</code>```

You need to get the value from the map declared in your first snippet. Replace the two lines above with:

```<code>LatLng ff = BAY_AREA_LANDMARKS.get("College");
</code>```

Title: Get LatLong from HashMap in Java

Body:
static final HashMap<String, LatLng> BAY_AREA_LANDMARKS = new HashMap<String, LatLng>();

static {
    // Office Location.
    BAY_AREA_LANDMARKS.put("Office", new LatLng(  31.112635, 73.114867));
    // House Location.
    BAY_AREA_LANDMARKS.put("Home", new LatLng(  31.138056, 73.108787));
    //College Location.
    BAY_AREA_LANDMARKS.put("College", new LatLng( 31.104999,73.114727));
    // Uncle's House Location.
    BAY_AREA_LANDMARKS.put("Uncle", new LatLng( 31.137073,73.105472));
    // Code Debuggers Location.
    BAY_AREA_LANDMARKS.put("Code Debuggers", new LatLng( 31.117376,73.117588));
}

There are my Hash Locations I want LatLong Value by string("College","Home".....)

Here is code which I am trying

public void addGeofencesButtonHandler(View view) {
    if (checkPermissions()) {
        Map<String , LatLng> Loc= new HashMap<String, LatLng>();
        LatLng ff =  Loc.get("College"); // return ff = null
        Toast.makeText(MainActivity.this, ff.toString(),Toast.LENGTH_SHORT).show();
    }
}

How can I get Lat and Long value and show them?

Body:
You're declaring a new map then attempting to get a value from it. You've just created it so it's empty.

Map<String , LatLng> Loc= new HashMap<String, LatLng>();
LatLng ff =  Loc.get("College"); // return ff = null

You need to get the value from the map declared in your first snippet. Replace the two lines above with:

LatLng ff = BAY_AREA_LANDMARKS.get("College");


问:
Two Django projects with same database - permission denied for relation django_migrations
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

```<code>django.db.utils.ProgrammingError: permission denied for relation django_migrations
</code>```

My setup is as follows:

```<code>//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
</code>```

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

```<code>GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;
</code>```

The DB access privileges in the psql shell:

```<code>=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov
</code>```

Any idea what am I doing wrong?

答:
the problem is that both project have their own migration files and they conflict, the solution is choosing only one project to manage your databases (migration and changes) and the other project should only connect to database (without changing db structure)

assuming you've already choose your main project (the one that runs migrations) I can think of two solutions for your second project

run migrations for secons project with --fake argument: docs

Tells Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema.

in your model class for second project set meta options managed to False (it tells django that you will manually handle db creation and migration for this model docs

sample code:

```<code>class MyModel(models.Model):
    # fields
    # ...

    class Meta:
        managed = False
</code>```

Body:
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database.

I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception:

django.db.utils.ProgrammingError: permission denied for relation django_migrations

My setup is as follows:

//First project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin',
        'PASSWORD': '******************',
        'HOST': 'localhost',
        'PORT': '',
    }
}
//Second project
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'srt_side_by_side',
        'USER': 'srt_side_by_side_admin_2',
        'PASSWORD': '**************',
        'HOST': 'localhost',
        'PORT': '',
    }
}

I have granted SUPERUSER privileges to both users.
I have tried to set individual privileges while being connected as the corresponding user in the psql shell.

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2;
GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2;

The DB access privileges in the psql shell:

=Tc/simeonparvanov
simeonparvanov=CTc/simeonparvanov
srt_side_by_side_admin=CTc/simeonparvanov
srt_side_by_side_admin_2=CTc/simeonparvanov

Any idea what am I doing wrong?

Body:
the problem is that both project have their own migration files and they conflict, the solution is choosing only one project to manage your databases (migration and changes) and the other project should only connect to database (without changing db structure)

assuming you've already choose your main project (the one that runs migrations) I can think of two solutions for your second project

run migrations for secons project with --fake argument: docs

Tells Django to mark the migrations as having been applied or unapplied, but without actually running the SQL to change your database schema.

in your model class for second project set meta options managed to False (it tells django that you will manually handle db creation and migration for this model docs

sample code:

class MyModel(models.Model):
    # fields
    # ...

    class Meta:
        managed = False


问:
How to hide or change the selection decorator on html buttons using bootstrap or css?
I am using arrows buttons like these ones:

```<code><button type="button" class="btn btn-default btn-arrow-left" > </button>
</code>```

```<code>body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a
</code>```

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

答:
Use css Outline property and set it to None</p>

```<code>.btn-arrow-left{outline: none !important;}
</code>```

Body:
I am using arrows buttons like these ones:

<button type="button" class="btn btn-default btn-arrow-left" > </button>

body { /* just for this demo. */
    padding: 30px;
}
.btn { /* just for this demo. */
    margin-top: 5px;
}
.btn-arrow-right,
.btn-arrow-left {
    position: relative;
    padding-left: 18px;
    padding-right: 18px;
}
.btn-arrow-right {
    padding-left: 36px;
}
.btn-arrow-left {
    padding-right: 36px;
}
.btn-arrow-right:before,
.btn-arrow-right:after,
.btn-arrow-left:before,
.btn-arrow-left:after { /* make two squares (before and after), looking similar to the button */
    content:"";
    position: absolute;
    top: 5px; /* move it down because of rounded corners */
    width: 22px; /* same as height */
    height: 22px; /* button_outer_height / sqrt(2) */
    background: inherit; /* use parent background */
    border: inherit; /* use parent border */
    border-left-color: transparent; /* hide left border */
    border-bottom-color: transparent; /* hide bottom border */
    border-radius: 0px 4px 0px 0px; /* round arrow corner, the shorthand property doesn't accept "inherit" so it is set to 4px */
    -webkit-border-radius: 0px 4px 0px 0px;
    -moz-border-radius: 0px 4px 0px 0px;
}
.btn-arrow-right:before,
.btn-arrow-right:after {
    transform: rotate(45deg); /* rotate right arrow squares 45 deg to point right */
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
}
.btn-arrow-left:before,
.btn-arrow-left:after {
    transform: rotate(225deg); /* rotate left arrow squares 225 deg to point left */
    -webkit-transform: rotate(225deg);
    -moz-transform: rotate(225deg);
    -o-transform: rotate(225deg);
    -ms-transform: rotate(225deg);
}
.btn-arrow-right:before,
.btn-arrow-left:before { /* align the "before" square to the left */
    left: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:after { /* align the "after" square to the right */
    right: -11px;
}
.btn-arrow-right:after,
.btn-arrow-left:before { /* bring arrow pointers to front */
    z-index: 1;
}
.btn-arrow-right:before,
.btn-a

But I do not know how can I hide or change the yellow decorator when it is selected. Is it possible?

NOTE: I am working with Bootstrap v3.3.7

Body:
Use css Outline property and set it to None

.btn-arrow-left{outline: none !important;}


问:
Pyspark: not able to print after file text is split
I am new to spark coding with Python (pyspark).
    I have a txt file in which messages needs to be split at }{ . That is message starts with {...}{...}... like this. I want to split these into

```<code>{...}
{...}
{...}
</code>```

few also has inner message like

```<code>{...
    {...}
...
}
</code>```

CODE:

I am trying with below code and I am getting error saying

Traceback (most recent call last):
  File "PythonBLEDataParser_work2.py", line 49, in <module>
    for line in words:
TypeError: 'PipelinedRDD' object is not iterable
```

<p>(note - i have removed couple of commented lines and hence line number 49 refers to <code>words = contentRDD.map(lambda x: x.split('}{'))</code>)</p>

<pre class="lang-python prettyprint-override"><code>        from pyspark.sql import SparkSession
        #importing re for removing space and others
        import re

        if __name__ == "__main__":

        spark = SparkSession\
                .builder\
                .appName("PythonBLEDataParser")\
                .getOrCreate()

        contentRDD = spark.sparkContext.textFile("BLE_data_Sample.txt")\

        #nonempty_lines = contentRDD.filter(lambda x: len(x) > 0)
        #print (nonempty_lines.collect())
        words = contentRDD.map(lambda x: x.split('}{'))
        for line in words:
            print (line)

        spark.stop
</code>```

I tried .map( lambda elem: list(elem)) mentioned in pyspark: 'PipelinedRDD' object is not iterable but didn't help.

答:
After:

```<code>words = contentRDD.map(lambda x: x.split('}{'))
</code>```

You only did a transformation on contentRDD not an action. This is still a PipelinedRDD object.

If you want to collect it into the driver you need an action like "collect", so:

```<code>words = contentRDD.map(lambda x: x.split('}{')).collect()
for line in words:
    print (line)
</code>```

Body:
I am new to spark coding with Python (pyspark).
    I have a txt file in which messages needs to be split at }{ . That is message starts with {...}{...}... like this. I want to split these into

{...}
{...}
{...}

few also has inner message like

{...
    {...}
...
}

CODE:

I am trying with below code and I am getting error saying

Traceback (most recent call last):
  File "PythonBLEDataParser_work2.py", line 49, in <module>
    for line in words:
TypeError: 'PipelinedRDD' object is not iterable

(note - i have removed couple of commented lines and hence line number 49 refers to words = contentRDD.map(lambda x: x.split('}{')))

        from pyspark.sql import SparkSession
        #importing re for removing space and others
        import re

        if __name__ == "__main__":

        spark = SparkSession\
                .builder\
                .appName("PythonBLEDataParser")\
                .getOrCreate()

        contentRDD = spark.sparkContext.textFile("BLE_data_Sample.txt")\

        #nonempty_lines = contentRDD.filter(lambda x: len(x) > 0)
        #print (nonempty_lines.collect())
        words = contentRDD.map(lambda x: x.split('}{'))
        for line in words:
            print (line)

        spark.stop

I tried .map( lambda elem: list(elem)) mentioned in pyspark: 'PipelinedRDD' object is not iterable but didn't help.

Body:
After:

words = contentRDD.map(lambda x: x.split('}{'))

You only did a transformation on contentRDD not an action. This is still a PipelinedRDD object.

If you want to collect it into the driver you need an action like "collect", so:

words = contentRDD.map(lambda x: x.split('}{')).collect()
for line in words:
    print (line)


问:
Get formatted value in SELECT statement
Is there a way to get the "Value" field from a Select statement? When using the SELECT in ABAP, I get the value like in "Value Unconverted".

Is there a special FM that I have to use to get the "Value" field?

答:
From the SELECT statement directly is not possible, you need to convert the value.

Go to SE11, enter the table name PROJ. Double click the data element PS_INTNR, double click the domain PS_PSPNR. There is a field 'Routine', here you should find the value KONPD. This is the conversion exit used for converting between input (unconverted, i.e. what are stored in DB) and output values (converted, i.e. what are shown on the screen).

If you double click this field, it will give you the function modules you can use for converting:

CONVERSION_EXIT_KONPD_INPUT

CONVERSION_EXIT_KONPD_OUTPUT

The bad news you have to convert each value separately, so if the data is in an internal table LOOP/ENDLOOP and call the FM.

Title: Get formatted value in SELECT statement


问:
How to read excel file to content status
I would like read to excel file (this file is not open) "content status" with VBA macros.
It is possible?
I attached picture what I want to read.

Thanks for your help.

答:
Can you try the below code:

```<code>Dim fileProperty As Variant
For Each fileProperty In ActiveWorkbook.BuiltinDocumentProperties
   Debug.Print fileProperty.Name
Next fileProperty
</code>```

I know this is not the full code, but you can also use .BuiltinDocumentProperties("Content Status")

Let me know if that works.

Body:
Can you try the below code:

Dim fileProperty As Variant
For Each fileProperty In ActiveWorkbook.BuiltinDocumentProperties
   Debug.Print fileProperty.Name
Next fileProperty

I know this is not the full code, but you can also use .BuiltinDocumentProperties("Content Status")

Let me know if that works.


问:
How to calculate number of days from a specified data till today?
Hi i have a database something lile this:

custId   gender  firstdate  fisrtregion  lastdate  buytime

abc         m       yymmdd     xws          yymmdd

qwe         f       yymmdd     rty          yymmdd    1

dfg         m       yymmdd     rew          yymmdd    1

and i need to find days between last  purchase date till today.
how can i do it.

答:
This will give you number of days from the database column lastdate till today

```<code>nm = date.today()
df['lastdate'] = df['lastdate'].map(lambda x: datetime.strptime(str(x),'%Y%m%d'))
df['days_from_last_buy'] = date.today() - df['lastdate']
temp = df[['custid','days_from_last_buy']].groupby('custid').agg(max)
temp.columns = ['last_visit_date']
df.merge(temp,how='left',left_on='custId',right_index=True)
</code>```

Body:
This will give you number of days from the database column lastdate till today

nm = date.today()
df['lastdate'] = df['lastdate'].map(lambda x: datetime.strptime(str(x),'%Y%m%d'))
df['days_from_last_buy'] = date.today() - df['lastdate']
temp = df[['custid','days_from_last_buy']].groupby('custid').agg(max)
temp.columns = ['last_visit_date']
df.merge(temp,how='left',left_on='custId',right_index=True)


问:
Check/uncheck check boxes based on database value
I have a gridview which contains checkboxes and fields in sql server database which has datatype bit.

If the value in database table is set to 1 then the checkbox in the gridview should be checked and disabled otherwise it should be unchecked and enabled.

This should happen at the time of databind. How to achive this task?

答:
int o = 0;

```<code>        foreach (GridViewRow row in GridView1.Rows)
            {

                if (z == ds1.Tables[4].Rows[o]["Name"].ToString())
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkusergroup");
                    chk.Checked = true;
                }
                else
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkusergroup");
                    chk.Checked = false;

                }

            o++;

            }`enter code here`
</code>```

Gridview1 is the Gridview ID.
Z is a string which contains a value.
I am checking for one column in every row whether it matches with 'z' and if it matches than set checkbox to checked.
O is the counter to iterate in every row.

Body:
int o = 0;

        foreach (GridViewRow row in GridView1.Rows)
            {

                if (z == ds1.Tables[4].Rows[o]["Name"].ToString())
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkusergroup");
                    chk.Checked = true;
                }
                else
                {
                    CheckBox chk = (CheckBox)row.FindControl("chkusergroup");
                    chk.Checked = false;

                }

            o++;

            }`enter code here`

Gridview1 is the Gridview ID.
Z is a string which contains a value.
I am checking for one column in every row whether it matches with 'z' and if it matches than set checkbox to checked.
O is the counter to iterate in every row.


问:
How to listen to focus event of a window with a browser?
By running this sample:

```<code><?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="640" height="480"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    onload="">

    <script>
        <![CDATA[
            function onfocus() {
                dump("FOCUSED!\n");
            }
            window.addEventListener("focus", onfocus, false);
        ]]>
    </script>

    <browser id="gmail" type="content" src="http://gmail.com/" flex="1" />
    <button label="click here to remove the focus from the browser"/>

</window>
</code>```

..you can see that the window's focus event will be thrown only if the focus is not on the browser. I added a button in the bottom, so you can remove the focus from the browser and see what I mean:

If the button is focused and you minimize and restore the window, you'll see the focus event occur.

If the browser is focused and you minimize and restore the window, the focus event will not occur.

I need this focus event to happen when the browser has the focus, any idea how to accomplish this goal?

答: Try using the activate event instead.</p>

ContentLicense: CC BY-SA 2.5

Body:
By running this sample:

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<window width="640" height="480"
    xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
    onload="">

    <browser id="gmail" type="content" src="http://gmail.com/" flex="1" />
    <button label="click here to remove the focus from the browser"/>

</window>

..you can see that the window's focus event will be thrown only if the focus is not on the browser. I added a button in the bottom, so you can remove the focus from the browser and see what I mean:

If the button is focused and you minimize and restore the window, you'll see the focus event occur.

If the browser is focused and you minimize and restore the window, the focus event will not occur.

I need this focus event to happen when the browser has the focus, any idea how to accomplish this goal?

Body: Try using the activate event instead.


问:
QuickBooks - QODBC Driver, Look up Item Serial Numbers
I know this may be a stretch, but does anyone know where to look in the QuickBooks tables for an inventory item's serial numbers?

I have looked through all documentation I can find and can not seem to find the table that holds the serial numbers.  Any advice is greatly appreciated.

Additionally, any information on where/how to pull an items Average Cost would be awesome too!

答:
Additionally, you can refer QODBC-Desktop knowledge base - Where Item Serial Numbers or Lot Numbers are stored

or

you may visit  QODBC Table Schema and click "ALPHABETICAL LISTING OF ALL TABLE'S DETAIL", this will list out all the tables and fields, Just search for "SerialNumber"


问:
How To Get Input From URL using javascript
I want an input form url.
for example:
this is my website : abc.html?name=anyname
i want anyname as input.

i have tried the following, but it didn't work:

```<code>window.onload = function(){

    function ParseURLParameter(Parameter)
    {
        var FullURL=window.location.search.substring(1);
        var ParameterArray=FullURL.split('&');
        for(var i=0; i<ParameterArray.length;i++)
        {
            var CurrentParameter=ParameterArray[i].split('=');
            if(CurrentParameter[0]==Parameter)
            {
                return CurrentParameter[1];
            }
        }
    }

    var PageName=ParseURLParameter('name');
    if(typeof PageName!=='undefined'){
        if(PageName=='Parameter'){
            alert(PageName);
        }
    }else{
        alert('No Page Parameter Found...');
    }
}
</code>```

答:
try this :

In variable name you can find value of querystring anyname

```<code>$(document).ready(function () {
        setInterval(function () {
                var name = GetParameterValues('name');
                if(name != 'undefined'){
                      $("#lblValue").text(name);
                }
            }, 1000);

        function GetParameterValues(param) {
            var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < url.length; i++) {
                var urlparam = url[i].split('=');
                if (urlparam[0] == param) {
                    return urlparam[1];
                }
            }
        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want an input form url.
for example:
this is my website : abc.html?name=anyname
i want anyname as input.

i have tried the following, but it didn't work:

window.onload = function(){

    function ParseURLParameter(Parameter)
    {
        var FullURL=window.location.search.substring(1);
        var ParameterArray=FullURL.split('&');
        for(var i=0; i<ParameterArray.length;i++)
        {
            var CurrentParameter=ParameterArray[i].split('=');
            if(CurrentParameter[0]==Parameter)
            {
                return CurrentParameter[1];
            }
        }
    }

    var PageName=ParseURLParameter('name');
    if(typeof PageName!=='undefined'){
        if(PageName=='Parameter'){
            alert(PageName);
        }
    }else{
        alert('No Page Parameter Found...');
    }
}

Body:
try this :

In variable name you can find value of querystring anyname

$(document).ready(function () {
        setInterval(function () {
                var name = GetParameterValues('name');
                if(name != 'undefined'){
                      $("#lblValue").text(name);
                }
            }, 1000);

        function GetParameterValues(param) {
            var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for (var i = 0; i < url.length; i++) {
                var urlparam = url[i].split('=');
                if (urlparam[0] == param) {
                    return urlparam[1];
                }
            }
        }
    });


问:
How can I have different data in different ReactJS Component instances?
Let's say I have 2 <Logs/> components. They're only displayed when their parent <Block/> has been clicked. Each <Block/> only has one <Logs/> but there will be many <Blocks/> on the page.

```<code>class Block extends React.Component {

    toggleExpanded() {

        this.setState({
            isExpanded: !this.state.isExpanded
        });

    }

    render() {

        let blockId = // ...

        return (
            <div>
                <button type="button" onClick={() => this.toggleExpanded()}>Toggle</button>
                {this.state.isExpanded && <Logs blockId={blockId} />}
            </div>
        );

    }

}

export default Block;
</code>```

As the <Logs/> is created, I want to get data from the server using Redux. There could be a lot of <Logs/> some day so I don't want to load in all data to begin with, only data as needed.

```<code>class Logs extends React.Component {

    componentDidMount() {

        if (!this.props.logs) {
            this.props.fetchBlockLogs(this.props.blockId);
        }

    }

    render() {

        return (this.props.logs && this.props.logs.length)
            ? (
                <ul>
                    {this.props.logs.map((log, i) => <li key={i}>{log}</li>)}
                </ul>
            )
            : (
                <p>Loading ...</p>
            );

    }

}

SupportLogs.defaultProps = {
    logs: null
}

const mapStateToProps = (state) => ({
    logs: state.support.logs
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    fetchBlockLogs: (blockId) => {
        dispatch(ActionTypes.fetchBlockLogs(blockId));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(SupportLogs);
</code>```

Currently, as I toggle one parent <Block/> closed and then re-opened, the data is remembered. That's a nice feature - the data won't change often and a local cache is a nice way to speed up the page. My problem is that as I toggle open a second <Block/>, the data from the first <Logs/> is shown.

My question is: how can I load in new data for a new instance of <Logs/>?

Do I have to re-load the data each time and, if so, can I clear the logs property so that I get the loading animation back?

答:
Maybe think about changing the logs in your store to be an object with logs loaded into it keyed by block id:

```<code>logs: {
 'someBlockId': [
   'some logline',
   'some other logline'
 ]
]
</code>```

Have your reducer add any requested logs to this object by block id, so as you request them they get cached in your store (by the way I really like that your component dispatches an action to trigger data fetching elsewhere as a side effect, rather than having the fetch data performed inside the component :) ).

This reducer assumes that the resulting fetched data is dispatched in an action to say it has received the logs for a particular block, {type: 'UPDATE_LOGS', blockId: 'nic cage', receivedLogsForBlock: ['oscar', 'winning', 'actor']}

```<code>logsReducer: (prevState, action) => {
  switch(action.type)
    case 'UPDATE_LOGS':
      return Object.assign({}, prevState, {
        [actions.blockId]: action.receivedLogsForBlock
      })
    default: return prevState
  }
}
</code>```

And in your component you can now look them up by id. If the required block is not defined in the logs object, then you know you need to send the action for loading, and can also show loader in meantime

```<code>class Logs extends React.Component {

  componentDidMount() {
    const {logs, blockId} = this.props
    if (!logs[blockId]) {
      this.props.fetchBlockLogs(blockId);
    }
  }

  render() {
    const {logs, blockId} = this.props
    return (logs && logs[blockId]) ? (
        <ul>
          {logs[blockId].map((log, i) => <li key={i}>{log}</li>)}
        </ul>
      ) : (
        <p>Loading ...</p>
      )
  }

}
</code>```

This has the added bonus of logs[blockId] being undefined meaning not loaded, so it is possible to distinguish between what needs to be loaded and what has already loaded but has empty logs, which your original would have mistaken for requiring a load

Body:
Let's say I have 2 <Logs/> components. They're only displayed when their parent <Block/> has been clicked. Each <Block/> only has one <Logs/> but there will be many <Blocks/> on the page.

class Block extends React.Component {

    toggleExpanded() {

        this.setState({
            isExpanded: !this.state.isExpanded
        });

    }

    render() {

        let blockId = // ...

        return (

                <button type="button" onClick={() => this.toggleExpanded()}>Toggle</button>
                {this.state.isExpanded && <Logs blockId={blockId} />}

        );

    }

}

export default Block;

As the <Logs/> is created, I want to get data from the server using Redux. There could be a lot of <Logs/> some day so I don't want to load in all data to begin with, only data as needed.

class Logs extends React.Component {

    componentDidMount() {

        if (!this.props.logs) {
            this.props.fetchBlockLogs(this.props.blockId);
        }

    }

    render() {

        return (this.props.logs && this.props.logs.length)
            ? (

                    {this.props.logs.map((log, i) =>
{log}
)}

            )
            : (

Loading ...

            );

    }

}

SupportLogs.defaultProps = {
    logs: null
}

const mapStateToProps = (state) => ({
    logs: state.support.logs
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    fetchBlockLogs: (blockId) => {
        dispatch(ActionTypes.fetchBlockLogs(blockId));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(SupportLogs);

Currently, as I toggle one parent <Block/> closed and then re-opened, the data is remembered. That's a nice feature - the data won't change often and a local cache is a nice way to speed up the page. My problem is that as I toggle open a second <Block/>, the data from the first <Logs/> is shown.

My question is: how can I load in new data for a new instance of <Logs/>?

Do I have to re-load the data each time and, if so, can I clear the logs property so that I get the loading animation back?

Body:
Maybe think about changing the logs in your store to be an object with logs loaded into it keyed by block id:

logs: {
 'someBlockId': [
   'some logline',
   'some other logline'
 ]
]

Have your reducer add any requested logs to this object by block id, so as you request them they get cached in your store (by the way I really like that your component dispatches an action to trigger data fetching elsewhere as a side effect, rather than having the fetch data performed inside the component :) ).

This reducer assumes that the resulting fetched data is dispatched in an action to say it has received the logs for a particular block, {type: 'UPDATE_LOGS', blockId: 'nic cage', receivedLogsForBlock: ['oscar', 'winning', 'actor']}

logsReducer: (prevState, action) => {
  switch(action.type)
    case 'UPDATE_LOGS':
      return Object.assign({}, prevState, {
        [actions.blockId]: action.receivedLogsForBlock
      })
    default: return prevState
  }
}

And in your component you can now look them up by id. If the required block is not defined in the logs object, then you know you need to send the action for loading, and can also show loader in meantime

class Logs extends React.Component {

  componentDidMount() {
    const {logs, blockId} = this.props
    if (!logs[blockId]) {
      this.props.fetchBlockLogs(blockId);
    }
  }

  render() {
    const {logs, blockId} = this.props
    return (logs && logs[blockId]) ? (
        <ul>
          {logs[blockId].map((log, i) => <li key={i}>{log}</li>)}
        </ul>
      ) : (
        <p>Loading ...</p>
      )
  }

}

This has the added bonus of logs[blockId] being undefined meaning not loaded, so it is possible to distinguish between what needs to be loaded and what has already loaded but has empty logs, which your original would have mistaken for requiring a load


问:
Analysis of list elements
I have a list of strings of variable length, from which I should remove elements of a certain length ONLY IF all the elements don't have the same length.

e.g.:

```<code>my_list = ['a', 'b', 'c'] # should remains the same (all elements have the same lenght)
</code>```

but:

```<code>my_list = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd'] # 'a' and 'b' because their length is <2.
</code>```

Any ideas?

答:
Here's the solution:

```<code>lengths = set([len(x) for x in mylist])
mylist = mylist if len(lengths) == 1
         else [x for x in mylist if len(x) != preferred_length]
</code>```

Another solution which is suggested by @Ev.Kounis:

```<code>new_list = my_list if all(len(x) == len(my_list[0]) for x in my_list[1:]) else [x for x in my_list if len(x) >= preferred_length]
</code>```

Title: Analysis of list elements

Body:
I have a list of strings of variable length, from which I should remove elements of a certain length ONLY IF all the elements don't have the same length.

e.g.:

my_list = ['a', 'b', 'c'] # should remains the same (all elements have the same lenght)

but:

my_list = ['a', 'ab', 'abc', 'abcd', 'b', 'bcd'] # 'a' and 'b' because their length is <2.

Any ideas?

Body:
Here's the solution:

lengths = set([len(x) for x in mylist])
mylist = mylist if len(lengths) == 1
         else [x for x in mylist if len(x) != preferred_length]

Another solution which is suggested by @Ev.Kounis:

new_list = my_list if all(len(x) == len(my_list[0]) for x in my_list[1:]) else [x for x in my_list if len(x) >= preferred_length]


问:
How to list files accessed by a newly process
I believe that a few years ago I worked with a shell command like

```<code>SOMECOMMAND php index.php
</code>```

giving me a list of all files that were accessed during that process, e.g.

```<code>index.php
config.php
some system internals
...
</code>```

I do not want the list of an ongoing process (since my script lives only for milliseconds), but explicitely the chronological order of file accesses.

Thanks!

答:
strace is the command tracing all system calls of a running executable.

You can filter the strace log to filter only with a file is opened:

```<code>strace php index.php 2>&1 | grep ^open
</code>```

2>&1 is needed for grep because strace is by default logging to stderr.

Body:
I believe that a few years ago I worked with a shell command like

SOMECOMMAND php index.php

giving me a list of all files that were accessed during that process, e.g.

index.php
config.php
some system internals
...

I do not want the list of an ongoing process (since my script lives only for milliseconds), but explicitely the chronological order of file accesses.

Thanks!

Body:
strace is the command tracing all system calls of a running executable.

You can filter the strace log to filter only with a file is opened:

strace php index.php 2>&1 | grep ^open

2>&1 is needed for grep because strace is by default logging to stderr.


问:
C#-Array Covariance In Generic Classes
I know that C# supports covariance in arrays like this :

```<code>object[] array = new string[3];
</code>```

But I'm getting an error when it tries to compile the below code

```<code>class Dummy<K,T> where T:K
{
    public void foo()
    {
        K[] arr = new T[4];
    }
}
</code>```

It says "Cannot implicitly convert type 'T[]' to 'K[]' "

Why I'm getting this error ???

答:
type T has to support implicit convertion to K. E.g.

T a = new T();
K b = a;

has to be valid.

Title: C#-Array Covariance In Generic Classes

Body:
I know that C# supports covariance in arrays like this :

object[] array = new string[3];

But I'm getting an error when it tries to compile the below code

class Dummy<K,T> where T:K
{
    public void foo()
    {
        K[] arr = new T[4];
    }
}

It says "Cannot implicitly convert type 'T[]' to 'K[]' "

Why I'm getting this error ???

OwnerDisplayName: Fredrik Jansson


问:
Can you figure out this PHP timing issue?
Can anyone tell me why when I ran a script with the below contents and then stop it after 5 seconds that I need to divide the elapsed time by 2 to get the correct script execution time?

```<code>ignore_user_abort(true); set_time_limit(0);

$begin_time = microtime(true);

$elapsed_time = 0;

while(!connection_aborted()) {
    echo ' ';
    flush();
    usleep(1000000);
}

$elapsed_time = microtime(true) - $begin_time;

$timer_seconds = $elapsed_time; //10 seconds

$timer_seconds = $elapsed_time / 2; //5 seconds

/*I am writing to a DB - but you can use this to test */
$fp = fopen('times.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fclose($fp);
</code>```

Feel free to try the code as it has baffled me on why the $elapsed_time needs to be divided by two. Maybe I have misunderstood something?

Thanks all for any help

Update

I have updated the code so that anyone can try this out and it will write to a text file to view the output.

答:
connection_aborted() can only detect disconnection when the buffer is sent. But flush() does not necessarily sent the buffer. So the loop keeps iterating until the buffer is filled and indeed flushed.

For more details please refer to the manual pages of the named functions.

Body:
Can anyone tell me why when I ran a script with the below contents and then stop it after 5 seconds that I need to divide the elapsed time by 2 to get the correct script execution time?

ignore_user_abort(true); set_time_limit(0);

$begin_time = microtime(true);

$elapsed_time = 0;

while(!connection_aborted()) {
    echo ' ';
    flush();
    usleep(1000000);
}

$elapsed_time = microtime(true) - $begin_time;

$timer_seconds = $elapsed_time; //10 seconds

$timer_seconds = $elapsed_time / 2; //5 seconds

/*I am writing to a DB - but you can use this to test */
$fp = fopen('times.txt', 'w');
fwrite($fp, 'Time Elapsed: '.$timer_seconds);
fclose($fp);

Feel free to try the code as it has baffled me on why the $elapsed_time needs to be divided by two. Maybe I have misunderstood something?

Thanks all for any help

Update

I have updated the code so that anyone can try this out and it will write to a text file to view the output.


问:
Evaluating JavaScript expression with a worker
I need to evaluate JavaScript expressions, in a browser, Chrome. To make it safe, I use a Blob and a Worker running my evaluator, until it posts back the result of a timeout cancels the wait. This is working fine. I also need to support an environment for my JavaScript. I do this as below:

```<code>function evalWorker () {
  let postResponse = function(expr, ...) {
    let presets = `var EnvObject = {};
                EnvObject.platform = "Chrome";
                EnvObject.pasteboard = "${clipboard}";
                EnvObject.baseDate = new Date();
                ...
                EnvObject._output = "";
                EnvObject.appendOutput = (str) => {EnvObject._output += str; };
                `
    postMessage(eval(presets + expr));
  };
  onmessage = function(e) {
    postResponse(e.data['expression'], e.data['clipboard'], ...);
  }
}
</code>```

My problem is that if _output is not empty, I need to return that - _output instead of the evaluated expression, as in

```<code>EnvObject.appendOutput('hello');
var a = 0;
++a;
</code>```

Should return hello; while without appendOutput, it should return 1.

How would I go about something like this?

答:
@Bergi had the right idea with pushing the scope out. The below works.</p>

```<code>function evalWorker () {
  let postResponse = function(expr, TextExpander) {
    let result = eval(expr);
    if (EnvObject._output && EnvObject._output.length) {
      postMessage(EnvObject._output);
    } else {
      postMessage(result);
    }
  };
  onmessage = function(e) {
    var EnvObject = {};
    EnvObject.platform = "Chrome";
    EnvObject.pasteboardText = e.data['clipboard'];
    ...
    EnvObject._output = "";
    EnvObject.appendOutput = function(str) {EnvObject._output += str; };
    postResponse(e.data['expression'], EnvObject);
  }
}
</code>```

Body:
I need to evaluate JavaScript expressions, in a browser, Chrome. To make it safe, I use a Blob and a Worker running my evaluator, until it posts back the result of a timeout cancels the wait. This is working fine. I also need to support an environment for my JavaScript. I do this as below:

function evalWorker () {
  let postResponse = function(expr, ...) {
    let presets = `var EnvObject = {};
                EnvObject.platform = "Chrome";
                EnvObject.pasteboard = "${clipboard}";
                EnvObject.baseDate = new Date();
                ...
                EnvObject._output = "";
                EnvObject.appendOutput = (str) => {EnvObject._output += str; };
                `
    postMessage(eval(presets + expr));
  };
  onmessage = function(e) {
    postResponse(e.data['expression'], e.data['clipboard'], ...);
  }
}

My problem is that if _output is not empty, I need to return that - _output instead of the evaluated expression, as in

EnvObject.appendOutput('hello');
var a = 0;
++a;

Should return hello; while without appendOutput, it should return 1.

How would I go about something like this?

Body:
@Bergi had the right idea with pushing the scope out. The below works.

function evalWorker () {
  let postResponse = function(expr, TextExpander) {
    let result = eval(expr);
    if (EnvObject._output && EnvObject._output.length) {
      postMessage(EnvObject._output);
    } else {
      postMessage(result);
    }
  };
  onmessage = function(e) {
    var EnvObject = {};
    EnvObject.platform = "Chrome";
    EnvObject.pasteboardText = e.data['clipboard'];
    ...
    EnvObject._output = "";
    EnvObject.appendOutput = function(str) {EnvObject._output += str; };
    postResponse(e.data['expression'], EnvObject);
  }
}


问:
Toolbar icons disappearing after expanding the SearchView in Android
here's my problem:

I have that nice toolbar with the icons in landscape mode:

after expanding the search view and showing the popup menu the "add" item appears (I thought that it shouldn't):

then returning with the back arrow key, as you see, the add button goes:

and you won't find it in the popup menu anymore:

I'm using support:appcompat-v7:25.1.0, and here's my menu code:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/app_bar_search"
        android:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_action_search"
        android:title="Search"
        app:showAsAction="always|collapseActionView"
        android:enabled="true"
        android:visible="true"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
    <item android:title="Add"
        android:enabled="true"
        android:icon="@drawable/ic_action_add"
        android:visible="true"
        app:showAsAction="ifRoom"
        android:id="@+id/add" />
    <item android:title="Settings"
        android:id="@+id/settings"
        app:showAsAction="never"
        android:icon="@drawable/ic_action_settings"
        android:enabled="true"
        android:visible="true" />
    <item android:title="Feedback"
        android:id="@+id/feedbvack"
        app:showAsAction="never"
        android:icon="@drawable/ic_action_feedback"
        android:enabled="true"
        android:visible="true" />

</menu>
</code>```

I can set the add button showAsAction to "always" but I know that this is discouraged.
Does anyone here know why is there this behavior? and how can I prevent that?

Thanks in advance.

答:
You can try to use this:

```<code>MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        supportInvalidateOptionsMenu();
        //or use invalidateOptionsMenu();
        return true;
    }
});
</code>```

So when SearchView will be collapsed Toolbar will reallocate items and ifRoom items will be visible. I had this bug too and solved it this way.

Body:
here's my problem:

I have that nice toolbar with the icons in landscape mode:

after expanding the search view and showing the popup menu the "add" item appears (I thought that it shouldn't):

then returning with the back arrow key, as you see, the add button goes:

and you won't find it in the popup menu anymore:

I'm using support:appcompat-v7:25.1.0, and here's my menu code:

    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/app_bar_search"
        android:actionViewClass="android.support.v7.widget.SearchView"
        android:icon="@drawable/ic_action_search"
        android:title="Search"
        app:showAsAction="always|collapseActionView"
        android:enabled="true"
        android:visible="true"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
    <item android:title="Add"
        android:enabled="true"
        android:icon="@drawable/ic_action_add"
        android:visible="true"
        app:showAsAction="ifRoom"
        android:id="@+id/add" />
    <item android:title="Settings"
        android:id="@+id/settings"
        app:showAsAction="never"
        android:icon="@drawable/ic_action_settings"
        android:enabled="true"
        android:visible="true" />
    <item android:title="Feedback"
        android:id="@+id/feedbvack"
        app:showAsAction="never"
        android:icon="@drawable/ic_action_feedback"
        android:enabled="true"
        android:visible="true" />

</menu>

I can set the add button showAsAction to "always" but I know that this is discouraged.
Does anyone here know why is there this behavior? and how can I prevent that?

Thanks in advance.

Body:
You can try to use this:

MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        supportInvalidateOptionsMenu();
        //or use invalidateOptionsMenu();
        return true;
    }
});

So when SearchView will be collapsed Toolbar will reallocate items and ifRoom items will be visible. I had this bug too and solved it this way.


问:
How to create custom keyboard in telegram bot with python?
my code is:

```<code>from telegram.ext import Updater, CommandHandler , MessageHandler, Filters

token = Updater("token")
reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])
</code>```

and there is an error:
Traceback (most recent call last):
  File "myFirstBot.py", line 15, in
    reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])
NameError: name 'telegram' is not defined

答:
Imports in Python don't work that way. You should add telegram import as well. You only imported 4 classes into you code but not telegram nor telegram.ext module itself.

```<code>import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

token = Updater("token")
reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])
</code>```

Body:
my code is:

from telegram.ext import Updater, CommandHandler , MessageHandler, Filters

token = Updater("token")
reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])

and there is an error:
Traceback (most recent call last):
  File "myFirstBot.py", line 15, in
    reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])
NameError: name 'telegram' is not defined

Body:
Imports in Python don't work that way. You should add telegram import as well. You only imported 4 classes into you code but not telegram nor telegram.ext module itself.

import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

token = Updater("token")
reply_markup = telegram.ReplyKeyboardMarkup([[telegram.KeyboardButton('Share contact', request_contact=True)]])


问:
MySqlImport - Import a date field not in the proper format
I have a csv file that has a date field in a format like (among other fields):

```<code>17DEC2009
</code>```

When I do a mysqlimport, the other fields are imported properly, but this field remains   0000-00-00 00:00:00

How can I import this date properly?  Do I have to run a sed/awk command on the file first to put it into a proper format?  If so, what would that be like?  Does the fact that the month is spelled out instead of a number matter?

答:
Here is the approach I took to solve similar problem. My use case was bit complex with so many columns, but making here simple to present the solution.
I have Persons table with (Id int autogen, name varchar(100),DOB date), and few million of data(name,DOB) needs to be populated from CSV file.

Created additional column in persons table with name like (varchar_DOB varchar(25)).

Imported data using mysqlimport utility into columns(name,varchar_DOB).

Executed update query that updated DOB column using str_to_date(varchar_DOB,'format') function.

Now, I have expected data populated DOB column.

The same logic could be applied in doing even other kind of data formatting like double,time_stamp etc.

Body:
I have a csv file that has a date field in a format like (among other fields):

17DEC2009

When I do a mysqlimport, the other fields are imported properly, but this field remains   0000-00-00 00:00:00

How can I import this date properly?  Do I have to run a sed/awk command on the file first to put it into a proper format?  If so, what would that be like?  Does the fact that the month is spelled out instead of a number matter?


问:
Are there variables for current file or folder in the VS Code terminal?
When in the terminal pane, I would like to reference the file or folder of the active editor tab via environment variable or PowerShell variable (preferred). Something like this:

ii $vsActivePath

or

ii $vsActiveFile

Is this possible?

答:
They have added some new variables and it contains ${fileDirname} which is the path to the directory where your current ${file} is.
The documentation seems to be a bit misleading here.

Those are the current available options:

```<code>${workspaceFolder} - the path of the folder opened in VS Code
${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
${file} - the current opened file
${relativeFile} - the current opened file relative to workspaceFolder
${fileBasename} - the current opened file's basename
${fileBasenameNoExtension} - the current opened file's basename with no file extension
${fileDirname} - the current opened file's dirname
${fileExtname} - the current opened file's extension
${cwd} - the task runner's current working directory on startup
${lineNumber} - the current selected line number in the active file
</code>```

Body:
They have added some new variables and it contains ${fileDirname} which is the path to the directory where your current ${file} is.
The documentation seems to be a bit misleading here.

Those are the current available options:

${workspaceFolder} - the path of the folder opened in VS Code
${workspaceFolderBasename} - the name of the folder opened in VS Code without any slashes (/)
${file} - the current opened file
${relativeFile} - the current opened file relative to workspaceFolder
${fileBasename} - the current opened file's basename
${fileBasenameNoExtension} - the current opened file's basename with no file extension
${fileDirname} - the current opened file's dirname
${fileExtname} - the current opened file's extension
${cwd} - the task runner's current working directory on startup
${lineNumber} - the current selected line number in the active file


问:
Select rows that are not urls using regexp?
I've tried multiple regexp's but still fetching rows that contains urls.</p>

```<code>$fields=array(
":regexp"=>"/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/"
);

$foo=$sql->prepare("SELECT * FROM names WHERE name NOT REGEXP :regexp");
$foo->execute($fields);
</code>```

Body:
I've tried multiple regexp's but still fetching rows that contains urls.

$fields=array(
":regexp"=>"/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/"
);

$foo=$sql->prepare("SELECT * FROM names WHERE name NOT REGEXP :regexp");
$foo->execute($fields);

Body: Try the regex  .*?:\/\/[^ ]*?\.[^ ]*


问:
Ionic: background-image not applying correctly
I have a (long) page with ion-list and many ion-scroll in ion-grid. I'm trying to apply a background image to this page in particular. It's working perfectly on another page (with less html)

sample.html:

```<code><ion-content no-padding overflow-scroll="true" class="test">
 <ion-refresher (ionRefresh)="refreshHome($event)">
   <ion-refresher-content></ion-refresher-content>
 </ion-refresher>
 <img [src]="banner.png"/>
 <ion-list class="category_list" *ngIf="tags_home && tags_home[0]">
   <div *ngFor='let tag_selected of tags_home' class="category">
    <ion-grid no-padding align-items: center>
      <ion-row>
        <ion-col>title
        </ion-col>
        <ion-col col-auto>
          <button>button</button>
        </ion-col>
      </ion-row>
    </ion-grid>
    <ion-scroll scrollX="true" direction="x">
      <img *ngFor="let item of tag_selected.slide" [src]="item.img"/>
    </ion-scroll>
</code>```

sample.css:

```<code>  ion-content {
   .category_list {
     bottom: 0;
     height: 62vh;
     .category { ... }
    }
  }
</code>```

I tried adding background-image under ion-content (and ion-list) but nothing is showing up (working on other pages without any problem). Adding the background under .category_list only show it for about 30% of the page (it stop before even scrolling).

Inspecting the css in Chrome inspector, I added a scroll-content class with background-image. The whole page showed the background but every ion-scroll had its own background as well...

I tried using the :not() but failed (either no background at all, no result or lost the background-size on the 'real' background)

<s>I'm pretty sure the ion-scrolls are messing with my background because they are not present on the other page.</s>

Edit: It wasn't in my sample to avoid cluttering but I have an ion-refresh before my banner... This ion-refresh does have the background when it is placed under ion-content. Deleting it correctly show the background on the whole page. But I need this ion-refresh...

答:
Finally solved it...

```<code>  ion-content {
   .scroll-content {
     background-image: url('../assets/imgs/sample.png');
     background-repeat: repeat !important;
     background-size: 120% !important;
   }
</code>```

This way, the ion-refresh isn't <s>eating</s> hiding my background. But every ion-scroll had a background too. So I selected every scroll-content under the .category class.

```<code>ion-content {
  .scroll-content {
     background-image: url('../assets/imgs/sample.png');
     background-repeat: repeat !important;
     background-size: 120% !important;
   }
  .category_list {
    //...
    .category {
      .scroll-content {
        background-image: none !important;
      }
      //...
    }
</code>```

And everything is working fine with that combinaison.

Body:
I have a (long) page with ion-list and many ion-scroll in ion-grid. I'm trying to apply a background image to this page in particular. It's working perfectly on another page (with less html)

sample.html:

<ion-content no-padding overflow-scroll="true" class="test">
 <ion-refresher (ionRefresh)="refreshHome($event)">
   <ion-refresher-content></ion-refresher-content>
 </ion-refresher>

 <ion-list class="category_list" *ngIf="tags_home && tags_home[0]">

    <ion-grid no-padding align-items: center>
      <ion-row>
        <ion-col>title
        </ion-col>
        <ion-col col-auto>
          <button>button</button>
        </ion-col>
      </ion-row>
    </ion-grid>
    <ion-scroll scrollX="true" direction="x">

    </ion-scroll>

sample.css:

  ion-content {
   .category_list {
     bottom: 0;
     height: 62vh;
     .category { ... }
    }
  }

I tried adding background-image under ion-content (and ion-list) but nothing is showing up (working on other pages without any problem). Adding the background under .category_list only show it for about 30% of the page (it stop before even scrolling).

Inspecting the css in Chrome inspector, I added a scroll-content class with background-image. The whole page showed the background but every ion-scroll had its own background as well...

I tried using the :not() but failed (either no background at all, no result or lost the background-size on the 'real' background)

<s>I'm pretty sure the ion-scrolls are messing with my background because they are not present on the other page.</s>

Edit: It wasn't in my sample to avoid cluttering but I have an ion-refresh before my banner... This ion-refresh does have the background when it is placed under ion-content. Deleting it correctly show the background on the whole page. But I need this ion-refresh...

Body:
Finally solved it...

  ion-content {
   .scroll-content {
     background-image: url('../assets/imgs/sample.png');
     background-repeat: repeat !important;
     background-size: 120% !important;
   }

This way, the ion-refresh isn't <s>eating</s> hiding my background. But every ion-scroll had a background too. So I selected every scroll-content under the .category class.

ion-content {
  .scroll-content {
     background-image: url('../assets/imgs/sample.png');
     background-repeat: repeat !important;
     background-size: 120% !important;
   }
  .category_list {
    //...
    .category {
      .scroll-content {
        background-image: none !important;
      }
      //...
    }

And everything is working fine with that combinaison.


问:
ThreeJS how to add interactivity,
I have rendered model in ThreeJS. Now, I need to add some interactivity so that:

Depending on user entered values I need to color some parts of the model.

If I click on any model part I want it to be highlighted.

I am new to ThreeJS and a little confused.  How do I do this?

答:
this event manager can help you.

```<code>import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } from 'three';
import { InteractionManager } from 'three.interaction';

const renderer = new WebGLRenderer({ canvas: canvasElement });
const scene = new Scene();
const camera = new PerspectiveCamera(60, width / height, 0.1, 100);

// new a manager, then you can add interaction-event with your free style
const interactionManager = new InteractionManager(renderer, scene, camera);

const cube = new Mesh(
  new BoxGeometry(1, 1, 1),
  new MeshBasicMaterial({ color: 0xffffff }),
);
cube.cursor = 'pointer';
cube.on('click', function(ev) {});
cube.on('touchstart', function(ev) {});
cube.on('touchcancel', function(ev) {});
cube.on('touchmove', function(ev) {});
cube.on('touchend', function(ev) {});
cube.on('mousedown', function(ev) {});
cube.on('mouseout', function(ev) {});
cube.on('mouseover', function(ev) {});
cube.on('mousemove', function(ev) {});
cube.on('mouseup', function(ev) {});
// ...

scene.add(cube);
</code>```

more detail see three.interaction.js

Title: ThreeJS how to add interactivity,

Body:
this event manager can help you.

import { Scene, PerspectiveCamera, WebGLRenderer, Mesh, BoxGeometry, MeshBasicMaterial } from 'three';
import { InteractionManager } from 'three.interaction';

const renderer = new WebGLRenderer({ canvas: canvasElement });
const scene = new Scene();
const camera = new PerspectiveCamera(60, width / height, 0.1, 100);

// new a manager, then you can add interaction-event with your free style
const interactionManager = new InteractionManager(renderer, scene, camera);

const cube = new Mesh(
  new BoxGeometry(1, 1, 1),
  new MeshBasicMaterial({ color: 0xffffff }),
);
cube.cursor = 'pointer';
cube.on('click', function(ev) {});
cube.on('touchstart', function(ev) {});
cube.on('touchcancel', function(ev) {});
cube.on('touchmove', function(ev) {});
cube.on('touchend', function(ev) {});
cube.on('mousedown', function(ev) {});
cube.on('mouseout', function(ev) {});
cube.on('mouseover', function(ev) {});
cube.on('mousemove', function(ev) {});
cube.on('mouseup', function(ev) {});
// ...

scene.add(cube);

more detail see three.interaction.js


问:
What is the purpose of a self executing function in javascript?
In javascript, when would you want to use this:

```<code>(function(){
    //Bunch of code...
})();
</code>```

over this:

```<code>//Bunch of code...
</code>```

答:
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

Better namespace management (Avoiding Namespace Pollution -> JS Module)

Closures (Simulating Private Class Members, as known from OOP)

The first one has been explained very well. For the second one, please study following example:

```<code>var MyClosureObject = (function (){
  var MyName = 'Michael Jackson RIP';
  return {
    getMyName: function () { return MyName;},
    setMyName: function (name) { MyName = name}
  }
}());
</code>```

Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

Let us try some experiments:

I can get MyName using getMyName and it works:

```<code> console.log(MyClosureObject.getMyName());
 // Michael Jackson RIP
</code>```

The following ingenuous approach would not work:

```<code>console.log(MyClosureObject.MyName);
// undefined
</code>```

But I can set an another name and get the expected result:

```<code>MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP
</code>```

Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.

OwnerDisplayName: Ej

Body:
In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...

Body:
I've read all answers, something very important is missing here, I'll KISS. There are 2 main reasons, why I need Self-Executing Anonymous Functions, or better said "Immediately-Invoked Function Expression (IIFE)":

Better namespace management (Avoiding Namespace Pollution -> JS Module)

Closures (Simulating Private Class Members, as known from OOP)

The first one has been explained very well. For the second one, please study following example:

var MyClosureObject = (function (){
  var MyName = 'Michael Jackson RIP';
  return {
    getMyName: function () { return MyName;},
    setMyName: function (name) { MyName = name}
  }
}());

Attention 1: We are not assigning a function to MyClosureObject, further more the result of invoking that function. Be aware of () in the last line.

Attention 2: What do you additionally have to know about functions in Javascript is that the inner functions get access to the parameters and variables of the functions, they are defined within.

Let us try some experiments:

I can get MyName using getMyName and it works:

 console.log(MyClosureObject.getMyName());
 // Michael Jackson RIP

The following ingenuous approach would not work:

console.log(MyClosureObject.MyName);
// undefined

But I can set an another name and get the expected result:

MyClosureObject.setMyName('George Michael RIP');
console.log(MyClosureObject.getMyName());
// George Michael RIP

Edit: In the example above MyClosureObject is designed to be used without the newprefix, therefore by convention it should not be capitalized.


问:
Code Sign Error in macOS Monterey, Xcode - resource fork, Finder information, or similar detritus not allowed
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

```<code>CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1
</code>```

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?

答: The problem is in the derived data, You should clean the derived data and then clean the project and build. Please check this link.</p>

Body:
Already tried : Code Sign Error on macOS Sierra, Xcode 8

Please see image showing error

CodeSign /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app
    cd "/Volumes/Development/Project/Top Best Games/19. Lets Flow/35/let's FLOW - source/proj.ios_mac"
    export CODESIGN_ALLOCATE=/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/codesign_allocate
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"

Signing Identity:     "iPhone Distribution: New Free Games (2CHN583K4J)"
Provisioning Profile: "Super Flow Flipp AppStore"
                      (c6c30d2a-1025-4a23-8d12-1863ff684a05)

    /usr/bin/codesign --force --sign E48B98966150110E55EAA9B149F731901A41B37F --entitlements /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Intermediates/Flow.build/Debug-iphoneos/Super\ Flow\ Flip.build/Super\ Flow\ Flip.app.xcent --timestamp=none /Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super\ Flow\ Flip.app

/Users/gururajtallur/Library/Developer/Xcode/DerivedData/Flow-bkqjkvtmvjovpyepfjeyqmjpintj/Build/Products/Debug-iphoneos/Super Flow Flip.app: resource fork, Finder information, or similar detritus not allowed
Command /usr/bin/codesign failed with exit code 1

In Code Sign section its allowing me to select profile and certificate...but still giving error.

How to fix this problem ?


问:
Intellij 14 Grails Project Error on run-app: Module not backed by Gradle
I recently downloaded a new Intellij version 2017 for Grails 3 upgrade .I am using Intellij 14 with Grails 2.3.7.When I was prompted to import settings for new version,I clicked yes .Now however when I try to run my existing 2.3.7 project in Intellij 14 ,it complains Module not backed by gradle. I did not use gradle in my 2.3.7 Project.How to run this app.</p>

答: Apparently my project.iml file was messed up.I had to clean that up and was able run in previous version.Thanks All</p>


问:
Magento database tables - where is EAN stored
I am working on a Magento project and to complete an import to ebay process I may need to do a bulk update on EAN numbers.

I am reviewing the database and the tables - and I haven't found or see any indication as to where this "EAN" field is stored.

I can see it present on individual products under "general" in the edit panel on the magento site

答:
Read about EAV.

get eans with product ids

```<code>SELECT entity_id, value FROM catalog_product_entity_varchar
WHERE attribute_id IN ( SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'ean');
</code>```

write ean to magento

```<code>INSERT INTO catalog_product_entity_varchar
(value, entity_id, entity_type_id, attribute_id, store_id)
VALUES ('".$value."', ".$productId.", 4, ".$attributeId.", ".$storeId.")
ON DUPLICATE KEY UPDATE value = '".$value."'
</code>```

where $attributeId is the id of "ean" attribute from table eav_attribute

Body:
Read about EAV.

get eans with product ids

SELECT entity_id, value FROM catalog_product_entity_varchar
WHERE attribute_id IN ( SELECT attribute_id FROM eav_attribute WHERE attribute_code = 'ean');

write ean to magento

INSERT INTO catalog_product_entity_varchar
(value, entity_id, entity_type_id, attribute_id, store_id)
VALUES ('".$value."', ".$productId.", 4, ".$attributeId.", ".$storeId.")
ON DUPLICATE KEY UPDATE value = '".$value."'

where $attributeId is the id of "ean" attribute from table eav_attribute


问:
How to version products inside monorepo?
I have been educating myself about monorepos as I believe it is a great solution for my team and the current state of our projects. We have multiple web products (Client portal, Internal Portal, API, Core shared code).

Where I am struggling to find the answer that I want to find is versioning.

What is the versioning strategy when all of your projects and products are inside a monorepo?

1 version fits all?

Git sub-modules with independent versioning (kind of breaks the point of having a mono repo)

Other strategy?

And from a CI perspective, when you commit something in project A, should you launch the whole suite of tests in all of the projects to make sure that nothing broke, even though there was no necessarily a change made to a dependency/share module?

答:
What is the versioning strategy when all of your projects and products are inside a monorepo?

I would suggest that one version fits all for the following reasons:

When releasing your products you can tag the entire branch as release-x.x.x for example. If bugs come up you wouldn't need to check "which version was of XXX was YYY using"

It also makes it easier to force that version x.x.x of XXX uses version x.x.x of YYY. In essence, keeping your projects in sync. How you go about this of course depends on what technology your projects are written in.

And from a CI perspective, when you commit something in project A, should you launch the whole suite of tests in all of the projects to make sure that nothing broke, even though there was no necessarily a change made to a dependency/share module?

If the tests don't take particularly long to execute, no harm can come from this. I would definitely recommend this. The more often your tests run the sooner you could uncover time dependent or environment dependent bugs.

If you do not want to run tests all the time for whatever reason, you could query your VCS and write a script which conditionally triggers tests depending on what has changed. This relies heavily on integration between your VCS and your CI server.


问:
How to get the Child in Firebase Android?
I'm trying to perform login operation in my app using firebase my Users node is something like:

```<code>mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        System.out.println(dataSnapshot.getChildrenCount());                        }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
</code>```

i want to get that complete object with which i have matched the name. so that

i can also compare password etc.
Thanks for help.

答:
this is pretty simple</p>

```<code>mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                        Log.i("your tag",""+dataSnapshot.toString());
    }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
</code>```

Body:
I'm trying to perform login operation in my app using firebase my Users node is something like:

mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        System.out.println(dataSnapshot.getChildrenCount());                        }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

i want to get that complete object with which i have matched the name. so that

i can also compare password etc.
Thanks for help.

Body:
this is pretty simple

mUserCompounds.orderByChild("email").equalTo("test@gmail.com").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {

                        Log.i("your tag",""+dataSnapshot.toString());
    }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });


问:
Sending picture with intent to TypeApp Mail
When I try to send a picture using an intent with chooser it's working with gmail for example but not with an other mail client (TypeApp).

It's strange because when I try to share picture using other apps, it's working everywhere, include with the TypeApp mail client. Maybe they use an other extra type ?

Maybe the extra EXTRA_STREAM is not correct ?

This is my intent :

```<code>Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
                        "mailto",getIntent().getStringExtra("mail"), null));
                emailIntent .putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
                startActivity(Intent.createChooser(emailIntent, "Send a mail..."));
</code>```

答:
I found the solution using ACTION_SEND and not ACTION_SEND_TO :

```<code>Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{getIntent().getStringExtra("mail")});
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
intent.setPackage("com.trtf.blue");
startActivity(intent);
</code>```

Body:
When I try to send a picture using an intent with chooser it's working with gmail for example but not with an other mail client (TypeApp).

It's strange because when I try to share picture using other apps, it's working everywhere, include with the TypeApp mail client. Maybe they use an other extra type ?

Maybe the extra EXTRA_STREAM is not correct ?

This is my intent :

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
                        "mailto",getIntent().getStringExtra("mail"), null));
                emailIntent .putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
                startActivity(Intent.createChooser(emailIntent, "Send a mail..."));

Body:
I found the solution using ACTION_SEND and not ACTION_SEND_TO :

Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{getIntent().getStringExtra("mail")});
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + filePath));
intent.setPackage("com.trtf.blue");
startActivity(intent);


问:
Apply a list of n functions to each row of a dataframe?
I have a list of functions

```<code>funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()
</code>```

And I have a dataframe:

```<code>mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters
</code>```

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

```<code>unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}
</code>```

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

答:
Ignoring your code snippet and sticking to your initial specification that you want to apply function j on the column number j and then "sum the results"... you can do:

```<code>mapply( do.call, funs, lapply( mydata, list))
#      [,1] [,2]      [,3] [,4]
# [1,]    1   27 0.8414710    2
# [2,]    4    8 0.9092974    3
# [3,]    9    1 0.9092974    3
</code>```

I wasn't sure which way you want to now add the results (i.e. row-wise or column-wise), so you could either do rowSums or colSums on this matrix. E.g:

```<code>colSums( mapply( do.call, funs,  lapply( mydata, list)) )
# [1] 14.000000 36.000000  2.660066  8.000000
</code>```

Body:
I have a list of functions

funs <- list(fn1 = function(x) x^2,
             fn2 = function(x) x^3,
             fn3 = function(x) sin(x),
             fn4 = function(x) x+1)
#in reality these are all f = splinefun()

And I have a dataframe:

mydata <- data.frame(x1 = c(1, 2, 3, 2),
                     x2 = c(3, 2, 1, 0),
                     x3 = c(1, 2, 2, 3),
                     x4 = c(1, 2, 1, 2))
#actually a 500x15 dataframe of 500 samples from 15 parameters

For each of i rows, I would like to evaluate function j on each of the j columns and sum the results:

unlist(funs)
attach(mydata)
a <- rep(NA,4)
for (i in 1:4) {
     a[i] <- sum(fn1(x1[i]), fn2(x2[i]), fn3(x3[i]), fn4(x4[i]))
}

How can I do this efficiently? Is this an appropriate occasion to implement plyr functions? If so, how?

bonus question: why is a[4] NA?

Is this an appropriate time to use functions from plyr, if so, how can I do so?

Body:
Ignoring your code snippet and sticking to your initial specification that you want to apply function j on the column number j and then "sum the results"... you can do:

mapply( do.call, funs, lapply( mydata, list))
#      [,1] [,2]      [,3] [,4]
# [1,]    1   27 0.8414710    2
# [2,]    4    8 0.9092974    3
# [3,]    9    1 0.9092974    3

I wasn't sure which way you want to now add the results (i.e. row-wise or column-wise), so you could either do rowSums or colSums on this matrix. E.g:

colSums( mapply( do.call, funs,  lapply( mydata, list)) )
# [1] 14.000000 36.000000  2.660066  8.000000


问:
continuous touch on the screen using ADB shell
I want to keep the camera button pressed to take continuous snaps. I tried this code:

```<code>#!/system/bin/sh
am start -n com.android.camera2/com.android.camera.CameraLauncher
sleep 1
count=1
x=2
while [ $count -le 1 ]
do
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
done
</code>```

But it does not hold the button. It taps with a delay.

Then I tried this:

```<code> sendevent /dev/input/event0 3 53 300
 sendevent /dev/input/event0 3 54 400
 sendevent /dev/input/event0 3 48 5
 sendevent /dev/input/event0 3 58 50
 sendevent /dev/input/event0 0 2 0
 sendevent /dev/input/event0 0 0 0
 sleep 1
 sendevent /dev/input/event0 0 2 0
 sendevent /dev/input/event0 0 0 0
</code>```

this code gets executed but the effect is not seen on the touchscreen

答:
There is workaround for this, You can use swipe for long press:
"adb shell input swipe 560 1800 560 1800 "

Its working for me

Body:
I want to keep the camera button pressed to take continuous snaps. I tried this code:

#!/system/bin/sh
am start -n com.android.camera2/com.android.camera.CameraLauncher
sleep 1
count=1
x=2
while [ $count -le 1 ]
do
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
    input touchscreen tap 560 1800
done

But it does not hold the button. It taps with a delay.

Then I tried this:

 sendevent /dev/input/event0 3 53 300
 sendevent /dev/input/event0 3 54 400
 sendevent /dev/input/event0 3 48 5
 sendevent /dev/input/event0 3 58 50
 sendevent /dev/input/event0 0 2 0
 sendevent /dev/input/event0 0 0 0
 sleep 1
 sendevent /dev/input/event0 0 2 0
 sendevent /dev/input/event0 0 0 0

this code gets executed but the effect is not seen on the touchscreen