问:
Validation is not working if integer value of old attribute is same as that of new attribute
I've a model Cart having has_many relationship with cart_items.

```<code># cart.rb:
  accepts_nested_attributes_for :cart_items, allow_destroy: true
  has_many :cart_items, dependent: :destroy, inverse_of: :cart

# cart_item.rb:
  validates :quantity, presence: true, numericality: { greater_than: 0 }

# Controller code:

  def update
    current_cart.assign_attributes(params[:cart])
    .....
    current_cart.valid?
  end
</code>```

While updating cart_items, if integer (to_i) value of quantity is same as old value then validation is not working.

For example,
If old value of quantity is 4, now new value is updated to 4abc then quantity validation is not working and record is considered as valid.

Although, if new value is updated from 4 to 5abc then it shows a validation error, as expected.

Any suggestions why this all is happening?

EDIT 1:

Here's the output of rails console:

```<code>[3] pry(#<Shopping::CartsController>)> cart
=> #<Cart id: 12, created_at: "2017-06-22 13:52:59", updated_at: "2017-06-23 08:54:27">

[4] pry(#<Shopping::CartsController>)> cart.cart_items
[#<CartItem id: 34201, cart_id: 12, quantity: 4, created_at: "2017-06-23 05:25:39", updated_at: "2017-06-23 08:54:27">]

[5] pry(#<Shopping::CartsController>)> param_hash
=> {"cart_items_attributes"=>{"0"=>{"id"=>"34201", "quantity"=>"4abc"}}}
[6] pry(#<Shopping::CartsController>)> cart.assign_attributes param_hash
=> nil
[7] pry(#<Shopping::CartsController>)> cart.valid?
=> true
</code>```

Here, previous quantity of cart_item is 4 and new value is 4abc, but still the cart is validated.

EDIT 2:

I've checked answers of How to validate numericality and inclusion while still allowing attribute to be nil in some cases?, as it is masked as duplicate in comments, but it does not seems to work.

As I mentioned above, validation is working fine if to_i of new quantity is different than previous quantity, but if it is same then validation is not working.

Also, I tried to apply a method for custom validation using validate, but I'm getting to_i value in that method. Something like:

Model code:

```<code>validate :validate_quantity

# quantity saved in db => 4
# new quantity in form => 4abc
def validate_quantity
  puts quantity_changed? # => false
  puts quantity # => 4
end
</code>```

EDIT 3:

It seems like if to_i of new value is same as previous value then model is casting the value to integer and considering the field not even updated.

EDIT 4:

I'm getting answers & comments about the pupose of to_i. I know what to_i does.

I just want to know why I'm not getting the validation error if to_i of new quantity is similar to the quantity stored in the database.

I know quantity column is integer and ActiveRecord will cast it to integer BUT there must be a validation error as I've added that in model.

I'm getting the validation error if to_i of new value is different than quantity stored in db.

BUT

I'm not getting the validation error if to_i of new value is same than quantity stored in db.

答:
This type of issue is already reported in Github.

Reported issues:

Parent model not marked as invalid when associated record is invalid, but not dirty

Validations not triggered when attribute is changed from 0 to a string if it's a nested attribute

Validates_numericality_of skipped when changing 0 to "foo" through accepts_nested_attributes_for

Fixed in:

[v4.0]

https://github.com/rails/rails/commit/b9ec47da00e7f5e159ff130441585c3b42e41849

[v3.2]

https://github.com/rails/rails/commit/40617c7e539b8b70469671619e3c1716edcfbf59

All the issues are reported where previous value of an integer attribute is 0 and new value is some string (whose to_i will be 0). Thus the fix is also only for 0.

You can check the same in #changes_from_zero_to_string? in active_record/attribute_methods/dirty.rb, which is initially called from #_field_changed?

Solution:

Override #_field_changed? specifically for quantity field only (due to lack of time. In future, I'll override method for all integer fields).

Now if to_i value of some alphanumeric quantity is equal to current quantity value in database then below method will return true and will not type cast the value.

```<code>def _field_changed?(attr, old, value)
  if attr == 'quantity' && old == value.to_i && value != value.to_i.to_s
    return true
  end

  super
end
</code>```

Body:
I've a model Cart having has_many relationship with cart_items.

# cart.rb:
  accepts_nested_attributes_for :cart_items, allow_destroy: true
  has_many :cart_items, dependent: :destroy, inverse_of: :cart

# cart_item.rb:
  validates :quantity, presence: true, numericality: { greater_than: 0 }

# Controller code:

  def update
    current_cart.assign_attributes(params[:cart])
    .....
    current_cart.valid?
  end

While updating cart_items, if integer (to_i) value of quantity is same as old value then validation is not working.

For example,
If old value of quantity is 4, now new value is updated to 4abc then quantity validation is not working and record is considered as valid.

Although, if new value is updated from 4 to 5abc then it shows a validation error, as expected.

Any suggestions why this all is happening?

EDIT 1:

Here's the output of rails console:

[3] pry(#<Shopping::CartsController>)> cart
=> #<Cart id: 12, created_at: "2017-06-22 13:52:59", updated_at: "2017-06-23 08:54:27">

[4] pry(#<Shopping::CartsController>)> cart.cart_items
[#<CartItem id: 34201, cart_id: 12, quantity: 4, created_at: "2017-06-23 05:25:39", updated_at: "2017-06-23 08:54:27">]

[5] pry(#<Shopping::CartsController>)> param_hash
=> {"cart_items_attributes"=>{"0"=>{"id"=>"34201", "quantity"=>"4abc"}}}
[6] pry(#<Shopping::CartsController>)> cart.assign_attributes param_hash
=> nil
[7] pry(#<Shopping::CartsController>)> cart.valid?
=> true

Here, previous quantity of cart_item is 4 and new value is 4abc, but still the cart is validated.

EDIT 2:

I've checked answers of How to validate numericality and inclusion while still allowing attribute to be nil in some cases?, as it is masked as duplicate in comments, but it does not seems to work.

As I mentioned above, validation is working fine if to_i of new quantity is different than previous quantity, but if it is same then validation is not working.

Also, I tried to apply a method for custom validation using validate, but I'm getting to_i value in that method. Something like:

Model code:

validate :validate_quantity

# quantity saved in db => 4
# new quantity in form => 4abc
def validate_quantity
  puts quantity_changed? # => false
  puts quantity # => 4
end

EDIT 3:

It seems like if to_i of new value is same as previous value then model is casting the value to integer and considering the field not even updated.

EDIT 4:

I'm getting answers & comments about the pupose of to_i. I know what to_i does.

I just want to know why I'm not getting the validation error if to_i of new quantity is similar to the quantity stored in the database.

I know quantity column is integer and ActiveRecord will cast it to integer BUT there must be a validation error as I've added that in model.

I'm getting the validation error if to_i of new value is different than quantity stored in db.

BUT

I'm not getting the validation error if to_i of new value is same than quantity stored in db.

Body:
This type of issue is already reported in Github.

Reported issues:

Parent model not marked as invalid when associated record is invalid, but not dirty

Validations not triggered when attribute is changed from 0 to a string if it's a nested attribute

Validates_numericality_of skipped when changing 0 to "foo" through accepts_nested_attributes_for

Fixed in:

[v4.0]

https://github.com/rails/rails/commit/b9ec47da00e7f5e159ff130441585c3b42e41849

[v3.2]

https://github.com/rails/rails/commit/40617c7e539b8b70469671619e3c1716edcfbf59

All the issues are reported where previous value of an integer attribute is 0 and new value is some string (whose to_i will be 0). Thus the fix is also only for 0.

You can check the same in #changes_from_zero_to_string? in active_record/attribute_methods/dirty.rb, which is initially called from #_field_changed?

Solution:

Override #_field_changed? specifically for quantity field only (due to lack of time. In future, I'll override method for all integer fields).

Now if to_i value of some alphanumeric quantity is equal to current quantity value in database then below method will return true and will not type cast the value.

def _field_changed?(attr, old, value)
  if attr == 'quantity' && old == value.to_i && value != value.to_i.to_s
    return true
  end

  super
end


来源: stackexchange

问:
return a full dataframe based on partial colnames
I have this data frame

```<code>dat <- read.table(text =
               " 'A;B;T' 'C;D'     E      X
                  101     2.1     0.9     1
                  102     1.1     0.8     2
                  103     2       1.5     2
                  104     2       1.5     0.5
                  105     1.1     0.8     2
                  106     1.1     0.8     2
                  106     1.1     0.8     2   ",
                  header=TRUE, check.names =FALSE)
</code>```

Some columns have multiple names separated by ; in the example 'A;B;T'  'C;D'.

I want to use a reference vector that will assign and select at the same time the column and the final name in this case "A" and "D". I want  also to maintain in my final data frame columns which have a correct single name.

Given a vector v1<-c("A", "D") to select and match colnames

I want to return this

```<code>  A   D   E   X
  101 2.1 0.9 1.0
  102 1.1 0.8 2.0
  103 2.0 1.5 2.0
  104 2.0 1.5 0.5
  105 1.1 0.8 2.0
  106 1.1 0.8 2.0
  106 1.1 0.8 2.0
</code>```

答:
We can use str_extract to extract the substring from the names of 'dat' and then assign the names with the newly extracted vector

```<code>library(stringr)
v1 <- str_extract(names(dat), paste(v1, collapse="|"))
i1 <- !is.na(v1)
names(dat)[i1] <- v1[i1]
dat
#    A   D   E   X
#1 101 2.1 0.9 1.0
#2 102 1.1 0.8 2.0
#3 103 2.0 1.5 2.0
#4 104 2.0 1.5 0.5
#5 105 1.1 0.8 2.0
#6 106 1.1 0.8 2.0
#7 106 1.1 0.8 2.0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this data frame

dat <- read.table(text =
               " 'A;B;T' 'C;D'     E      X
                  101     2.1     0.9     1
                  102     1.1     0.8     2
                  103     2       1.5     2
                  104     2       1.5     0.5
                  105     1.1     0.8     2
                  106     1.1     0.8     2
                  106     1.1     0.8     2   ",
                  header=TRUE, check.names =FALSE)

Some columns have multiple names separated by ; in the example 'A;B;T'  'C;D'.

I want to use a reference vector that will assign and select at the same time the column and the final name in this case "A" and "D". I want  also to maintain in my final data frame columns which have a correct single name.

Given a vector v1<-c("A", "D") to select and match colnames

I want to return this

  A   D   E   X
  101 2.1 0.9 1.0
  102 1.1 0.8 2.0
  103 2.0 1.5 2.0
  104 2.0 1.5 0.5
  105 1.1 0.8 2.0
  106 1.1 0.8 2.0
  106 1.1 0.8 2.0

Body:
We can use str_extract to extract the substring from the names of 'dat' and then assign the names with the newly extracted vector

library(stringr)
v1 <- str_extract(names(dat), paste(v1, collapse="|"))
i1 <- !is.na(v1)
names(dat)[i1] <- v1[i1]
dat
#    A   D   E   X
#1 101 2.1 0.9 1.0
#2 102 1.1 0.8 2.0
#3 103 2.0 1.5 2.0
#4 104 2.0 1.5 0.5
#5 105 1.1 0.8 2.0
#6 106 1.1 0.8 2.0
#7 106 1.1 0.8 2.0


问:
R 3.4.1 "Single Candle" Personal Library Path Error: unable to create ‘NA’
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

```<code>> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’
</code>```

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

```<code>Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y
</code>```

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?

答:
Looking at the details in @Dirk 's comment (https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=866768) this is a planned behaviour so that packages are installed once for all users of the system.

The solution is to make /usr/local/lib/R/ writable for all users, rather than to re-instate the old behaviour of having a personal package library for every individual user.

Open up a terminal and:

Navigate to /usr/local/lib/ with cd /usr/local/lib/

Change the owner:group so that all users can write to the folder. I happen to have a group on my computer that all users are a member of, so I used that, but see https://askubuntu.com/questions/66718/how-to-manage-users-and-groups for help with setting up a group if necessary

To change ownership use sudo chown owner:group -R R/. owner is an any user, it doesn't really matter. group is the key one; make sure anyone wanting to use R on your system is a member of this group. -R is recursive (i.e. do it to all files and folders in R/).

If you need to change group permissions, use chmod -R 775 R/. This gives the owner and group read, write, and execute permissions, and gives all others read and execute permissions.

Now restart R and you should be able to install packages to your this shared location.

Body:
I just updated to R (3.4.1 "Single Candle") on my Linux Mint 18.1 Cinnamon machine and I attempted to install a package. R returned the following:

> install.packages('ggplot2')
Installing package into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)
Warning in install.packages("ggplot2") :
  'lib = "/usr/local/lib/R/site-library"' is not writable
Would you like to use a personal library instead?  (y/n) y
Would you like to create a personal library
NA
to install packages into?  (y/n) y
Error in install.packages("ggplot2") : unable to create ‘NA’

I have encountered the 'lib not writable' output before but typically it offers a solution like this one:

Would you like to create a personal library
~/R/x86_64-pc-linux-gnu-library/3.4
to install packages into?  (y/n) y

Any ideas why the personal library is suggesting NA? Is there a way to manually override this?


问:
When does SQLiteOpenHelper onCreate() / onUpgrade() run?
I have created my tables in my SQLiteOpenHelper onCreate() but receive

```<code>SQLiteException: no such table
</code>```

or

```<code>SQLiteException: no such column
</code>```

errors. Why?

NOTE:

(This is the amalgamated summary of tens of similar questions every week. Attempting to provide a "canonical" community wiki question/answer here so that all those questions can be directed to a good reference.)

答:
no such table found is mainly when you have not opened the SQLiteOpenHelper class with getwritabledata() and before this you also have to call make constructor with databasename & version.
And OnUpgrade is called whenever there is upgrade value in version number given in SQLiteOpenHelper class.

Below is the code snippet (No such column found may be because of spell in column name):

```<code>public class database_db {
    entry_data endb;
    String file_name="Record.db";
    SQLiteDatabase sq;
    public database_db(Context c)
    {
        endb=new entry_data(c, file_name, null, 8);
    }
    public database_db open()
    {
        sq=endb.getWritableDatabase();
        return this;
    }
    public Cursor getdata(String table)
    {
        return sq.query(table, null, null, null, null, null, null);
    }
    public long insert_data(String table,ContentValues value)
    {
        return sq.insert(table, null, value);
    }
    public void close()
    {
        sq.close();
    }
    public void delete(String table)
    {
        sq.delete(table,null,null);
    }
}
class entry_data extends SQLiteOpenHelper
{

    public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
                      int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase sqdb) {
        // TODO Auto-generated method stub

        sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          onCreate(db);
    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have created my tables in my SQLiteOpenHelper onCreate() but receive

SQLiteException: no such table

or

SQLiteException: no such column

errors. Why?

NOTE:

(This is the amalgamated summary of tens of similar questions every week. Attempting to provide a "canonical" community wiki question/answer here so that all those questions can be directed to a good reference.)

Body:
no such table found is mainly when you have not opened the SQLiteOpenHelper class with getwritabledata() and before this you also have to call make constructor with databasename & version.
And OnUpgrade is called whenever there is upgrade value in version number given in SQLiteOpenHelper class.

Below is the code snippet (No such column found may be because of spell in column name):

public class database_db {
    entry_data endb;
    String file_name="Record.db";
    SQLiteDatabase sq;
    public database_db(Context c)
    {
        endb=new entry_data(c, file_name, null, 8);
    }
    public database_db open()
    {
        sq=endb.getWritableDatabase();
        return this;
    }
    public Cursor getdata(String table)
    {
        return sq.query(table, null, null, null, null, null, null);
    }
    public long insert_data(String table,ContentValues value)
    {
        return sq.insert(table, null, value);
    }
    public void close()
    {
        sq.close();
    }
    public void delete(String table)
    {
        sq.delete(table,null,null);
    }
}
class entry_data extends SQLiteOpenHelper
{

    public entry_data(Context context, String name, SQLiteDatabase.CursorFactory factory,
                      int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase sqdb) {
        // TODO Auto-generated method stub

        sqdb.execSQL("CREATE TABLE IF NOT EXISTS 'YOUR_TABLE_NAME'(Column_1 text not null,Column_2 text not null);");

    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
          onCreate(db);
    }

}


答: What I would try, is using string functions to replace all parens with square brackets, then wrap each number or word in quotes, then inserting a comma between each, until you have a string that you can use with json_decode() to parse into an array.</p>

ContentLicense: CC BY-SA 2.5

Title: Parsing query like string to array

Body:
i have a string that looks like this:

$query = '(((306352743) and (306354310 OR 306354381 OR 306354379 OR 306354383 OR 306354372 OR 306354371 OR 306354378 OR 306354384 OR 306354373 OR 306354375 OR 306354376 OR 306354377 OR 306354382 OR 306354380 OR 306354374)) and ((306348630 OR 306347920) and (306348630)))';

and i want to parse it in to some kind of array that i can easly loop through.
any sugestions?


问:
Connect to drone wifi via an application
I need an information about a connection to a drone WiFi. Is it possible to connect to a drone WiFi via an Android application? For example, there is a button "Connect" and when the user clicks the button, the phone automatically connects to the drone WiFi (the user does not need to go to phone settings and WiFi settings to connect to the WiFi drone, just clicks the "Connect" button on the application).

答:
It is possible.

If you know drone's Wi-Fi network SSID and password then just connect to it like described here or here. Don't forget to set CHANGE_WIFI_STATE permission in manifest.


问:
Regular expression to validate time but exclude 0:00
I'm not an expert to regular expressions, but I tried to validate the user input for a time field with it.

My current regex: /^([0-9]|0[0-9]):[0-5][0-9]$/

It should validate anything positive between 0:01 and 9:59, but it also give positive return to 0:00.

Can you please help me to modify my regular expression to exclude 0:00?

Thanks a lot!

Body:
You could use a negative lookahead:

^(?!0?0:00$)0?[0-9]:[0-5][0-9]$


问:
Signtool error: No certificates were found that met all given criteria with a Windows Store App?
I'm trying to sign a Windows 8 appx package with a pfx file I have. I'm using a command like so:

```<code>signtool.exe sign /fd sha256 /f "key.pfx" "app.appx"
</code>```

And from this, I get:

SignTool Error: No certificates were found that met all the given criteria.

What "criteria" am I not meeting? This is only for testing so these are self-signed certificates. I've tried importing the key and then signing it, but it always results in the same error. How do I fix this?

答:
With /debug, when you get this message "After Private Key filter, 0 certs were left.", one reason could be that the pfx file doesn't have the private key.
When you export the installed certificate to pfx file ensure to enable the check box to also include the private key.</p>

Body:
I'm trying to sign a Windows 8 appx package with a pfx file I have. I'm using a command like so:

signtool.exe sign /fd sha256 /f "key.pfx" "app.appx"

And from this, I get:

SignTool Error: No certificates were found that met all the given criteria.

What "criteria" am I not meeting? This is only for testing so these are self-signed certificates. I've tried importing the key and then signing it, but it always results in the same error. How do I fix this?


问:
Difference between using continue and stream filter operation
Is there any advantage of using stream filter operation over iterator with continue operation?

Example for iteration:

```<code>for (ApiSite apiSite : sites) {
    Site mSite = Site.getSiteByName(apiSite.getName());
    if (mSite == null || deletedSitesToSkip.contains(mSite)) {
        LOGGER.info("Skipping site: {} as this has been deleted ", apiSite.getName());
        continue;
    }
    // operation
}
</code>```

stream with filter example:

```<code>sites.stream().filter(apiSite -> {
    Site mSite = Site.getSiteByName(apiSite.getName());
    return (mSite != null && !deletedSitesToSkip.contains(mSite));
}).map(//some operation);
</code>```

答:
First, the filter behavior depends on which terminal operation is invoked.

IF a short-circuiting terminal operation, e.g:anyMatch is invoked, the filter will be exit until the first satisfied element.

IF a non-short-circuiting terminal operation, e.g:count, collect is invoked, the filter's behavior just like as yours. continue and process the next until the last.

Second, the stream api will make your code more expressive.

Third, Stream api allows you do some time-consuming operations in parallel . but for loop will take more effort to do it, for example:

```<code>stream.parallel().map(it-> remoteCall(it)).collect(...);
</code>```

Fourth, Stream operation can be serialized, cached, the apache spark core & streaming api is a framework that processing distributed operations on nodes in a cluster.

Body:
Is there any advantage of using stream filter operation over iterator with continue operation?

Example for iteration:

for (ApiSite apiSite : sites) {
    Site mSite = Site.getSiteByName(apiSite.getName());
    if (mSite == null || deletedSitesToSkip.contains(mSite)) {
        LOGGER.info("Skipping site: {} as this has been deleted ", apiSite.getName());
        continue;
    }
    // operation
}

stream with filter example:

sites.stream().filter(apiSite -> {
    Site mSite = Site.getSiteByName(apiSite.getName());
    return (mSite != null && !deletedSitesToSkip.contains(mSite));
}).map(//some operation);

Body:
First, the filter behavior depends on which terminal operation is invoked.

IF a short-circuiting terminal operation, e.g:anyMatch is invoked, the filter will be exit until the first satisfied element.

IF a non-short-circuiting terminal operation, e.g:count, collect is invoked, the filter's behavior just like as yours. continue and process the next until the last.

Second, the stream api will make your code more expressive.

Third, Stream api allows you do some time-consuming operations in parallel . but for loop will take more effort to do it, for example:

stream.parallel().map(it-> remoteCall(it)).collect(...);

Fourth, Stream operation can be serialized, cached, the apache spark core & streaming api is a framework that processing distributed operations on nodes in a cluster.


问:
Change datetime format in jQuery
I have using following jquery code snippet in an input field to pick date and time in my page

```<code>$('.timePicker').datetimepicker({
    format:'yyyy/mm/dd HH:mm:ss',
    minDate: getFormattedDate(new Date())
});
</code>```

Current output is : 2017/07/05 06:07:04

While in need the date and time format in following format

Expected output : 07/05/2017 06:07AM

Ho can i change this code for this purpose ?

答:
```<code>   $('.timePicker').datetimepicker({
        ampm: true, // FOR AM/PM FORMAT
        format : 'g:i A'
    });
</code>```

or

```<code>$('.timePicker').datetimepicker(
                {
                    format: 'DD MMM YYYY hh:mm A'

                });
</code>```

this should do it

Title: Change datetime format in jQuery

Body:
I have using following jquery code snippet in an input field to pick date and time in my page

$('.timePicker').datetimepicker({
    format:'yyyy/mm/dd HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

Current output is : 2017/07/05 06:07:04

While in need the date and time format in following format

Expected output : 07/05/2017 06:07AM

Ho can i change this code for this purpose ?

Body:
   $('.timePicker').datetimepicker({
        ampm: true, // FOR AM/PM FORMAT
        format : 'g:i A'
    });

or

$('.timePicker').datetimepicker(
                {
                    format: 'DD MMM YYYY hh:mm A'

                });

this should do it


问:
Delete image from database and from folder in php mysql
I try to delete an image from database and from folder, image path is saved in the database when we create a post, when  echo $res = $row['image']; i got this result
/bp_project/admin-bp/job/ad_images/Picture3.jpg , Every thing is fine and record gets deleted from the database but the image is still in 'ad_images' Folder.
if i try unlink("ad_images/"."Picture3.jpg"); its working but we didn't need this, we want to delete image by fetching image path from database.
Anybody can help me delete image by fetching image path from database Thanks.

```<code>$user_email=$_SESSION['session_email_id'];
$token=$_GET['id'];

$result = $con->prepare("SELECT * FROM bp_users WHERE email= '".$user_email."'");
$result->execute();
$row = $result->fetch();
$user_token = $row['token_id'];

if(isset($token)){
    $result = $con->prepare("SELECT * FROM job WHERE token_id = '".$token."'");
    $result->execute();
    $row = $result->fetch();

    echo $res = $row['image'];

    if(file_exists($res)){

        unlink($res);

        $result = $con->prepare("DELETE FROM job WHERE token_id= :memid");
        $result->bindParam(':memid', $token);
        $result->execute();

        echo "<script language='javascript' type='text/javascript'>alert('Ad Successfully Deleted!')</script>";
        echo "<script language='javascript' type='text/javascript'>window.open('all-ad.php?user_token=".$user_token."','_self')</script>";
    }
    else{
        echo "<script language='javascript' type='text/javascript'>alert('Ad not Deleted Please Try Again!')</script>";
        echo "<script language='javascript'
        type='text/javascript'>window.open('all-ad.php?
        user_token=".$user_token."','_self')</script>";
    }
}
</code>```

答:
but we didn't need this, we want to delete image by fetching image
  path from database.

if you want to delete it by fetching image path from the database then you need to store absolute path in your database.

Instead of storing complete path in the database just store the image name and use it with absolute path to delete.

Then you can use unlink($_SERVER['DOCUMENT_ROOT'].'image_name_from_db'); to delete it

Body:
I try to delete an image from database and from folder, image path is saved in the database when we create a post, when  echo $res = $row['image']; i got this result
/bp_project/admin-bp/job/ad_images/Picture3.jpg , Every thing is fine and record gets deleted from the database but the image is still in 'ad_images' Folder.
if i try unlink("ad_images/"."Picture3.jpg"); its working but we didn't need this, we want to delete image by fetching image path from database.
Anybody can help me delete image by fetching image path from database Thanks.

$user_email=$_SESSION['session_email_id'];
$token=$_GET['id'];

$result = $con->prepare("SELECT * FROM bp_users WHERE email= '".$user_email."'");
$result->execute();
$row = $result->fetch();
$user_token = $row['token_id'];

if(isset($token)){
    $result = $con->prepare("SELECT * FROM job WHERE token_id = '".$token."'");
    $result->execute();
    $row = $result->fetch();

    echo $res = $row['image'];

    if(file_exists($res)){

        unlink($res);

        $result = $con->prepare("DELETE FROM job WHERE token_id= :memid");
        $result->bindParam(':memid', $token);
        $result->execute();

        echo "";
        echo "";
    }
    else{
        echo "";
        echo "";
    }
}


问:
how to know if a field is on a particular page?
The PDFbox content stream is done per page, but the fields come from the form which comes from the catalog, which comes from the pdf doc itself. So I'm not sure which fields are on which pages, and its causing to write text out to incorrect locations/pages.

ie. I'm processing fields per page, but not sure which fields are on which pages.

Is there a way to tell which field is on which page? Or, is there a way to get just the fields on the current page?

Thank you!

Mark

code snippet:

```<code>PDDocument pdfDoc = PDDocument.load(file);
PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();

// Get field names
List<PDField> fieldList = acroForm.getFields();
List<PDPage> pages = pdfDoc.getDocumentCatalog().getAllPages();
for (PDPage page : pages) {
  PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page, true, true, true);
  processFields(acroForm, fieldList, contentStream, page);
  contentStream.close();
}
</code>```

答:
General solution for single or multiple widget of (duplicate qualified name  of single page)..

```<code>List<PDAnnotationWidget>  widget=field.getWidgets();
PDDocumentCatalog catalog = doc.getDocumentCatalog();
for(int i=0;i<widget.size();i++) {
int pageNumber = 1+ catalog.getPages().indexOf(field.getWidgets().get(i).getPage());
</code>```

/* field co ordinate also can get here for single or multiple both it will work..*/

//PDRectangle r= widget.get(i).getRectangle();

```<code>}
</code>```

Body:
The PDFbox content stream is done per page, but the fields come from the form which comes from the catalog, which comes from the pdf doc itself. So I'm not sure which fields are on which pages, and its causing to write text out to incorrect locations/pages.

ie. I'm processing fields per page, but not sure which fields are on which pages.

Is there a way to tell which field is on which page? Or, is there a way to get just the fields on the current page?

Thank you!

Mark

code snippet:

PDDocument pdfDoc = PDDocument.load(file);
PDDocumentCatalog docCatalog = pdfDoc.getDocumentCatalog();
PDAcroForm acroForm = docCatalog.getAcroForm();

// Get field names
List<PDField> fieldList = acroForm.getFields();
List<PDPage> pages = pdfDoc.getDocumentCatalog().getAllPages();
for (PDPage page : pages) {
  PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page, true, true, true);
  processFields(acroForm, fieldList, contentStream, page);
  contentStream.close();
}

Body:
General solution for single or multiple widget of (duplicate qualified name  of single page)..

List<PDAnnotationWidget>  widget=field.getWidgets();
PDDocumentCatalog catalog = doc.getDocumentCatalog();
for(int i=0;i<widget.size();i++) {
int pageNumber = 1+ catalog.getPages().indexOf(field.getWidgets().get(i).getPage());

/* field co ordinate also can get here for single or multiple both it will work..*/

//PDRectangle r= widget.get(i).getRectangle();

}


问:
Reading JSON file in angular 2 application
I have a file data.json which I want to import in my angular 2 application. I am getting file with HTML input tag.

```<code><input type="file" (change)="onImport($event)"/>
</code>```

in my typescript file I want to read this data.json file and store the content of file in JSON array. I have searched but couldn't find any way to read file or any library which could help me with this.

答:
Use FileReader from the File API and JSON.parse() method like:

```<code>  onImport(event) {
    var file = event.srcElement.files[0];
    if (file) {
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            console.log(JSON.parse(evt.target.result));
        }
        reader.onerror = function (evt) {
            console.log('error reading file');
        }
    }
  }
</code>```

Body:
I have a file data.json which I want to import in my angular 2 application. I am getting file with HTML input tag.

<input type="file" (change)="onImport($event)"/>

in my typescript file I want to read this data.json file and store the content of file in JSON array. I have searched but couldn't find any way to read file or any library which could help me with this.

Body:
Use FileReader from the File API and JSON.parse() method like:

  onImport(event) {
    var file = event.srcElement.files[0];
    if (file) {
        var reader = new FileReader();
        reader.readAsText(file, "UTF-8");
        reader.onload = function (evt) {
            console.log(JSON.parse(evt.target.result));
        }
        reader.onerror = function (evt) {
            console.log('error reading file');
        }
    }
  }


问:
Using Terraform with docker-compose and nginx-proxy
Has anyone tried using all these tools together?

I'm currently using nginx-proxy and docker-compose for a four-container solution.

I'm now trying to make deployment better/faster/cheaper and think terraform might be the piece I'm now looking for.

My question is - does terraform work with docker-compose? Or is there too much overlap between them?

Thanks for any advice!

答:
You can run single or multiple docker container in Terraform using the docker provider.

https://www.terraform.io/docs/providers/docker/index.html

Sample nginx terraform config

```<code>provider "docker" {
  host = "tcp://ec2-xxxxxxx.compute.amazonaws.com:2375/"
}
resource "docker_image" "nginx" {
  name = "nginx:1.11-alpine"
}
resource "docker_container" "nginx-server" {
  name = "nginx-server"
  image = "${docker_image.nginx.latest}"
  ports {
    internal = 80
    external = 80
  }
  volumes {
    container_path  = "/usr/share/nginx/html"
    host_path = "/home/scrapbook/tutorial/www"
    read_only = true
  }
}
</code>```

Body:
You can run single or multiple docker container in Terraform using the docker provider.

https://www.terraform.io/docs/providers/docker/index.html

Sample nginx terraform config

provider "docker" {
  host = "tcp://ec2-xxxxxxx.compute.amazonaws.com:2375/"
}
resource "docker_image" "nginx" {
  name = "nginx:1.11-alpine"
}
resource "docker_container" "nginx-server" {
  name = "nginx-server"
  image = "${docker_image.nginx.latest}"
  ports {
    internal = 80
    external = 80
  }
  volumes {
    container_path  = "/usr/share/nginx/html"
    host_path = "/home/scrapbook/tutorial/www"
    read_only = true
  }
}


问:
PopupWindow how to change icon and background programmatically?
Have is xml file for PopupWindow:

How to programmatically replace the icon and Backgroud in this xml?

答:
First initialize the imageView you want to change. Like this:

```<code>ImageView imageView = (ImageView) findViewById(R.id.yourImageViewId);
</code>```

then

```<code>imageView.setImageResource(R.drawable.yournewIconId);
</code>```

Similarly you can do it for the background change.

Body:
First initialize the imageView you want to change. Like this:

ImageView imageView = (ImageView) findViewById(R.id.yourImageViewId);

then

imageView.setImageResource(R.drawable.yournewIconId);

Similarly you can do it for the background change.


问:
React-google-maps warnings
I've started recently to learn React and I want to build a React App with Google Maps API so I downloaded React-google-maps package but its documentation is outdated. I have this sample code. Console logs error:

process.env.ENV is not defined, assuming 'prod' env

Accessing PropTypes via the main React package is deprecated

Accessing createClass via the main React package is deprecated.

TL:DR How to fix this code

import React from "react";
import ReactDOM from "react-dom";
import {
  withGoogleMap,
  GoogleMap,
  Marker,
  InfoWindow,
} from "react-google-maps";

const MapInit = withGoogleMap(props => (
  <GoogleMap
    ref={props.onMapLoad}
    defaultZoom={1}
    defaultCenter={{ lat: -25.363882, lng: 131.044922 }}
  >
  </GoogleMap>
));
class MapContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      markers: [
        {}
      ],
    };
    this.handleMapLoad = this.handleMapLoad.bind(this);
  }
  handleMapLoad(map) {
    this._mapComponent = map;
  }
  render() {
    return (
      <div style={{height: `100%`}}>
        <MapInit
          containerElement={
            <div style={{ height: `100%` }} />
          }
          mapElement={
            <div style={{ height: `100%` }} />
          }
          onMapLoad={this.handleMapLoad}
        />

    );
  }
}

export default MapContainer;```

答:
https://github.com/tomchentw/react-google-maps

Versions

For React >= 15.5, use next
  tag on npm

For React < 15.5, use latest
  tag on npm

You need to update to v7.0.0 of react-google-maps to get rid of the deprecation warnings.

You might want to consider using google-map-react instead, which has more community activity and looks to be of higher quality.

Title: React-google-maps warnings


问:
show text in one line only followed by ... in handson table dynamic columns
In my handSon table I want to show the text in one line only and after that there should be ..., if there is more text.

$scope.textRenderer = function (instance, td, row, col, prop, value, cellProperties) {
            if (cellProperties) {

                var template;
                template = ['' + value + ''].join('');
                while (td.firstChild) {
                    td.removeChild(td.firstChild);
                }

                if (!td.firstChild) {
                    td.appendChild($compile(template)($scope)[0]);
                }
            }
            return td;
        };```

I have tried the above code but the ellipsis is not shown.

答:
What you're trying to do does not work on inline elements.

Give your span tag display:block;

Body:
In my handSon table I want to show the text in one line only and after that there should be ..., if there is more text.

$scope.textRenderer = function (instance, td, row, col, prop, value, cellProperties) {
            if (cellProperties) {

                var template;
                template = ['' + value + ''].join('');
                while (td.firstChild) {
                    td.removeChild(td.firstChild);
                }

                if (!td.firstChild) {
                    td.appendChild($compile(template)($scope)[0]);
                }
            }
            return td;
        };

I have tried the above code but the ellipsis is not shown.


问:
jQuery Div Notification Alert Syntax on Pusher Notification
I am pushing an event via pusher to the following code:
I am not getting the expected html from  alertDivNotification.

```<code><!-- output -->
<div class="alert alert-danger alert-server" role="alert">Hello</div>

<!-- expected -->
<div class="alert alert-danger alert-server" role="alert">
  <button type="button" class="close" data-dismiss="alert">×</button>
  <strong>Moving Servers</strong> Hello
</div>
</code>```

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
  var alertDivNotification = $('
<button type="button" class="close" data-dismiss="alert">×</button>Moving Servers message
');
  alertDivNotification.html(data.message);
  $('#alertDivContainer').prepend(alertDivNotification);
});
```

答:
The problem is with:

```<code>var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button><strong>Moving Servers</strong> message</div>');
alertDivNotification.html(data.message);
</code>```

I assume you want the data.message from the Pusher event to replace the literal word "message" in your HTML. But the jQuery .html method is replacing all children of your
, including your button. Instead, use .append, appending a text node constructed from the data.message. Like this:

```<code>var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button><strong>Moving Servers</strong></div>');
alertDivNotification.append(document.createTextNode(data.message));
</code>```

(Edit) If you want to add a data.notification_title to your Pusher event and display that, you can:

```<code>var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button></div>');
alertDivNotification.append($('<strong></strong>').append(document.createTextNode(data.notification_title)));
alertDivNotification.append(document.createTextNode(data.message));
</code>```

Body:
I am pushing an event via pusher to the following code:
I am not getting the expected html from  alertDivNotification.

Hello

  <button type="button" class="close" data-dismiss="alert">×</button>
  Moving Servers Hello

var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data) {
  var alertDivNotification = $('
<button type="button" class="close" data-dismiss="alert">×</button>Moving Servers message
');
  alertDivNotification.html(data.message);
  $('#alertDivContainer').prepend(alertDivNotification);
});

Body:
The problem is with:

var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button><strong>Moving Servers</strong> message</div>');
alertDivNotification.html(data.message);

I assume you want the data.message from the Pusher event to replace the literal word "message" in your HTML. But the jQuery .html method is replacing all children of your <div>, including your button. Instead, use .append, appending a text node constructed from the data.message. Like this:

var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button><strong>Moving Servers</strong></div>');
alertDivNotification.append(document.createTextNode(data.message));

(Edit) If you want to add a data.notification_title to your Pusher event and display that, you can:

var alertDivNotification = $('<div class="alert alert-danger alert-server" role="alert"><button type="button" class="close" data-dismiss="alert">×</button></div>');
alertDivNotification.append($('<strong></strong>').append(document.createTextNode(data.notification_title)));
alertDivNotification.append(document.createTextNode(data.message));


问:
How is the active class added to the correct nav item inside scroll my event?
So I have a single page where the active menu item gets highlighted when you scroll to its corresponding section.

My code works, but I don't understand why, specifically this part:

document.querySelector('nav a[href="' + anchorID + '"]').classList.add("active");

On window.onscroll the for loop collects all the anchors (nav a) from the menu

Then I get access to individual anchorIDs (hrefs) with:

var anchorID = anchorsArray[i].getAttribute("href");

What I don't understand, is how the .activeclass gets added to the correct anchorID based on the current section inside the viewport — when no comparison is made between the section id and the corresponding anchor href. E.g. the href & section id:

Section 2

..are never compared on scroll.

DEMO: https://jsfiddle.net/zgpzrvns/

All the JS

    (function() {
      var anchorsArray = document.querySelectorAll("nav a");
      var sections = document.querySelectorAll("section");
      var sectionsArray = [];

      // Collect all sections and push to sectionsArray
      for (var i = 0; i < sections.length; i++) {
        var section = sections[i];
        sectionsArray.push(section);
      }

      window.onscroll = function() {
        var scrollPosition = window.pageYOffset;

        for (var i = 0; i < anchorsArray.length; i++) {
          // Get hrefs from each anchor
          var anchorID = anchorsArray[i].getAttribute("href");

          var sectionHeight = sectionsArray[i].offsetHeight;
          var sectionTop = sectionsArray[i].offsetTop;

          if (
            scrollPosition >= sectionTop &&
            scrollPosition < sectionTop + sectionHeight
          ) {
            /**
            * I don't understand how querySelector finds & adds the active
            * class to the correct anchor, when no comparison is made between the
            * section ID (that is inside current section in viewport) and the
            * anchors ID from anchorsArray
            */
            document
              .querySelector('nav a[href="' + anchorID + '"]')
              .classList.add("active");
          } else {
            document
              .querySelector('nav a[href="' + anchorID + '"]')
              .classList.remove("active");
          }
        }
      };
    })();```

In summary: how is the active class added to correct anchor ID, when the corresponding section ID inside the viewport on scroll (when section ID is never detected inside the scroll event?)

I'm so confused about this, and I bet it's something silly I'm overlooking!

Would greatly appreciate some input! :-)

答:
In short:
It doesn't need to compare any ids, because on scroll you loop over all anchors in your navigation. For each you check, if the section at the same index is in the viewport. If so, you add the active class.

If you switch the positions of your navigation items, you'll see that it will add the active class to the wrong item, because it just checks the index.

If you need some more explanation, tell me. Going to edit the answer then.

Edit index explanation:

You have your navigation anchors in an array, and also your sections.

```<code>var anchorsArray = document.querySelectorAll("nav a");
var sections = document.querySelectorAll("section");
</code>```

You are looping your anchors array

```<code>for (var i = 0; i < anchorsArray.length; i++) {
</code>```

and then you get the height and top position of your section at the same index as your anchor (variable i)

```<code>var sectionHeight = sectionsArray[i].offsetHeight;
var sectionTop = sectionsArray[i].offsetTop;

if (
    scrollPosition >= sectionTop &&
    scrollPosition < sectionTop + sectionHeight
) {
</code>```

and then you set the active class if its true, or remove it, if its false.

So on each scroll your code does the following:

Get anchor one -> check if section one is in range -> If yes -> add active -> else remove active

Get anchor two -> check if section two is in range -> If yes -> add active -> else remove active

Get anchor three -> ... and so one

Body:
So I have a single page where the active menu item gets highlighted when you scroll to its corresponding section.

My code works, but I don't understand why, specifically this part:

document.querySelector('nav a[href="' + anchorID + '"]').classList.add("active");

On window.onscroll the for loop collects all the anchors (nav a) from the menu

Then I get access to individual anchorIDs (hrefs) with:

var anchorID = anchorsArray[i].getAttribute("href");

What I don't understand, is how the .activeclass gets added to the correct anchorID based on the current section inside the viewport — when no comparison is made between the section id and the corresponding anchor href. E.g. the href & section id:

Section 2

..are never compared on scroll.

DEMO: https://jsfiddle.net/zgpzrvns/

All the JS

    (function() {
      var anchorsArray = document.querySelectorAll("nav a");
      var sections = document.querySelectorAll("section");
      var sectionsArray = [];

      // Collect all sections and push to sectionsArray
      for (var i = 0; i < sections.length; i++) {
        var section = sections[i];
        sectionsArray.push(section);
      }

      window.onscroll = function() {
        var scrollPosition = window.pageYOffset;

        for (var i = 0; i < anchorsArray.length; i++) {
          // Get hrefs from each anchor
          var anchorID = anchorsArray[i].getAttribute("href");

          var sectionHeight = sectionsArray[i].offsetHeight;
          var sectionTop = sectionsArray[i].offsetTop;

          if (
            scrollPosition >= sectionTop &&
            scrollPosition < sectionTop + sectionHeight
          ) {
            /**
            * I don't understand how querySelector finds & adds the active
            * class to the correct anchor, when no comparison is made between the
            * section ID (that is inside current section in viewport) and the
            * anchors ID from anchorsArray
            */
            document
              .querySelector('nav a[href="' + anchorID + '"]')
              .classList.add("active");
          } else {
            document
              .querySelector('nav a[href="' + anchorID + '"]')
              .classList.remove("active");
          }
        }
      };
    })();

In summary: how is the active class added to correct anchor ID, when the corresponding section ID inside the viewport on scroll (when section ID is never detected inside the scroll event?)

I'm so confused about this, and I bet it's something silly I'm overlooking!

Would greatly appreciate some input! :-)

Body:
In short:
It doesn't need to compare any ids, because on scroll you loop over all anchors in your navigation. For each you check, if the section at the same index is in the viewport. If so, you add the active class.

If you switch the positions of your navigation items, you'll see that it will add the active class to the wrong item, because it just checks the index.

If you need some more explanation, tell me. Going to edit the answer then.

Edit index explanation:

You have your navigation anchors in an array, and also your sections.

var anchorsArray = document.querySelectorAll("nav a");
var sections = document.querySelectorAll("section");

You are looping your anchors array

for (var i = 0; i < anchorsArray.length; i++) {

and then you get the height and top position of your section at the same index as your anchor (variable i)

var sectionHeight = sectionsArray[i].offsetHeight;
var sectionTop = sectionsArray[i].offsetTop;

if (
    scrollPosition >= sectionTop &&
    scrollPosition < sectionTop + sectionHeight
) {

and then you set the active class if its true, or remove it, if its false.

So on each scroll your code does the following:

Get anchor one -> check if section one is in range -> If yes -> add active -> else remove active

Get anchor two -> check if section two is in range -> If yes -> add active -> else remove active

Get anchor three -> ... and so one


问:
Returning values with &&
What does it mean to return a value with &&? </p>

```<code>else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the traditional ' text-align' style of rule writing,
    // instead of textAlign
    name = name.replace(/([A-Z]) /g, " -$1" );
    name = name.toLowerCase();
    // Get the style object and get the value of the property (if it exists)
    var s = document.defaultView.getComputedStyle(elem, " ") ;
    return s && s.getPropertyValue(name) ;
</code>```

答:
return a && b means "return a if a is falsy, return b if a is truthy".

It is equivalent to

```<code>if (a) return b;
else return a;
</code>```

Title: Returning values with &&

Body:
What does it mean to return a value with &&?

else if (document.defaultView && document.defaultView.getComputedStyle) {

    // It uses the traditional ' text-align' style of rule writing,
    // instead of textAlign
    name = name.replace(/([A-Z]) /g, " -$1" );
    name = name.toLowerCase();
    // Get the style object and get the value of the property (if it exists)
    var s = document.defaultView.getComputedStyle(elem, " ") ;
    return s && s.getPropertyValue(name) ;

Body:
return a && b means "return a if a is falsy, return b if a is truthy".

It is equivalent to

if (a) return b;
else return a;


问:
Call to a member function query() on null in PHP
I am getting below error when I run my PHP code.

```<code>Call to a member function query() on null
</code>```

Below is the code,

```<code>function fetch_url($url_code) {
    $query = "SELECT * FROM `urls` WHERE `url_code` = ? ";

    $result = $this->db->query($query, array($url_code));
    if ($result) {
        return $result;
    } else {
        return false;
    }
}
</code>```

Please guide me how to remove this error.

答:
```<code>class Database {

public $host=DB_HOST;           // Specify localhost
public $username=DB_USER;       //Specify username
public $password=DB_PASSWORD;   // specify password
public $dbname=DB_NAME;         // specify database name

public $conn ;
public $error;

/*

* Class Constructor

*/

Public function __constructor() {

    // Call Connect Function

    $this->connect();

}

/*
*    Connector
*/

Public function connect() {

    //* Creating mySqli Class Object * //

 $this->conn  = new mysqli($this->host,$this->username,$this->password,$this->dbname);

  if (!$this->conn) {

      $this->error = "Connection failed :" .$conn->connect_error ;
      return false;

                    }

                            }

    /*
    * Select function
    */

    public function select($query) {

        /*  to avoid call to member function query() on Null Error

        Use this 2 lines of code */

         if ($this->conn === null) {
            $this->connect();
            }

        $results = $this->conn->query($query) or die($this->conn->error.__LINE__);

    /* If there is atleast one row in the table Condition is true / Return table Rows as per your sql query */

    if($results->num_rows > 0) {

                     return $results;

    }

                     else {

                         return false;

                          }
         } //Select Function Ends;

    } //Class ends here ..
</code>```

Body:
I am getting below error when I run my PHP code.

Call to a member function query() on null

Below is the code,

function fetch_url($url_code) {
    $query = "SELECT * FROM `urls` WHERE `url_code` = ? ";

    $result = $this->db->query($query, array($url_code));
    if ($result) {
        return $result;
    } else {
        return false;
    }
}

Please guide me how to remove this error.


问:
How to call an api from another api in expressjs?
I have an api like this:

```<code>app.get('/test', (req, res) => {
   console.log("this is test");
});
</code>```

and another api:

```<code>app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});
</code>```

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

答:
Simple solution is to define a method which can be called using both request routes. </p>

```<code>app.get('/test', (req, res) => {
   console.log("this is test");
    callMeMayBe();
});

callMeMayBe()
{
    //Your code here
}
</code>```

Body:
I have an api like this:

app.get('/test', (req, res) => {
   console.log("this is test");
});

and another api:

app.get('/check', (req, res) => {
   //I want to call "test" api without redirect to it.
});

I want to call "test" api in "check" api without redirect to "test" api, just do the function in the "test" api.
Above is the example code. 'Cause I dont' want to rewrite function from "test" api to "check"

Body:
Simple solution is to define a method which can be called using both request routes.

app.get('/test', (req, res) => {
   console.log("this is test");
    callMeMayBe();
});

callMeMayBe()
{
    //Your code here
}


问:
How do I search for a file in a directory using the terminal?
I'm trying to locate a file in a huge directory with a lot of other subdirectories and files.

What's the easiest way to find a given file_name.x in such directory tree?

答:
You could try

find path_to_huge_directory -type f -name "file_name.x"

This will search through all files in that directory and its subdirectories.


问:
How to get info about file compression using ImageIO?
I have a TIFF file and I'd like to know which compression it used - is there a way to achieve it using ImageIO? I unsuccessfully tried to get this info from IIOMetadata object. I initially create a BufferedImage from this file, process it and then try to save it with the same compression as original but with different name.

答:
Using the ImageIO API the following code will give you the compression (in a human-readable way):

```<code>ImageReader reader = ...;

IIOMetadata metadata = reader.getImageMetadata(0); // 0, first image
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
IIOMetadataNode compression = (IIOMetadataNode) root.getElementsByTagName("CompressionTypeName").item(0);
String compressionName = compression.getAttribute("value");

System.out.printf("Compression: %s", compressionName);
</code>```

Note that this compression name may not always match the compression type names supported by the plugin's ImageWriteParam (though it often does). The above will work for all plugins that supports the standard or "plug-in neutral" metadata format (most do).

In any case, a safer option if you want to keep the compression, is to use the COPY_FROM_METADATA compression mode in the ImageWriteParam (this is the default, so you don't need to specify it), and pass the entire metadata object to the write method (remember to pass it as image metadata and not stream metadata). This will work regardless of the metadata formats supported, as long as the reader and writer understands the same format.

The easiest way to achieve this, is probably to read using the ImageReader.readAll(..) method like this:

```<code>IIOImage iioimg = reader.readAll(0, readParam);  // image AND metadata in one go

RenderedImage image = iioimg.getRenderedImage(); // normally a BufferedImage
// ... image manipulation
iioimg.setRenderedImage(modifiedImage);          // in case the reference changed

writer.write(null, iioimg, writeParam);          // will preserve compression by default
</code>```

Small caveat: Some plugins have readers that reads more compressions than their corresponding writer can write. E.g. For TIFF, the reader might be able to read the now deprecated "Old style JPEG" compression, even though the writer only supports writing in the new "JPEG" compression.

Body:
Using the ImageIO API the following code will give you the compression (in a human-readable way):

ImageReader reader = ...;

IIOMetadata metadata = reader.getImageMetadata(0); // 0, first image
IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(IIOMetadataFormatImpl.standardMetadataFormatName);
IIOMetadataNode compression = (IIOMetadataNode) root.getElementsByTagName("CompressionTypeName").item(0);
String compressionName = compression.getAttribute("value");

System.out.printf("Compression: %s", compressionName);

Note that this compression name may not always match the compression type names supported by the plugin's ImageWriteParam (though it often does). The above will work for all plugins that supports the standard or "plug-in neutral" metadata format (most do).

In any case, a safer option if you want to keep the compression, is to use the COPY_FROM_METADATA compression mode in the ImageWriteParam (this is the default, so you don't need to specify it), and pass the entire metadata object to the write method (remember to pass it as image metadata and not stream metadata). This will work regardless of the metadata formats supported, as long as the reader and writer understands the same format.

The easiest way to achieve this, is probably to read using the ImageReader.readAll(..) method like this:

IIOImage iioimg = reader.readAll(0, readParam);  // image AND metadata in one go

RenderedImage image = iioimg.getRenderedImage(); // normally a BufferedImage
// ... image manipulation
iioimg.setRenderedImage(modifiedImage);          // in case the reference changed

writer.write(null, iioimg, writeParam);          // will preserve compression by default

Small caveat: Some plugins have readers that reads more compressions than their corresponding writer can write. E.g. For TIFF, the reader might be able to read the now deprecated "Old style JPEG" compression, even though the writer only supports writing in the new "JPEG" compression.


问:
How to export (copy) a Grafana query
I'm using grafana to query elasticsearch for plotting some charts. Now, i would like to replicate the same charts in my website, and to do so I've to query elastic on my code and then plot the chart.

Since the query will be the same as the one created with grafana, is there a way to know (and thus copy) the query that grafana generates for plotting the chart?
If i check the exporting of the chart it seems more a grafana syntaxt than an elastic query.

Thanks

答:
With the Grafana web page opened, launch the developer tools of the specific browser you are using (F12 in Chrome).

In the network section, you will see the queries Grafana calls when it refreshes its charts.

You can look at the "_msearch" requests, and in the "payload" section you will see the exact elasticsearch query its using.

Title: How to export (copy) a Grafana query


问:
Quickest way to build a bunch of DLL files with the same settings in VS 2008
I'm currently porting a POSIX C++ application to run on Windows without Cygwin or anything. No problem so far. Now, the application (ZNC, an IRC bouncer, in case you're interested) supports loading modules from .so shared library files on Linux/BSD etc.

I ported the main executable without much of a problem, all wrapped into a VS 2008 project file and stuff. Now, said modules are all separate .cpp files which can't be linked into the executable as they all export symbols like GetVersion(). And it isn't feasible anyway.

So, to cut a long story short, I want to (have to) compile all the modules (over 20) into separate DLL files. I don't want to create a single VS project for each however. Which means I'll probably have to create a makefile? Or something the like? I've never done that before on Windows, so that's my question. What is the best approach to compile a bunch of .cpps into separate DLL files (with the same settings, all stored conveniently in one place/file)?

Thanks in Advance!
I.R.

答:
cmake works pretty well with MSVC, and is cross-platform. You can list all your libraries in one (or, at your option, one per dll) CMakeList.txt file and it will generate a solution with all the project files. On unix, it generates makefiles.

Oh, and in Windows, make is called nmake, if I'm not mistaken.

OwnerDisplayName: KiNgMaR


问:
formArray in a tbody with only one colum to be validated
I'm having a hard time using formArray. We have a list of a class:

```<code>class item {
    value: number;
    name: string
    status: string
}
</code>```

Only the property value should be validated and is bounded to an input field.

We managed to display the readonly properties (I don't know if this is the correct way to do this tho).

We didn't manage to bind the input field (the samples I found they don't use ngModel, so I'm avoiding it)

We also don't know how to add the validation only for the value property.

So here are my questions:

How to bind properly the readonly fields?

How to bind the input field without ngModel?

How to create validation for the value property only?

That is our HTML:

```<code><div [formGroup]="parentForm">
  <div *ngIf="items">
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Value</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody formArrayName="itemsForm">
        <tr *ngFor="let item of parentForm.controls.itemsForm.controls; let i=index">
          <td><span>{{ item.value.name }}</span></td>
          <td>
            <input type="number" [formControlName]="i" tabindex="1" autocomplete="off" /> <!--How do I show the value here?-->
          </td>
          <td>
            <app-status [status]="item.value.status"></app-status>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
</code>```

That is how we bind our form:

```<code>public ngOnInit(): void {

    let controls = new Array<FormControl>();

    this.items.forEach((item) => controls.push(new FormControl(item)));

    this.parentForm.addControl("itemsForm", new FormArray(controls));

    console.log(this.parentForm);
}
</code>```

答:
You'd need to use nested form groups inside the form array. I like to inject formbuilder in constructor, here in this sample I refer to it with fb.

So build your form...

ngOnInit() {
  this.parentForm = this.fb.group({
    itemsForm: this.fb.array([])
  });
  // add below to the callback instead after you have received your data!
  this.populateForm();
}
```

<p>and the <code>populateForm</code>:</p>

<pre class="lang-ts prettyprint-override"><code>populateForm() {
  const control = <FormArray>this.parentForm.controls['itemsForm'];
  // the data you have received, for each object create a form group
  this.items.forEach(item => {
    control.push(this.initItems(item))
  })
}

initItems(item) {
  // create a formgroup for each item
  return this.fb.group({
    value: [item.value, Validators.required], // set required or whatever else
    name: [item.name]
    status: [item.status]
  })
}
</code>```

Then in your view iterate this formarray and display input field for value and the others can be shown just as plain text:

....

    <ng-container formGroupName="{{i}}">
       <input formControlName="value" />
       Name: {{item.value.name}}
       Status: {{item.value.status}}
    </ng-container>

....
```

You'd also perhaps want to actually use variables, to which you assign the different form control "paths" and not use e.g... parentForm.controls.itemsForm.controls but that is just a suggestion :)

Body:
I'm having a hard time using formArray. We have a list of a class:

class item {
    value: number;
    name: string
    status: string
}

Only the property value should be validated and is bounded to an input field.

We managed to display the readonly properties (I don't know if this is the correct way to do this tho).

We didn't manage to bind the input field (the samples I found they don't use ngModel, so I'm avoiding it)

We also don't know how to add the validation only for the value property.

So here are my questions:

How to bind properly the readonly fields?

How to bind the input field without ngModel?

How to create validation for the value property only?

That is our HTML:

          Name
          Value
          Status

          {{ item.value.name }}

            <input type="number" [formControlName]="i" tabindex="1" autocomplete="off" />

            <app-status [status]="item.value.status"></app-status>

That is how we bind our form:

public ngOnInit(): void {

    let controls = new Array<FormControl>();

    this.items.forEach((item) => controls.push(new FormControl(item)));

    this.parentForm.addControl("itemsForm", new FormArray(controls));

    console.log(this.parentForm);
}

Body:
You'd need to use nested form groups inside the form array. I like to inject formbuilder in constructor, here in this sample I refer to it with fb.

So build your form...

ngOnInit() {
  this.parentForm = this.fb.group({
    itemsForm: this.fb.array([])
  });
  // add below to the callback instead after you have received your data!
  this.populateForm();
}

and the populateForm:

populateForm() {
  const control = <FormArray>this.parentForm.controls['itemsForm'];
  // the data you have received, for each object create a form group
  this.items.forEach(item => {
    control.push(this.initItems(item))
  })
}

initItems(item) {
  // create a formgroup for each item
  return this.fb.group({
    value: [item.value, Validators.required], // set required or whatever else
    name: [item.name]
    status: [item.status]
  })
}

Then in your view iterate this formarray and display input field for value and the others can be shown just as plain text:

....
<tbody formArrayName="itemsForm">
  <tr *ngFor="let item of parentForm.controls.itemsForm.controls; let i = index" >
    <ng-container formGroupName="{{i}}">
       <td><input formControlName="value" /></td>
       <td>Name: {{item.value.name}}</td>
       <td>Status: {{item.value.status}}</td>
    </ng-container>
  </tr>
</tbody>
....

You'd also perhaps want to actually use variables, to which you assign the different form control "paths" and not use e.g... parentForm.controls.itemsForm.controls but that is just a suggestion :)


问:
How to add a collections of parameters to an SqlCommand before query execution in C#?
I have this code where I want to add a collections of Parameters to an SqlCommand.

```<code>public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}
</code>```

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?

答: The only way to "optimize" that scenario is to already have a DbCommand instance sat around with the correct command-text / type, and the parameters already added, and you simply set the .Value of each in turn before executing it against the connection. However, this demands careful synchronization if you are using multiple connections / threads, so would need to be done carefully. Ultimately, anything you do here is going to be nothing compared to the latency of talking to a database, so: it is very likely that this is simply premature optimization and yak shaving - meaning: you might feel like you've achieved something useful here, but all you're actually doing is spending your time.

Body:
I have this code where I want to add a collections of Parameters to an SqlCommand.

public void AddParameters(Dictionary<string, object> parameters)
{
    if (parameters == null)
        return;

    foreach(KeyValuePair<string, object> keyValue in parameters)
    {
        sqlCommand.Parameters.AddWithValue(keyValue.Key, keyValue.Value);
    }
}

I want to make it more efficienty without using a loop because I can have a very large collection of parameters. Is there any way to add the entire collection with a single function?


问:
python incorrectly calculates number
So, this was in my exam paper and I was really confused

```<code>def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()
</code>```

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

```<code>num1: 45
num2: 90
</code>```

but why is the output:

```<code>num1: 45
num2: 67.5
</code>```

?

答:
```<code>    num1 = input("num1: ")  # 60
    num2 = input("num2: ")  # 18
    num1 = int(num2)*2.5  # 18 * 2.5 = 45
    num2 = int(num1)*1.5  # 45 * 1.5 = 67.5
 `  print("num1:", num1, "num2:", num2)
</code>```

In comment lines, answer is calculated

Title: python incorrectly calculates number

Body:
So, this was in my exam paper and I was really confused

def num_input():
    num1 = input("num1: ")
    num2 = input("num2: ")
    num1 = int(num2)*2.5
    num2 = int(num1)*1.5
    print("num1:", num1, "num2:", num2)

num_input()

say that num1 = 60, and num2 = 18, shouldn't the new numbers be:

num1: 45
num2: 90

but why is the output:

num1: 45
num2: 67.5

?

Body:
    num1 = input("num1: ")  # 60
    num2 = input("num2: ")  # 18
    num1 = int(num2)*2.5  # 18 * 2.5 = 45
    num2 = int(num1)*1.5  # 45 * 1.5 = 67.5
 `  print("num1:", num1, "num2:", num2)

In comment lines, answer is calculated


问:
Extract the path from a full file-name in VBA
I m new in VBA and below is my code which is not working, can any one of u can help?

```<code>Dim nPath1() As String
nPath1() = Split(nPath, "\")

'Declare path as integer
 Dim path As Integer
'Getting array length
 path = UBound(nPath1())
 Dim lastname As String
 'For Loop
 For i = 0 To path-1
     lastname += nPath1(i)+"\"
 Next i
</code>```

The above code is not working; my path string is Root\zTrash - No longer needed\NOC\NOC and what I want is Root\zTrash - No longer needed\NOC.

答:
If you are fan of long formulas, this is another option:

```<code>left(nPath,len(nPath)-len(split(nPath,"\")(ubound(split(nPath,"\")))))
</code>```

The idea is that you split by \

Then you get the last value in the
array (with ubound, but you split twice)

Then you get the difference between it and the whole length

Then you pass this difference to the left as a parameter

Body:
I m new in VBA and below is my code which is not working, can any one of u can help?

Dim nPath1() As String
nPath1() = Split(nPath, "\")

'Declare path as integer
 Dim path As Integer
'Getting array length
 path = UBound(nPath1())
 Dim lastname As String
 'For Loop
 For i = 0 To path-1
     lastname += nPath1(i)+"\"
 Next i

The above code is not working; my path string is Root\zTrash - No longer needed\NOC\NOC and what I want is Root\zTrash - No longer needed\NOC.

Body:
If you are fan of long formulas, this is another option:

left(nPath,len(nPath)-len(split(nPath,"\")(ubound(split(nPath,"\")))))

The idea is that you split by \

Then you get the last value in the
array (with ubound, but you split twice)

Then you get the difference between it and the whole length

Then you pass this difference to the left as a parameter


问:
Convert ASP.NET MDF to MySQL Database?
How to convert ASPNETDB.MDF mssql database to MySql which works with ASp.NET</p>

答:
Here is a tool:

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
http://www.bullzip.com/products/a2m/info.php

Title: Convert ASP.NET MDF to MySQL Database?


问:
I want to move 100 out of 1Million files of a particular extension to a target folder in linux
I have a folder(/DIR/SRC) containing 1 Million files with different types of extensions.
I would like to pick a particular extension files from the SRC folder, may be 1000 at a time and move to a target folder which is at /DIR/TGT.
The file name has the format 1234_XXXX-XXXX_TIMESTAMP.ext</p>

答:
This will move all files with .your_extension in current folder to your new path

```<code>mv *.your_ext your/new/path
</code>```

Body:
This will move all files with .your_extension in current folder to your new path

mv *.your_ext your/new/path


问:
Objective -C Call back doesnot working with an unfortunate background crash
I'm trying to send a call back listener from a completion block. I initiate callback in custom UIView & completion block executes from parent viewcontroller (where UIView subviewed). Here is the code... (I dont want to use delegate)

Declaration of Call-Back in ViewController.h

```<code>typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;
-(void) exportCompletionBlock:(ExportCompletion)callback;
</code>```

Initialization & Implementation of Call-Back in ViewController.m

```<code>-(void) exportCompletionBlock:(ExportCompletion)callback
{
    if (callback) {
        self.exportBlock = callback;
    }
}
</code>```

Implementation (call) from Completion handler (its also in ViewController.m)

```<code>-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}
</code>```

Call back operation in uicustomview... CustomUIView.m

```<code>-(void) initUIView{
    [(ViewController*)[[self superview] nextResponder] exportCompletionBlock:^(BOOL success, NSURL *url) {
    if (success) {
        doing something...
    }
}];
</code>```

I can use delegate here but I want to use call back. I'm very new with call back. I like to know why I'm having the crash (its from background - so dont get the reason) & how do I optimize the code?

答:
If [(ViewController*)[[self superview] nextResponder] returns nil that might be a reason for crash. But using [[self superview] nextResponder] is not a good practice. Lets try a completion handler. I try to give you an example.

Declaration of Call-Back in ViewController.h

```<code>typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;
</code>```

In your viewcontroller ViewController.m no need to assign exportCompletionBlock . Just assign when you need it. For an example you have a delegate in your CustomView which is implemented in ViewController.m.

In your CustomUIView.h add this

```<code>typedef void(^ExportCompletion)(BOOL success, NSURL* url);

@protocol CustomUIViewDelegate <NSObject>
- (void) startExport:(ExportCompletion)completionBlock;
@end
</code>```

Call your delegate from your desired event like

In your CustomUIView.m

```<code>- (IBAction)ButtonTapped:(UIButton *)sender {
    [self.delegate startExport:^(BOOL success, NSURL *url) {
        if (success) {
            doing something...
        }
    }];
}
</code>```

In your ViewCOntroller.m code remain same but with a slide modification a little

Same as it was

```<code>-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}
</code>```

Implement the delegate in ViewCOntroller.m

```<code>- (void) startExport:(ExportCompletion)completionBlock{
    self.exportBlock = completionBlock;
    the thing you want to do...
}
</code>```

This is a way of handling a completion block. I dont know how much it'll help you. It's just a new way to implement your code. & It helps you prevent use of [[self superview] nextResponder] view dependence.

Body:
I'm trying to send a call back listener from a completion block. I initiate callback in custom UIView & completion block executes from parent viewcontroller (where UIView subviewed). Here is the code... (I dont want to use delegate)

Declaration of Call-Back in ViewController.h

typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;
-(void) exportCompletionBlock:(ExportCompletion)callback;

Initialization & Implementation of Call-Back in ViewController.m

-(void) exportCompletionBlock:(ExportCompletion)callback
{
    if (callback) {
        self.exportBlock = callback;
    }
}

Implementation (call) from Completion handler (its also in ViewController.m)

-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}

Call back operation in uicustomview... CustomUIView.m

-(void) initUIView{
    [(ViewController*)[[self superview] nextResponder] exportCompletionBlock:^(BOOL success, NSURL *url) {
    if (success) {
        doing something...
    }
}];

I can use delegate here but I want to use call back. I'm very new with call back. I like to know why I'm having the crash (its from background - so dont get the reason) & how do I optimize the code?

Body:
If [(ViewController*)[[self superview] nextResponder] returns nil that might be a reason for crash. But using [[self superview] nextResponder] is not a good practice. Lets try a completion handler. I try to give you an example.

Declaration of Call-Back in ViewController.h

typedef void(^ExportCompletion)(BOOL success, NSURL* url);
@property (nonatomic, copy) ExportCompletion exportBlock;

In your viewcontroller ViewController.m no need to assign exportCompletionBlock . Just assign when you need it. For an example you have a delegate in your CustomView which is implemented in ViewController.m.

In your CustomUIView.h add this

typedef void(^ExportCompletion)(BOOL success, NSURL* url);

@protocol CustomUIViewDelegate <NSObject>
- (void) startExport:(ExportCompletion)completionBlock;
@end

Call your delegate from your desired event like

In your CustomUIView.m

- (IBAction)ButtonTapped:(UIButton *)sender {
    [self.delegate startExport:^(BOOL success, NSURL *url) {
        if (success) {
            doing something...
        }
    }];
}

In your ViewCOntroller.m code remain same but with a slide modification a little

Same as it was

-(void)blockAlertAppear:(float)progress{
    if(EXPORT_SESSION_COMPLETED!=progress)
        doing something...
    if(EXPORT_SESSION_COMPLETED==progress){
        self.exportBlock(YES, mCompositor.url);
    }
}

Implement the delegate in ViewCOntroller.m

- (void) startExport:(ExportCompletion)completionBlock{
    self.exportBlock = completionBlock;
    the thing you want to do...
}

This is a way of handling a completion block. I dont know how much it'll help you. It's just a new way to implement your code. & It helps you prevent use of [[self superview] nextResponder] view dependence.


问:
Sed remove NULL but only when the NULL means empty or no value
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
</code>```

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

```<code>sed -i 's/NULL//g'
</code>```

However, how do we handle IF we have the following?

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

```<code>| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!

答:
```<code>$ cat mysql.txt | sed -r 's/(\| )NULL( \|)/\1\2/g'
| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |
</code>```

will only remove capital NULL fields delimited by the opening and closing pipe symbols alone.

It will keep your origin column "| NULL|" in the line "| 3  | NULL AND VOID | DJ Null Bee| NULL| 2016-05-13 |" as well.

Body:
Exporting a table from MySQL where fields that have no value will have the keyword NULL within.

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |

I have written a script to automatically remove all occurrences of NULL using a one-liner sed, which will remove the NULL in date column correctly:

sed -i 's/NULL//g'

However, how do we handle IF we have the following?

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL | NULL |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Apparently, the global search and replace all occurrences of NULL will be removed, where even "ALA PUHU MINULLE" will become "ALA PUHU MIE", which is incorrect.

I suppose the use of regex perhaps can be useful to apply the rule? But if so, will "DJ Null Bee" be affected or will it become "DJ Bee"? The desired outcome should really be:

| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | DJ Null Bee| | 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

Given that NULL is a special keyword for any databases, but there is no stopping anyone from calling themselves a DJ NULL, or have the word NULL because it means differently in another language.

Any ideas on how to resolve this? Any suggestions welcomed. Thank you!

Body:
$ cat mysql.txt | sed -r 's/(\| )NULL( \|)/\1\2/g'
| id | name | nickname | origin | date |
| 1  | Joe  | Mini-J   | BRAZIL |  |
| 2  | Dees | DJ Null Bee| US| 2017-04-01 |
| 3  | NULL AND VOID | NULLZIET | NULL| 2016-05-13 |
| 4  | Pablo | ALA PUHU MINULLE | GERMANY| 2017-02-14 |

will only remove capital NULL fields delimited by the opening and closing pipe symbols alone.

It will keep your origin column "| NULL|" in the line "| 3  | NULL AND VOID | DJ Null Bee| NULL| 2016-05-13 |" as well.


问:
how to allow only one IAM user to be able to upload files to S3 without it being able to list the directories in S3 bucket?
in policy of a IAM user i added:

```<code>    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PermissionForObjectOperations",
            "Effect": "Allow",
            "Action": [
                "s3:putObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket-name/*"
            ]
        }
    ]
}
</code>```

and when i try to upload a file using below code:

```<code>var params = {
    Body: 'some body',
    Bucket: 'my-bucket-name',
    Key: 'exampleobject',
    ServerSideEncryption: 'AES256',
    Tagging: 'key1=value1&key2=value2'
};
s3.putObject(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});
</code>```

i get the following error:

message: 'Access Denied',   code: 'AccessDenied',

答: i needed to add "s3:PutObjectTagging"</p>

Body:
in policy of a IAM user i added:

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "PermissionForObjectOperations",
            "Effect": "Allow",
            "Action": [
                "s3:putObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket-name/*"
            ]
        }
    ]
}

and when i try to upload a file using below code:

var params = {
    Body: 'some body',
    Bucket: 'my-bucket-name',
    Key: 'exampleobject',
    ServerSideEncryption: 'AES256',
    Tagging: 'key1=value1&key2=value2'
};
s3.putObject(params, function(err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log(data);           // successful response
});

i get the following error:

message: 'Access Denied',   code: 'AccessDenied',

Body: i needed to add "s3:PutObjectTagging"


问:
Redmine Custom Query to return only specific columns
How to filter Redmine issues to only include specified columns, when using the REST API xml/json format?

I have a custom query to obtain specific columns of issues:

Filter set to "status(open)" and "Due Date(any)"

Options / Selected Columns set to "Due Date" (To only return the ID and the Due Date in the response)

These are two ways of accessing it:

A /issues?query_id=myqueryid

B /issues.xml?query_id=myqueryid

When i run A in my browser, the correct response is given, containing only the id and the due date. In contrast to B, now every field (ie. id, description, start date,...) is included in the response.

I also tried to add a "fields" value as some other apis suggest, but to no avail (ie. /issues.xml?issue_id=1337&fields=due_date,etc).

答:
Redmine's REST API (i.e. the JSON and XML APIs) always returns all base fields of filtered issues. You can optionally include additional fields like watchers, journals, issue relations, ... by using the include mechanism describe in the API docs

When using the API, the client is supposed to fetch any fields it desires from the response on their own. The feature to show a tailored HTML table with selected columns as done in the web UI is considered not very useful for the API use-case right now.


问:
Porting ajaxified pages from IE to firefox/chrome
I need to port an old IE-only ajax webapp to a more modern browser. What are the differences in xmlhttprequest behavior that i should be aware of? Are the DOM differences more important?

Any help is appreciated.

答:
Not an answer to your question, but the best thing would probably be to port it to a modern library like jQuery that will work in any fairly modern browser, including IE.

It will probably require you to rewrite large parts of the application, but the resulting code is very likely to be much simpler and smaller than the old one. jQuery has shorthand notation and robust functions for most everyday use cases.

For example, see the jQuery Ajax functions


问:
MKMapView contraints in storyboard issue
I have this constaints for map view

But I have this error

If I replace map view with UIView, everything is OK

Update

To reproduce you need to set settings of view controller like this:

答:
I experienced the same issue when I tried to put an MKMapView as a full screen view. To do so I set:

Center horizontally

Center vertically

Equal widths

Equal heights

These above are referred to the MKMapView's superview (the main controller view). And xCode kept saying me "Error: missing constraints for Y position". I had never seen this error doing the way I did. I solved with these other four constraints (equivalent in my opinion):

Leading space 0

Trailing space 0

Top space 0

Bottom space 0

Always referred to the MKMapView's superview (the main controller view).


问:
Continue with transaction after exception - JPA
I am using JPA with Spring. I am trying to do batch import. If there is problem with batch import then I would like to insert individually, and if this fails also then I would like to save to duplicates table. I wrote a logic for this but I get this error everytime:

```<code>Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
</code>```

Mine setting for JPA are like this:

```<code>@Bean(name = "dataSource", destroyMethod = "")
  public DataSource getDataSource() {
    return new JndiDataSourceLookup().getDataSource(props.getDbJndiName());
  }

  @Bean
  public JpaVendorAdapter getHibernateJpaVendorAdapter() {
    return new HibernateJpaVendorAdapter();
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean();
    lcemfb.setDataSource(getDataSource());
    lcemfb.setPersistenceUnitName("MyPU");
    lcemfb.setPackagesToScan("com.project");
    lcemfb.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
    lcemfb.setJpaProperties(getHibernateProperties());
    return lcemfb;
  }

  @Bean
  public Properties getHibernateProperties() {
    Properties jpaProperties = new Properties();
    jpaProperties.put(DIALECT, "org.hibernate.dialect.Oracle10gDialect");
    jpaProperties.put(SHOW_SQL, true);
    jpaProperties.put(AUTOCOMMIT, true);
    jpaProperties.put(FORMAT_SQL, true);
    jpaProperties.put(USE_SQL_COMMENTS, true);
    jpaProperties.put(STATEMENT_BATCH_SIZE, 20);
    jpaProperties.put(ORDER_INSERTS, true);
    jpaProperties.put("hibernate.ejb.entitymanager_factory_name", "MyEM");
    return jpaProperties;
  }

  @Bean
  public JpaTransactionManager getTransactionManager() {
    return new JpaTransactionManager(getEntityManagerFactoryBean().getObject());
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor getPersistenceExceptionTranslationPostProcessor() {
    return new PersistenceExceptionTranslationPostProcessor();
  }
</code>```

I get entity manager like this

```<code>@PersistenceContext(unitName = "MyPU")
  private EntityManager em;

  protected EntityManager em() {
    return em;
  }
</code>```

my import method is:

```<code>  @Override
  @Transactional
  public void importBusinessFile(MultipartFile file)
      throws GeneralException, IOException {
    // process file

    //save batch
    dealsRepository.saveBatch(deals);
  }
</code>```

and saveBatch method from repository:

```<code>  public void saveBatch(List<Deal> list) {
    for (Deal deal : list) {
      em().persist(deal);
    }

    try {
      em().flush();
      em().clear();
    } catch (Exception e) {
      log.info("Duplicates detected, save individually.", e);

      for (Deal deal : list) {
        try {
          save(deal);
        } catch (Exception ex) {
          log.error("Problem saving individual deal", e);
          // TODO write to duplicates
        }
      }
    }
  }
</code>```

I tried setting dontRollbackOn but I can't get past this exception. I found some other similar threads but none helped me.

答: I only managed to fix this by creating another bean containing batch import method. So after that Spring can intercept the call from this bean and start a new transaction.</p>

Body:
I am using JPA with Spring. I am trying to do batch import. If there is problem with batch import then I would like to insert individually, and if this fails also then I would like to save to duplicates table. I wrote a logic for this but I get this error everytime:

Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly

Mine setting for JPA are like this:

@Bean(name = "dataSource", destroyMethod = "")
  public DataSource getDataSource() {
    return new JndiDataSourceLookup().getDataSource(props.getDbJndiName());
  }

  @Bean
  public JpaVendorAdapter getHibernateJpaVendorAdapter() {
    return new HibernateJpaVendorAdapter();
  }

  @Bean
  public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
    LocalContainerEntityManagerFactoryBean lcemfb = new LocalContainerEntityManagerFactoryBean();
    lcemfb.setDataSource(getDataSource());
    lcemfb.setPersistenceUnitName("MyPU");
    lcemfb.setPackagesToScan("com.project");
    lcemfb.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
    lcemfb.setJpaProperties(getHibernateProperties());
    return lcemfb;
  }

  @Bean
  public Properties getHibernateProperties() {
    Properties jpaProperties = new Properties();
    jpaProperties.put(DIALECT, "org.hibernate.dialect.Oracle10gDialect");
    jpaProperties.put(SHOW_SQL, true);
    jpaProperties.put(AUTOCOMMIT, true);
    jpaProperties.put(FORMAT_SQL, true);
    jpaProperties.put(USE_SQL_COMMENTS, true);
    jpaProperties.put(STATEMENT_BATCH_SIZE, 20);
    jpaProperties.put(ORDER_INSERTS, true);
    jpaProperties.put("hibernate.ejb.entitymanager_factory_name", "MyEM");
    return jpaProperties;
  }

  @Bean
  public JpaTransactionManager getTransactionManager() {
    return new JpaTransactionManager(getEntityManagerFactoryBean().getObject());
  }

  @Bean
  public PersistenceExceptionTranslationPostProcessor getPersistenceExceptionTranslationPostProcessor() {
    return new PersistenceExceptionTranslationPostProcessor();
  }

I get entity manager like this

@PersistenceContext(unitName = "MyPU")
  private EntityManager em;

  protected EntityManager em() {
    return em;
  }

my import method is:

  @Override
  @Transactional
  public void importBusinessFile(MultipartFile file)
      throws GeneralException, IOException {
    // process file

    //save batch
    dealsRepository.saveBatch(deals);
  }

and saveBatch method from repository:

  public void saveBatch(List<Deal> list) {
    for (Deal deal : list) {
      em().persist(deal);
    }

    try {
      em().flush();
      em().clear();
    } catch (Exception e) {
      log.info("Duplicates detected, save individually.", e);

      for (Deal deal : list) {
        try {
          save(deal);
        } catch (Exception ex) {
          log.error("Problem saving individual deal", e);
          // TODO write to duplicates
        }
      }
    }
  }

I tried setting dontRollbackOn but I can't get past this exception. I found some other similar threads but none helped me.