问:
How to parse float with two decimal places in javascript?
I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.</p>

```<code>price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
</code>```

答:
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

```<code>function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
</code>```

Body:
I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00.
Or if it equals 10.6 would be 10.60. Not sure how to do this.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));

Body:
If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}


来源: stackexchange

问:
Using the make command to compile class files
In my current computer science project, I've had to use a lot of classes and class files to help break up the enormous load of the program. However, I want to create a makefile that would be able to compile dependencies without using an intermediate ".o" step.
I already have:

```<code>%: %.cpp
    g++ -std=c++11 $< -o $@
</code>```

Yes, I do have to use c++11, not 14 or 17.
But is there a way to make it so that I can write make foo.cpp bar.cpp and have it run g++ -std=c++11 foo.cpp bar.cpp -o foo?

答:
In order to do what you want you'll have to list all of you *.cpp files as dependencies of foo, and do make foo (or have foo as the first target in your Makefile) to compile it.

```<code>foo: foo.cpp bar.cpp
    g++ -std=c++11 $^ -o $@
</code>```

$^ stands for all the prerequisites.

However, why don't you want to use and intermediate step ? Doing it this way, every time any of your source files change, you will recompile and relink your whole project. Using *.o allows to avoid that :

```<code>foo: foo.o bar.o
    g++ -std=c++11 $^ -o $@

%.o: %.cpp
    g++ -std=c++11 $< -o $@
</code>```

That way you'll avoid unnecessary recompilation.

(You can also omit the %.o rule, since make has built-in rules that are already defined by default)

ContentLicense: CC BY-SA 3.0

Body:
In my current computer science project, I've had to use a lot of classes and class files to help break up the enormous load of the program. However, I want to create a makefile that would be able to compile dependencies without using an intermediate ".o" step.
I already have:

%: %.cpp
    g++ -std=c++11 $< -o $@

Yes, I do have to use c++11, not 14 or 17.
But is there a way to make it so that I can write make foo.cpp bar.cpp and have it run g++ -std=c++11 foo.cpp bar.cpp -o foo?

Body:
In order to do what you want you'll have to list all of you *.cpp files as dependencies of foo, and do make foo (or have foo as the first target in your Makefile) to compile it.

foo: foo.cpp bar.cpp
    g++ -std=c++11 $^ -o $@

$^ stands for all the prerequisites.

However, why don't you want to use and intermediate step ? Doing it this way, every time any of your source files change, you will recompile and relink your whole project. Using *.o allows to avoid that :

foo: foo.o bar.o
    g++ -std=c++11 $^ -o $@

%.o: %.cpp
    g++ -std=c++11 $< -o $@

That way you'll avoid unnecessary recompilation.

(You can also omit the %.o rule, since make has built-in rules that are already defined by default)


问:
.load() with success function
I know this has been asked many times before...

I have a simple ('#Div').load(file.php?id='+id+'&page='+page)

The on click event acts as follows

```<code>function recp(id) {
  var user = $('#page').attr('page');
  $("#button").hide()
  $("#loading").html('<img src="images/loader.gif">');
  $('#div').load('file.php?id='+id+'&page='+page);
  $("#loading").empty();
  $("#button1").show()
}
</code>```

I have a similar process on my site with ajax post, works very nicely, but I can't seem to get this to work with .load().

Would need a bit of advice. Cheers.

答:
The problem is that load is asynchronous.  The function call returns before the AJAX request is complete.  If you have code that needs to be executed after the request is complete, you need to use the complete callback specified in the API:

```<code>$('#div').load('file.php?id='+id+'&page='+page, function(){
    $("#loading").empty();
    $("#button1").show();
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: .load() with success function

Body:
I know this has been asked many times before...

I have a simple ('#Div').load(file.php?id='+id+'&page='+page)

The on click event acts as follows

function recp(id) {
  var user = $('#page').attr('page');
  $("#button").hide()
  $("#loading").html('');
  $('#div').load('file.php?id='+id+'&page='+page);
  $("#loading").empty();
  $("#button1").show()
}

I have a similar process on my site with ajax post, works very nicely, but I can't seem to get this to work with .load().

Would need a bit of advice. Cheers.

Body:
The problem is that load is asynchronous.  The function call returns before the AJAX request is complete.  If you have code that needs to be executed after the request is complete, you need to use the complete callback specified in the API:

$('#div').load('file.php?id='+id+'&page='+page, function(){
    $("#loading").empty();
    $("#button1").show();
});


问:
Create folder failed when root is
Thanks for others help , i can create folder succeed now.

But i get a strange issue if android emulator doesn't has sdcard, i can't create the folder.

I can't figure it out..

Here is my code:

```<code>try {
            if (Environment.getExternalStorageState()
                    .equals(Environment.MEDIA_MOUNTED)) {
                System.out.println("can be read and write");
                File sdFile = android.os.Environment.getExternalStorageDirectory();
                //String path = sdFile.getPath() + File.separator + "DestPdf";
                String path = sdFile.getPath() + "/DestPdf";
                File dirFile = new File(path);

                if (!dirFile.exists()) {// if folder doesn't exist
                    System.out.println("create file");
                    dirFile.mkdirs();// create file
                    System.out.println(dirFile.toString());
                }
            }
        } catch (Exception ex) {
            ex.toString();
        }
</code>```

If my android emulator has sdcard root, i can create the folder DestPdf:

If there is no sdcard , i print the root is /storage/emulated/0/DestPdf, i create the folder failed, the folder emulated has nothing...

Any help would be appreciated .  Thanks in advance.

答:
you can use your app Internal Package folder for saving data,

```<code> context.getFilesDir().getPath()
</code>```

context is here Activity instance.Ok?

Do with it..

Title: Create folder failed when root is

Body:
Thanks for others help , i can create folder succeed now.

But i get a strange issue if android emulator doesn't has sdcard, i can't create the folder.

I can't figure it out..

Here is my code:

try {
            if (Environment.getExternalStorageState()
                    .equals(Environment.MEDIA_MOUNTED)) {
                System.out.println("can be read and write");
                File sdFile = android.os.Environment.getExternalStorageDirectory();
                //String path = sdFile.getPath() + File.separator + "DestPdf";
                String path = sdFile.getPath() + "/DestPdf";
                File dirFile = new File(path);

                if (!dirFile.exists()) {// if folder doesn't exist
                    System.out.println("create file");
                    dirFile.mkdirs();// create file
                    System.out.println(dirFile.toString());
                }
            }
        } catch (Exception ex) {
            ex.toString();
        }

If my android emulator has sdcard root, i can create the folder DestPdf:

If there is no sdcard , i print the root is /storage/emulated/0/DestPdf, i create the folder failed, the folder emulated has nothing...

Any help would be appreciated .  Thanks in advance.

Body:
you can use your app Internal Package folder for saving data,

 context.getFilesDir().getPath()

context is here Activity instance.Ok?

Do with it..


问:
MySQL table date update gives 00/00/0000 12:00:00 am format in table
I am updating datetime column in one table, but when update the column date save as 00/00/0000 12:00:00 am.

Here is Mysql query

update b_tasks set DEADLINE='28/12/2017 01:30:00 pm' where ID=4666 AND TITLE LIKE 'Perform demo%'.
And in PHP look like

```<code>$sql='update b_tasks set DEADLINE="'.$dtformat.'" where ID="'.$tid1.'"
AND TITLE LIKE "Perform demo%"';
</code>```

答:
```<code>$sql="update b_tasks set DEADLINE=STR_TO_DATE('".$dtformat."','%d/%m/%Y %h:%i:%s %p') where ID='".$tid1."'
AND TITLE LIKE 'Perform demo%'";
</code>```

Try above query.

You need to use STR_TO_DATE, which convert your given format string to date.

If you don't want to use this function you can go with default format 'yyyy-mm-dd HH:MM:SS'

This will help you.

Body:
I am updating datetime column in one table, but when update the column date save as 00/00/0000 12:00:00 am.

Here is Mysql query

update b_tasks set DEADLINE='28/12/2017 01:30:00 pm' where ID=4666 AND TITLE LIKE 'Perform demo%'.
And in PHP look like

$sql='update b_tasks set DEADLINE="'.$dtformat.'" where ID="'.$tid1.'"
AND TITLE LIKE "Perform demo%"';

Body:
$sql="update b_tasks set DEADLINE=STR_TO_DATE('".$dtformat."','%d/%m/%Y %h:%i:%s %p') where ID='".$tid1."'
AND TITLE LIKE 'Perform demo%'";

Try above query.

You need to use STR_TO_DATE, which convert your given format string to date.

If you don't want to use this function you can go with default format 'yyyy-mm-dd HH:MM:SS'

This will help you.


问:
database attached is read only
I used the following the script to attach a database. But the database created is read only.

What modifications should I make in the script to make it read-write. Please help me.

```<code>USE [master]
GO
CREATE DATABASE [GemDatabase] ON
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase.mdf' ),
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase_log.ldf' )
 FOR ATTACH
GO
if not exists (select name from master.sys.databases sd where name = N'GemDatabase' and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [GemDatabase].dbo.sp_changedbowner @loginame=N'sa', @map=false
GO
</code>```

答:
Another Way which worked for me is:

After dettaching before you attach

-> go to the .mdf file
-> right click & select properties on the file
-> security tab
-> Check Group or usernames:

for your name\account (optional)
 and for "NT SERVICE\MSSQLSERVER"(NB)

List item

-> if not there than click on edit button
   -> click on add button

```<code>  and enter\search NT SERVICE\MSSQLSERVER
</code>```

-> click on OK
-> give full rights
-> apply then ok

then ok again
do this for .ldf file too.

then attach

Title: database attached is read only

Body:
I used the following the script to attach a database. But the database created is read only.

What modifications should I make in the script to make it read-write. Please help me.

USE [master]
GO
CREATE DATABASE [GemDatabase] ON
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase.mdf' ),
( FILENAME = N'E:\Program Files (x86)\ICE Products\ICEConnect200\New Database\GemDatabase_log.ldf' )
 FOR ATTACH
GO
if not exists (select name from master.sys.databases sd where name = N'GemDatabase' and SUSER_SNAME(sd.owner_sid) = SUSER_SNAME() ) EXEC [GemDatabase].dbo.sp_changedbowner @loginame=N'sa', @map=false
GO

Body:
Another Way which worked for me is:

After dettaching before you attach

-> go to the .mdf file
-> right click & select properties on the file
-> security tab
-> Check Group or usernames:

for your name\account (optional)
 and for "NT SERVICE\MSSQLSERVER"(NB)

List item

-> if not there than click on edit button
   -> click on add button

  and enter\search NT SERVICE\MSSQLSERVER

-> click on OK
-> give full rights
-> apply then ok

then ok again
do this for .ldf file too.

then attach


问:
Is it possible to limit file references to a specific file storage?
The setup is the following:
I client of mine wants to give users the possibility to select a background image for a page. For the sake of simplicity let's say we create a new field in the pages table and configure its TCA separately, so we are completely side-effect free.

Now comes the tricky part. The storage, the users should select images from for that field, should be limited. So even if a backend user has admin rights and therefore access to all file storages and all files, users should only be able to select images from a given(configured) storage.

Is that somehow possible with a specific TCA configuration?

答:
I would first try to extend FileBrowser for this requirement. As you said nothing about visibility of the files, you could override fileIsSelectableInFileList in a subclass. So not exactly a pure TCA feature, but the implementation would allow a deeper integration of your ruleset.

class LocalStorageBrowser extends FileBrowser {
    // users should only be able to select files from a specific driver
    protected function fileIsSelectableInFileList(FileInterface $file, array $imgInfo)
    {
        return $file->getStorage()->getDriver() instanceof LocalDriver;
    }
    // ...
}
```


问:
TransactionScope causes TransactionManagerCommunicationException when used for DB unit tests
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

```<code>using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}
</code>```

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

```<code>public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}
</code>```

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.

答:
You could create your setup something like this:

```<code>void Main()
{
   using(new SetupTransaction())
   {
    //Your test
   }
}

public class SetupTransaction : IDisposable
{
    private TransactionScope transaction;

    public SetupTransaction()
    {
        transaction = new TransactionScope();
        //Do your stuff here
    }

    public void Dispose()
    {
        transaction.Dispose();
    }
}
</code>```

As for the error you're getting, could you post exactly how you're using your implementation?

Body:
I'd like to run some tests of stored procedures in my database without actually affecting the data (or, to put it more exactly, without a lasting impact after the test has run).

After some research I came up with the approach of using TransactionScope within my Visual Studio 2010 test project such as

using( new TransactionScope())
{
    using( SqlConnection connection = new SqlConnection("someConnectionString"))
    {
        connection.Open();
        using( SqlCommand command = new SqlCommand( "some sql", connection ))
        {
            // Do some database stuff...
        }
     }
}

Now this works fine as long as I put all of this within a single test method, i.e. all my changes to the database are automatically rolled back when the using block for TransactionScope is finished.

My problem is now that I'd like to do some database stuff in ClassInitialize so I only have to do it once per test class and not for every test method. When I create a public TransactionScope property and assign it an instance of TransactionScope in the ClassInitialize method, this works okay. As soon as I do any database related stuff in one of my test methods, I run into a TransactionManagerCommunicationException within that method.

I don't quite understand why that is the case, and I'd also like to know whether there is a mistake in my approach or how I can get it to work without having to set up the TransactionScope including all set up stuff for the tests within each test method again.

EDIT

Code excerpt below, I hope this gives enough information:

public TransactionScope Scope { get; set; }

[ClassInitialize]
public static void ClassInitialize( TestContext testContext )
{
    Scope = new TransactionScope();
    // Do some db set up stuff, e.g. create records used for tests etc.
}

[ClassCleanup]
public static void ClassCleanup()
{
    Scope.Dispose();
}

[TestMethod]
public void MyTestMethod()
{
    using( SqlConnection connection = new SqlConnection( "someConnectionString" ) )
    {
        DataTable result = new DataTable();
        using( SqlCommand command = new SqlCommand( "spName", connection ) )
        {
            command.CommandType = CommandType.StoredProcedure;
            using( SqlDataAdapter adapter = new SqlDataAdapter() )
            {
                adapter.SelecteCommand = command;
                // The next line causes the exception to be thrown
                adapter.Fill( result );
            }
        }

        // Assertions against DataTable result
    }
}

The exception is

TransactionManagerCommunicationException was unhandled by user code
Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.

I understand that I could try and change the settings, but I do not understand why I get the exception to begin with - what is different compared to having the code above in a single (test) method?

Thanks in advance and

best regards

G.

Body:
You could create your setup something like this:

void Main()
{
   using(new SetupTransaction())
   {
    //Your test
   }
}

public class SetupTransaction : IDisposable
{
    private TransactionScope transaction;

    public SetupTransaction()
    {
        transaction = new TransactionScope();
        //Do your stuff here
    }

    public void Dispose()
    {
        transaction.Dispose();
    }
}

As for the error you're getting, could you post exactly how you're using your implementation?


问:
Pattern Matching for CSV processing
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

```<code>def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}
</code>```

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?

答:
Try using an extractor like StringDouble below. If the unapply returns Some then it matches, if it returns None then it doesn't match.

```<code>object StringDouble {
  def unapply(str: String): Option[Double] = Try(str.toDouble).toOption
}

val doubles =
  Source.fromFile("my.csv").getLines().map { line =>
    line.split(",").map(_.trim)
  }.map {
    case Array(_, _, StringDouble(d)) => d
  }
</code>```

Title: Pattern Matching for CSV processing

Body:
I have a csv file with three columns and I want to get the third column into an Iterator. I want to filter out the headers by using the trytoDouble method in combination of the Pattern Matching.

def trytoDouble(s: String): Option[Double] = {
  try {
    Some(s.toDouble)
  } catch {
    case e: Exception => None
  }
}

val asdf = Source.fromFile("my.csv").getLines().map(_.split(",").map(_.trim).map(utils.trytoDouble(_))).map{
  _ match {
    case Array(a, b, Some(c: Double)) => c
  }
}

results in

An exception or error caused a run to abort: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)
  scala.MatchError: [Lscala.Option;@2b4a2ec7 (of class [Lscala.Option;)

what did I do wrong?

Body:
Try using an extractor like StringDouble below. If the unapply returns Some then it matches, if it returns None then it doesn't match.

object StringDouble {
  def unapply(str: String): Option[Double] = Try(str.toDouble).toOption
}

val doubles =
  Source.fromFile("my.csv").getLines().map { line =>
    line.split(",").map(_.trim)
  }.map {
    case Array(_, _, StringDouble(d)) => d
  }


问:
Iterate through many tables to get data (MySQL)
First of all I'm kinda new to MySql, so the solution to this may be very easy and I'm not seeing it.

This is the problem: I have to get all the prices related to a kind of event and I'm having troubles doing so.

Basically, I have to get from the table where I get the event type, to the one where I get its price.
That's the path to follow to get from the initial table to the one with the result:

I start like this, giving the event type

```<code>std_event.type = <my type of event goes here>
</code>```

from here I have to iterate from a table to another comparing the IDs, doing something like this:

```<code>std_event.id = std_concert.event_id
AND
std_concert.id = std_slot.concert_id
AND
std_slot.id = std_slot_deal.slot_id
AND
std_slot_deal.accepted = 1;
</code>```

At this point in the SELECT at the beginning I would have had

```<code>std_slot_deal.cachet
</code>```

so I would have got the cachet (which is the price I was talking about) at the end of all this.

Thanks for your help!

p.s. In case you need it, this is my query at the moment:

```<code>SELECT std_event.type, std_slot_deal.cachet
FROM std_event
INNER JOIN std_concert, std_slot, std_slot_deal
ON std_event.type = '.$evt_type.'
AND
std_event.id = std_concert.event_id
AND
std_concert.id = std_slot.concert_id
AND
std_slot.id = std_slot_deal.slot_id
AND
std_slot_deal.accepted = 1;
</code>```

(yes, I'm sending the quest through PHP, this '.$evt_type.' is the input event type)

EDIT
Here's the tables' structures I was asked for:

std_event: id(I use it to link to event_id in std_concert table), title, description, type(the input data I use), image, ...

std_concert: id(I use it to link to concert_id in std_slot table), date, place, street, city, ..., event_id

std_slot: id(I use it to link to slot_id in std_slot_deal table), concert_id, due_date, ...

std_slot_deal: id, club_id, artist_id, slot_id, ..., accepted, cachet(the result I need)

With this query I want to retrive all the cachet of the events with the given type basically.
I know the database is quite messy but I have to work on that, I don't even have a documentation or anything.

答:
Try this code, this may help you </p>

```<code>SELECT std_event.type, std_slot_deal.cachet
FROM std_event
INNER JOIN std_concert ON std_event.id = std_concert.event_id
INNER JOIN std_slot ON std_slot.concert_id = std_concert.id
INNER JOIN std_slot_deal ON std_slot.id = std_slot_deal.slot_id
WHERE std_event.type = '.$evt_type.'
AND
std_slot_deal.accepted = 1;
</code>```

Body:
First of all I'm kinda new to MySql, so the solution to this may be very easy and I'm not seeing it.

This is the problem: I have to get all the prices related to a kind of event and I'm having troubles doing so.

Basically, I have to get from the table where I get the event type, to the one where I get its price.
That's the path to follow to get from the initial table to the one with the result:

I start like this, giving the event type

std_event.type = <my type of event goes here>

from here I have to iterate from a table to another comparing the IDs, doing something like this:

std_event.id = std_concert.event_id
AND
std_concert.id = std_slot.concert_id
AND
std_slot.id = std_slot_deal.slot_id
AND
std_slot_deal.accepted = 1;

At this point in the SELECT at the beginning I would have had

std_slot_deal.cachet

so I would have got the cachet (which is the price I was talking about) at the end of all this.

Thanks for your help!

p.s. In case you need it, this is my query at the moment:

SELECT std_event.type, std_slot_deal.cachet
FROM std_event
INNER JOIN std_concert, std_slot, std_slot_deal
ON std_event.type = '.$evt_type.'
AND
std_event.id = std_concert.event_id
AND
std_concert.id = std_slot.concert_id
AND
std_slot.id = std_slot_deal.slot_id
AND
std_slot_deal.accepted = 1;

(yes, I'm sending the quest through PHP, this '.$evt_type.' is the input event type)

EDIT
Here's the tables' structures I was asked for:

std_event: id(I use it to link to event_id in std_concert table), title, description, type(the input data I use), image, ...

std_concert: id(I use it to link to concert_id in std_slot table), date, place, street, city, ..., event_id

std_slot: id(I use it to link to slot_id in std_slot_deal table), concert_id, due_date, ...

std_slot_deal: id, club_id, artist_id, slot_id, ..., accepted, cachet(the result I need)

With this query I want to retrive all the cachet of the events with the given type basically.
I know the database is quite messy but I have to work on that, I don't even have a documentation or anything.

Body:
Try this code, this may help you

SELECT std_event.type, std_slot_deal.cachet
FROM std_event
INNER JOIN std_concert ON std_event.id = std_concert.event_id
INNER JOIN std_slot ON std_slot.concert_id = std_concert.id
INNER JOIN std_slot_deal ON std_slot.id = std_slot_deal.slot_id
WHERE std_event.type = '.$evt_type.'
AND
std_slot_deal.accepted = 1;


问:
'extractIdentityAndTrust' error and warning while using code sample from certificate, key and trust programming guide
I am trying to use the code from the 'Certificate,Key and trust programming guide'. In the section about extracting and evaluating an identity from a p12 file, I am getting error and warning from using the code given in the guide.

The line

```<code>status = extractIdentityAndTrust(inPKCS12Data, &myIdentity, &myTrust);
</code>```

gives the warning: "Implicit declaration of function extractIdentityAndTrust "

while the function declaration of extractIdentityAndTrust"

```<code>OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data,SecIdentityRef *outIdentity,SecTrustRef *outTrust)
</code>```

gives me the error:conflicting types for extractIdentityAndTrust.

I am just trying to impement the code sample given in the guide. Please guide me where I am going wrong on this.

答: My mistake!! didn't declare the method in the header file.</p>

Body:
I am trying to use the code from the 'Certificate,Key and trust programming guide'. In the section about extracting and evaluating an identity from a p12 file, I am getting error and warning from using the code given in the guide.

The line

status = extractIdentityAndTrust(inPKCS12Data, &myIdentity, &myTrust);

gives the warning: "Implicit declaration of function extractIdentityAndTrust "

while the function declaration of extractIdentityAndTrust"

OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data,SecIdentityRef *outIdentity,SecTrustRef *outTrust)

gives me the error:conflicting types for extractIdentityAndTrust.

I am just trying to impement the code sample given in the guide. Please guide me where I am going wrong on this.


问:
Find time difference between highest and lowest value in data frame and sort by factor
I have a data frame and it looks like this:

```<code>submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...
</code>```

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

```<code>submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...
</code>```

I would like it in minutes as well.

答:
```<code>require(dplyr)
DF <- DF%>%group_by(submition_id)%>%summarise(difference = difftime(min(time_answered), max(time_answered), units = "min"))
</code>```

Body:
I have a data frame and it looks like this:

submition_id       time_answered
           2 2017-11-06 14:19:30
           2 2017-11-06 14:22:45
           2 2017-11-06 14:24:55
           2 2017-11-06 14:34:10
           4 2017-11-06 14:31:23
           4 2017-11-06 14:33:21
           5 2017-11-06 14:54:48
           5 2017-11-06 14:59:38
           5 2017-11-06 15:05:39
         ...                 ...

So basically my submition_id column is a factor column and time_answered column is POSIXct column. I want to find the time difference for each factor which is basically max(x) - min(x). How can I do this effective with inbuilt functions? Such that I get

submition_id       difference
           2            14.67
           4             1.96
           5             9.77
         ...              ...

I would like it in minutes as well.


问:
How can i calculate the sum of numbers written in a html table below specific headings - IONIC
Explanation: I have a html table with 2 columns namely Debit and Credit. Numers are written below them.

Requirement: I need to sum the number written below Debit and Credit

Please open about page in the repo.........
  Please find the stackblitz repo

On the about page you will find 2 buttons , 1. Total Debit   2. Total Credit

I want to calculate the total amount under debit and credit once that specific button is clicked.

Adding image for your reference below:

答:
inVoiceItems has each row in it. Create two methods, one for total debit and one for total credit.

```<code>public totalDebitValue = 0;
public totalCreditValue = 0;

totalDebit() {
    this.totalDebitValue = 0;
    this.inVoiceItems.forEach(e => {
        this.totalDebitValue += +e.prdDesc //+ is here to convert it to a number
    });
}

totalCredit() {
    this.totalCreditValue = 0;
    this.inVoiceItems.forEach(e => {
        this.totalCreditValue += +e.prdQty //+ is here to convert it to a number
    });
}
</code>```

This will fail if the user inputs a value that cannot be converted to a number.

Body:
inVoiceItems has each row in it. Create two methods, one for total debit and one for total credit.

public totalDebitValue = 0;
public totalCreditValue = 0;

totalDebit() {
    this.totalDebitValue = 0;
    this.inVoiceItems.forEach(e => {
        this.totalDebitValue += +e.prdDesc //+ is here to convert it to a number
    });
}

totalCredit() {
    this.totalCreditValue = 0;
    this.inVoiceItems.forEach(e => {
        this.totalCreditValue += +e.prdQty //+ is here to convert it to a number
    });
}

This will fail if the user inputs a value that cannot be converted to a number.


问:
performance problem
OK so I need to know if anyone can see a way to reduce the number of iterations of these loops because I can't. The first while loop is for going through a file, reading one line at a time. The first foreach loop is then comparing each of the compareSet with what was read in the first while loop. Then the next while loop is to do with bit counting.

As requested, an explaination of my algorithm:

There is a file that is too large to fit in memory. It contains a word followed by the pages in a very large document that this word is on. EG:

sky 1 7 9 32....... (it is not in this format, but you get the idea).

so parseLine reads in the line and converts it into a list of ints that are like a bit array where 1 means the word is on the page, and 0 means it isn't.

CompareSet is a bunch of other words. I can't fit my entire list of words into memory so I can only fit a subset of them. This is a bunch of words just like the "sky" example. I then compare each word in compareSet with Sky by seeing if they are on the same page.

So if sky and some other word both have 1 set at a certain index in the bit array (simulated as an int array for performance), they are on the same page. The algorithm therefore counts the occurances of any two words on a particular page. So in the end I will have a list like:

(for all words in list) is on the same page as (for all words in list) x number of times.

eg sky and land is on the same page x number of times.

```<code> while ((line = parseLine(s)) != null) {
     getPageList(line.Item2, compareWord);
     foreach (Tuple<int, uint[], List<Tuple<int, int>>> word in compareSet) {
         unchecked {
             for (int i = 0; i < 327395; i++) {
                 if (word.Item2[i] == 0 || compareWord[i] == 0)
                     continue;
                 uint combinedNumber = word.Item2[i] & compareWord[i];
                 while (combinedNumber != 0) {
                     actual++;
                     combinedNumber = combinedNumber & (combinedNumber - 1);
                 }
             }
         }
</code>```

答:
As Joal already mentioned nobody is able to optimize this looping algorithm. But what you can do is trying to better explain what you are trying to accomplish and what your hard requirements are. Maybe you can take a different approach by using some like HashSet<T>.IntersectWith() or BloomFilter or something like this.

So if you really want help from here you should not only post the code that doesn't work, but also what the overall task is you like to accomplish. Maybe someone has a completely other idea to solve your problem, making your whole algorithm obsolete.

Title: performance problem

Body:
OK so I need to know if anyone can see a way to reduce the number of iterations of these loops because I can't. The first while loop is for going through a file, reading one line at a time. The first foreach loop is then comparing each of the compareSet with what was read in the first while loop. Then the next while loop is to do with bit counting.

As requested, an explaination of my algorithm:

There is a file that is too large to fit in memory. It contains a word followed by the pages in a very large document that this word is on. EG:

sky 1 7 9 32....... (it is not in this format, but you get the idea).

so parseLine reads in the line and converts it into a list of ints that are like a bit array where 1 means the word is on the page, and 0 means it isn't.

CompareSet is a bunch of other words. I can't fit my entire list of words into memory so I can only fit a subset of them. This is a bunch of words just like the "sky" example. I then compare each word in compareSet with Sky by seeing if they are on the same page.

So if sky and some other word both have 1 set at a certain index in the bit array (simulated as an int array for performance), they are on the same page. The algorithm therefore counts the occurances of any two words on a particular page. So in the end I will have a list like:

(for all words in list) is on the same page as (for all words in list) x number of times.

eg sky and land is on the same page x number of times.

 while ((line = parseLine(s)) != null) {
     getPageList(line.Item2, compareWord);
     foreach (Tuple<int, uint[], List<Tuple<int, int>>> word in compareSet) {
         unchecked {
             for (int i = 0; i < 327395; i++) {
                 if (word.Item2[i] == 0 || compareWord[i] == 0)
                     continue;
                 uint combinedNumber = word.Item2[i] & compareWord[i];
                 while (combinedNumber != 0) {
                     actual++;
                     combinedNumber = combinedNumber & (combinedNumber - 1);
                 }
             }
         }


问:
Is there a way to add a configurable modal/lighbox/pop-up to a website?
Problem:

I manage a series of websites for clients that are all in the same industry. During certain times of the year (ie. Christmas, New Years, Summer, etc), we want to push certain promotions or specials on the sites. Right now when this happens, I have to go to each client's website (some wordpress, some straight html, some grav, some dnn...) and change some code to reflect the promotion.

Desired solution:

I would like to go into a tool/ui, configure some settings like the text, an image and a start/end date and have a pop up dialog be displayed on the website. For bonus points, I'd love to be able to build/schedule these ahead of time and just let them run. I use some tools like Drip that do something similar (displaying a modal) for sign up forms but haven't found anything that quite fits what I'm trying to do.

Ideas so far:

All of our sites have tag manager so I think there may be a way to do it using it. I would likely not be able to run things on a schedule or get an easy way to configure the modals but at least it would get me out of having to go to each site and do something different. I could copy/paste the html for the modal for each container, turn the tag on/off and update the markup when needed. Does that sound reasonable or a terrible idea? It feels like there should be something that does this already but I cant find anything.

Anyways, if someone has done something similar or if there are any tools/libraries I could buy I'd really appreciate the help!

Thanks!

答: This is perfectly possible by using the Custom HTML Tag..</p>


答:
having only one match case is always breaking code.

See the REPL example,

```<code>scala> def trytoDouble(s: String): Option[Double] = {
     |   try {
     |     Some(s.toDouble)
     |   } catch {
     |     case e: Exception => None
     |   }
     | }
</code>```

when there's no Double in your CSV,

```<code>scala> List("a,b,c").map(_.split(",").map(_.trim).map(trytoDouble(_)))
res1:  List[Array[Option[Double]]] = List(Array(None, None, None))
</code>```

When you match above result (Array(None, None, None)) with Array(a, b, Some(c: Double)) always going to fail,

```<code>scala> List("a,b,c").map(_.split(",").map(_.trim).map(trytoDouble(_))).map { data =>
     | data match {
     |     case Array(a, b, Some(c: Double)) => c
     | }
     | }
scala.MatchError: [Lscala.Option;@22604c7e (of class [Lscala.Option;)
  at .$anonfun$res4$4(<console>:15)
  at .$anonfun$res4$4$adapted(<console>:13)
  at scala.collection.immutable.List.map(List.scala:283)
  ... 33 elided
</code>```

And when there Double,

```<code>scala> List("a,b,100").map(_.split(",").map(_.trim).map(trytoDouble(_))).map { data => data match { case Array(a, b, Some(c: Double)) => c }}
res5: List[Double] = List(100.0)
</code>```

You basically need to check for Some(c) or None.

BUT, if I understand you you are to extract third field as Double which can be done this way,

```<code>scala> List("a,b,100", "100, 200, p").map(_.split(",")).map { case Array(a, b, c) => trytoDouble(c)}.filter(_.nonEmpty)
res14: List[Option[Double]] = List(Some(100.0))
</code>```

Title: Pattern Matching for CSV processing

Body:
having only one match case is always breaking code.

See the REPL example,

scala> def trytoDouble(s: String): Option[Double] = {
     |   try {
     |     Some(s.toDouble)
     |   } catch {
     |     case e: Exception => None
     |   }
     | }

when there's no Double in your CSV,

scala> List("a,b,c").map(_.split(",").map(_.trim).map(trytoDouble(_)))
res1:  List[Array[Option[Double]]] = List(Array(None, None, None))

When you match above result (Array(None, None, None)) with Array(a, b, Some(c: Double)) always going to fail,

scala> List("a,b,c").map(_.split(",").map(_.trim).map(trytoDouble(_))).map { data =>
     | data match {
     |     case Array(a, b, Some(c: Double)) => c
     | }
     | }
scala.MatchError: [Lscala.Option;@22604c7e (of class [Lscala.Option;)
  at .$anonfun$res4$4(<console>:15)
  at .$anonfun$res4$4$adapted(<console>:13)
  at scala.collection.immutable.List.map(List.scala:283)
  ... 33 elided

And when there Double,

scala> List("a,b,100").map(_.split(",").map(_.trim).map(trytoDouble(_))).map { data => data match { case Array(a, b, Some(c: Double)) => c }}
res5: List[Double] = List(100.0)

You basically need to check for Some(c) or None.

BUT, if I understand you you are to extract third field as Double which can be done this way,

scala> List("a,b,100", "100, 200, p").map(_.split(",")).map { case Array(a, b, c) => trytoDouble(c)}.filter(_.nonEmpty)
res14: List[Option[Double]] = List(Some(100.0))


问:
Declaration and use of function in c
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

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

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}
</code>```

答:
Declaration:

```<code>int day_of_year(int day, int month, int year);
</code>```

Call:

```<code>count=day_of_year();
</code>```

Definition:

```<code>int day_of_year (int day, int month, int year, int i, int count){
</code>```

C is a strongly typed language meaning the number and the type of functions arguments much match.

So, you need correct the argument list and add the missing parameters to the function call.

It looks like you don't really need the last two arguments in the definition - declare them as local variables instead:

```<code>int day_of_year (int day, int month, int year){
    int i, count;
</code>```

Title: Declaration and use of function in c

Body:
I can't find errors in this code. I'm trying to write a program that returns the number of days (ex: 60) in the year based on day, month and year [ex: 1/3/2000 (3 Mar 2000)].

The compiler give me these errors:

too few arguments to function 'day_of_year'

conflicting types for 'day_of_year'

#include <stdio.h>

int day_of_year(int day, int month, int year);

int main(){
    int day, month, year, i, count=0;
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    printf ("Enter the day: ");
    scanf ("%d", &day);
    printf ("Enter the month: ");
    scanf ("%d", &month);
    printf ("Enter the year: ");
    scanf ("%d", &year);
    count=day_of_year();
    printf ("Count: %d", count);
    return 0;
}

int day_of_year (int day, int month, int year, int i, int count){
    int a[]={31,28,31,30,31,30,31,31,30,31,30,31};
    if (year%4==0) a[2]++;
    count = day;
    for (i=0;i<month;i++)
        count+=a[i];
    return count;
}

Body:
Declaration:

int day_of_year(int day, int month, int year);

Call:

count=day_of_year();

Definition:

int day_of_year (int day, int month, int year, int i, int count){

C is a strongly typed language meaning the number and the type of functions arguments much match.

So, you need correct the argument list and add the missing parameters to the function call.

It looks like you don't really need the last two arguments in the definition - declare them as local variables instead:

int day_of_year (int day, int month, int year){
    int i, count;


问:
Django (DRF): How to do case-insensitive ordering
I have an api with ?ordering=name,type

I want both the name and the type to be as case-insensitive

```<code>class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [OrderingFilter]
</code>```

答:
got the solution from https://github.com/encode/django-rest-framework/issues/3280

```<code>from django.db.models.functions import Lower
from rest_framework.filters import OrderingFilter

class CaseInsensitiveOrderingFilter(OrderingFilter):

    def filter_queryset(self, request, queryset, view):
        ordering = self.get_ordering(request, queryset, view)

        if ordering:
            new_ordering = []
            for field in ordering:
                if field.startswith('-'):
                    new_ordering.append(Lower(field[1:]).desc())
                else:
                    new_ordering.append(Lower(field).asc())
            return queryset.order_by(*new_ordering)

        return queryset
</code>```

then use it in the ListView

```<code>class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [SearchFilter,CaseInsensitiveOrderingFilter]
    search_fields = ['name','slug']
</code>```

Body:
I have an api with ?ordering=name,type

I want both the name and the type to be as case-insensitive

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [OrderingFilter]

Body:
got the solution from https://github.com/encode/django-rest-framework/issues/3280

from django.db.models.functions import Lower
from rest_framework.filters import OrderingFilter

class CaseInsensitiveOrderingFilter(OrderingFilter):

    def filter_queryset(self, request, queryset, view):
        ordering = self.get_ordering(request, queryset, view)

        if ordering:
            new_ordering = []
            for field in ordering:
                if field.startswith('-'):
                    new_ordering.append(Lower(field[1:]).desc())
                else:
                    new_ordering.append(Lower(field).asc())
            return queryset.order_by(*new_ordering)

        return queryset

then use it in the ListView

class IngredientListAPIView(ListAPIView):
    queryset = Ingredient.objects.all()
    serializer_class = IngredientListSerializer
    filter_backends = [SearchFilter,CaseInsensitiveOrderingFilter]
    search_fields = ['name','slug']


答:
It will always give scala.MatchError

```<code>scala> val url = "/home/knoldus/data/moviedataset.csv"
url: String = /home/knoldus/data/moviedataset.csv

scala> val asdf1 = Source.fromFile(url).getLines().map(_.split(",").map(_.trim).map(trytoDouble(_))).toList
asdf1: List[Array[Option[Double]]] = List(Array(Some(1.0), None, Some(1993.0), Some(3.9), Some(4568.0)), Array(Some(2.0), None, Some(1932.0), Some(3.5), Some(4388.0)), Array(Some(3.0), None, Some(1921.0), Some(3.2), Some(9062.0)), Array(Some(4.0), None, Some(1991.0), Some(2.8), Some(6150.0)), Array(Some(5.0), None, Some(1963.0), Some(2.8), Some(5126.0)), ....
</code>```

As it will return non-empty iterator so, to see the result i have converted it toList.
If you notice return type is List[Array[Option[Double]]], and you are trying to match with Array of tuple3 but it always returns Array[Option[Double]].
Therefore, it will always throw error.

Title: Pattern Matching for CSV processing

Body:
It will always give scala.MatchError

scala> val url = "/home/knoldus/data/moviedataset.csv"
url: String = /home/knoldus/data/moviedataset.csv

scala> val asdf1 = Source.fromFile(url).getLines().map(_.split(",").map(_.trim).map(trytoDouble(_))).toList
asdf1: List[Array[Option[Double]]] = List(Array(Some(1.0), None, Some(1993.0), Some(3.9), Some(4568.0)), Array(Some(2.0), None, Some(1932.0), Some(3.5), Some(4388.0)), Array(Some(3.0), None, Some(1921.0), Some(3.2), Some(9062.0)), Array(Some(4.0), None, Some(1991.0), Some(2.8), Some(6150.0)), Array(Some(5.0), None, Some(1963.0), Some(2.8), Some(5126.0)), ....

As it will return non-empty iterator so, to see the result i have converted it toList.
If you notice return type is List[Array[Option[Double]]], and you are trying to match with Array of tuple3 but it always returns Array[Option[Double]].
Therefore, it will always throw error.


问:
How to use angular.bind(self, fn, args)
I am new to angular js. I was gone through the angular api references,
I had seen function called angular.bind(self, fn, args).
I could not understand the usage of this function. Can anyone explain this function with one example?</p>

答:
Controller

```<code> app.controller('Identity`enter code here`Controller', ['$scope',
   function($scope) {
   $scope.Name = "";
   $scope.Result = "";
  var greet = function (greeting, punctuation) {
    $scope.Result = greeting + ' ' + $scope.Name +''+ punctuation;
  };
   $scope.callBind = function () {
    var bound = angular.bind(this, greet, 'Welcome');
     bound('!!!!!');
  };
 }]);
</code>```

html

```<code> <fieldset style="background-color:#DDE4E9;">
    <legend>AngulerJS $scope.bind() Example</legend>
        <div ng-controller="IdentityController">
          <p>{{Result}}</p>
          <input ng-model="Name">
          <button ng-click="callBind()">Call Bind</button>
        </div>
 </fieldset>
</code>```

I Think Its Working

Title: How to use angular.bind(self, fn, args)

Body:
Controller

 app.controller('Identity`enter code here`Controller', ['$scope',
   function($scope) {
   $scope.Name = "";
   $scope.Result = "";
  var greet = function (greeting, punctuation) {
    $scope.Result = greeting + ' ' + $scope.Name +''+ punctuation;
  };
   $scope.callBind = function () {
    var bound = angular.bind(this, greet, 'Welcome');
     bound('!!!!!');
  };
 }]);

html

 <fieldset style="background-color:#DDE4E9;">
    <legend>AngulerJS $scope.bind() Example</legend>
        <div ng-controller="IdentityController">
          <p>{{Result}}</p>
          <input ng-model="Name">
          <button ng-click="callBind()">Call Bind</button>
        </div>
 </fieldset>

I Think Its Working


问:
D3 How to keep element same size while transform scale / translate
This example illustrates my problem: https://bl.ocks.org/feketegy/ce9ab2efa9439f3c59c381f567522dd3

I have a couple of paths in a group element and I want to pan/zoom these elements except the blue rectangle path, which is in another group element.

The zooming and panning is done by applying transform="translate(0,0) scale(1) to the outer most group element then capturing the zoom delta and applying it to the same-size group element to keep it the same size.

This is working, but the blue rectangle position, which should remain the same size, is messed up, I would like to keep it in the same relative position to the other paths.

The rendered html structure looks like this:

```<code><svg width="100%" height="100%">
  <g class="outer-group" transform="translate(0,0)scale(1)">
    <path d="M100,100 L140,140 L200,250 L100,250 Z" fill="#cccccc" stroke="#8191A2" stroke-width="2px"></path>
    <path d="M400,100 L450,100 L450,250 L400,250 Z" fill="#cccccc" stroke="#8191A2" stroke-width="2px"></path>

    <g class="same-size-position" transform="translate(300,250)">
      <g class="same-size" transform="scale(1)">
        <path d="M0,0 L50,0 L50,50 L0,50 Z" fill="#0000ff"></path>
      </g>
    </g>
  </g>
</svg>
</code>```

I've tried to get the X/Y position of the same-size-position group and create a delta from the translate x/y of the outer-group, but that doesn't seem to work.

答:
After dusting off my high school geometry books I found a solution.

You need to get the bounding box of the element you want to keep the same size of and calculate a matrix conversion on it like so:

```<code>const zoomDelta = 1 / d3.event.transform.k;

const sameSizeElem = d3.select('.same-size');
const bbox = sameSizeElem.node().getBBox();

const cx = bbox.x + (bbox.width / 2);
const cy = bbox.y + (bbox.height / 2);
const zx = cx - zoomDelta * cx;
const zy = cy - zoomDelta * cy;

sameSizeElem
  .attr('transform', 'matrix(' + zoomDelta + ', 0, 0, ' + zoomDelta + ', ' + zx + ', ' + zy + ')');
</code>```

The matrix transformation will keep the relative position of the element which size remains the same and the other elements will pan/zoom.

Body:
This example illustrates my problem: https://bl.ocks.org/feketegy/ce9ab2efa9439f3c59c381f567522dd3

I have a couple of paths in a group element and I want to pan/zoom these elements except the blue rectangle path, which is in another group element.

The zooming and panning is done by applying transform="translate(0,0) scale(1) to the outer most group element then capturing the zoom delta and applying it to the same-size group element to keep it the same size.

This is working, but the blue rectangle position, which should remain the same size, is messed up, I would like to keep it in the same relative position to the other paths.

The rendered html structure looks like this:

<svg width="100%" height="100%">
  <g class="outer-group" transform="translate(0,0)scale(1)">
    <path d="M100,100 L140,140 L200,250 L100,250 Z" fill="#cccccc" stroke="#8191A2" stroke-width="2px"></path>
    <path d="M400,100 L450,100 L450,250 L400,250 Z" fill="#cccccc" stroke="#8191A2" stroke-width="2px"></path>

    <g class="same-size-position" transform="translate(300,250)">
      <g class="same-size" transform="scale(1)">
        <path d="M0,0 L50,0 L50,50 L0,50 Z" fill="#0000ff"></path>
      </g>
    </g>
  </g>
</svg>

I've tried to get the X/Y position of the same-size-position group and create a delta from the translate x/y of the outer-group, but that doesn't seem to work.

Body:
After dusting off my high school geometry books I found a solution.

You need to get the bounding box of the element you want to keep the same size of and calculate a matrix conversion on it like so:

const zoomDelta = 1 / d3.event.transform.k;

const sameSizeElem = d3.select('.same-size');
const bbox = sameSizeElem.node().getBBox();

const cx = bbox.x + (bbox.width / 2);
const cy = bbox.y + (bbox.height / 2);
const zx = cx - zoomDelta * cx;
const zy = cy - zoomDelta * cy;

sameSizeElem
  .attr('transform', 'matrix(' + zoomDelta + ', 0, 0, ' + zoomDelta + ', ' + zx + ', ' + zy + ')');

The matrix transformation will keep the relative position of the element which size remains the same and the other elements will pan/zoom.


问:
How to pass variable with sys_date in oracle
I want to pass sysdate into V_TODAY variable which i can use it for other anounymous block or during spooling. I am writing below code which is giving an error has V_TODAY must be declare. For variable with value NAME and ID i am able to pass the value.</p>

```<code>SET ECHO OFF;
SET FEEDBACK OFF;
SET HEAD OFF;
SET LIN 256;
SET TRIMSPOOL ON;
SET WRAP OFF;
SET PAGES 100;
SET TERM OFF;
SET SERVEROUTPUT ON;

SPOOL F:\LATEST\Loop_TRE.sql;

PROMPT VAR NAME VARCHAR2(100);
PROMPT VAR ID VARCHAR2(100);
PROMPT VAR V_TODAY date;

BEGIN
FOR TARGET_POINTER IN (SELECT NAME, ID from D_URL)
    LOOP
    DBMS_OUTPUT.PUT_LINE('DEFINE TARGET = '''||TARGET_POINTER.NAME||''';');
    DBMS_OUTPUT.PUT_LINE('EXEC :NAME  := '''||TARGET_POINTER.NAME||'''; ');
    DBMS_OUTPUT.PUT_LINE('DEFINE TARGET1 = '''||TARGET_POINTER.ID||''';');
    DBMS_OUTPUT.PUT_LINE('EXEC :ID  := '''||TARGET_POINTER.ID||'''; ');
    DBMS_OUTPUT.PUT_LINE('@@TGT_DOP.sql;');
  END LOOP;
  Select SYS_DATE INTO V_TODAY from DUAL;
  DBMS_OUTPUT.PUT_LINE('DEFINE V_TODAY = '''||V_TODAY||''';');
  DBMS_OUTPUT.PUT_LINE('EXEC :V_TODAY  := '''||V_TODAY||'''; ');
  DBMS_OUTPUT.PUT_LINE('@@Loop_TST.sql;');
END;
/

SPOOL OFF;

@@Loop_TRE.sql;
</code>```

答:
Declare V_TODAY in Declare block and use SYSDATE instead of SYS_DATE

in Reference with your code:

```<code>SET ECHO OFF;

.
.
PROMPT VAR NAME VARCHAR2(100);
PROMPT VAR ID VARCHAR2(100);

DECLARE
V_TODAY DATE;
BEGIN
....
...
END LOOP;
Select SYSDATE INTO V_TODAY from DUAL;

...
...
</code>```

Body:
I want to pass sysdate into V_TODAY variable which i can use it for other anounymous block or during spooling. I am writing below code which is giving an error has V_TODAY must be declare. For variable with value NAME and ID i am able to pass the value.

SET ECHO OFF;
SET FEEDBACK OFF;
SET HEAD OFF;
SET LIN 256;
SET TRIMSPOOL ON;
SET WRAP OFF;
SET PAGES 100;
SET TERM OFF;
SET SERVEROUTPUT ON;

SPOOL F:\LATEST\Loop_TRE.sql;

PROMPT VAR NAME VARCHAR2(100);
PROMPT VAR ID VARCHAR2(100);
PROMPT VAR V_TODAY date;

BEGIN
FOR TARGET_POINTER IN (SELECT NAME, ID from D_URL)
    LOOP
    DBMS_OUTPUT.PUT_LINE('DEFINE TARGET = '''||TARGET_POINTER.NAME||''';');
    DBMS_OUTPUT.PUT_LINE('EXEC :NAME  := '''||TARGET_POINTER.NAME||'''; ');
    DBMS_OUTPUT.PUT_LINE('DEFINE TARGET1 = '''||TARGET_POINTER.ID||''';');
    DBMS_OUTPUT.PUT_LINE('EXEC :ID  := '''||TARGET_POINTER.ID||'''; ');
    DBMS_OUTPUT.PUT_LINE('@@TGT_DOP.sql;');
  END LOOP;
  Select SYS_DATE INTO V_TODAY from DUAL;
  DBMS_OUTPUT.PUT_LINE('DEFINE V_TODAY = '''||V_TODAY||''';');
  DBMS_OUTPUT.PUT_LINE('EXEC :V_TODAY  := '''||V_TODAY||'''; ');
  DBMS_OUTPUT.PUT_LINE('@@Loop_TST.sql;');
END;
/

SPOOL OFF;

@@Loop_TRE.sql;

Body:
Declare V_TODAY in Declare block and use SYSDATE instead of SYS_DATE

in Reference with your code:

SET ECHO OFF;

.
.
PROMPT VAR NAME VARCHAR2(100);
PROMPT VAR ID VARCHAR2(100);

DECLARE
V_TODAY DATE;
BEGIN
....
...
END LOOP;
Select SYSDATE INTO V_TODAY from DUAL;

...
...


问:
How to obtain the indicated order along the x axis in python matplotlib
I want to draw points in the desired sequence along the x axis - '2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4 ',' 2017-11-01-5', for example. But the plot function changes the order to alphabetical - '2017-11-01-1', '2017-11-01-2', '2017-11-01-3', '2017-11-01-4 ',' 2017-11-01-5'.

Is it possible to draw points along the x axis in the sequence I need?

```<code>import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
x = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5'] # the order I need
y = ['1879994', '1879995', '1891647', '1889925', '1879900']

xax = ax.get_xaxis()

plt.title('Title')
plt.ylabel('PPS')
plt.xlabel('Date-Commit')
xlabels = xax.get_ticklabels()

for label in xlabels:
    label.set_rotation(45)

ax.plot(x, y, '-bo')
plt.savefig('chart.png', fmt='png')
plt.show()
</code>```

received chart

答:
Try having a dummy x-axis and using the dates that you require as just xticklabels</p>

```<code>import matplotlib.pyplot as plt

y = [1879994, 1879995, 1891647, 1889925, 1879900]
x = range(len(y))
ticklabels = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5']
plt.xticks(x, ticklabels)
plt.plot(x, y)
plt.show()
</code>```

Body:
I want to draw points in the desired sequence along the x axis - '2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4 ',' 2017-11-01-5', for example. But the plot function changes the order to alphabetical - '2017-11-01-1', '2017-11-01-2', '2017-11-01-3', '2017-11-01-4 ',' 2017-11-01-5'.

Is it possible to draw points along the x axis in the sequence I need?

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
x = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5'] # the order I need
y = ['1879994', '1879995', '1891647', '1889925', '1879900']

xax = ax.get_xaxis()

plt.title('Title')
plt.ylabel('PPS')
plt.xlabel('Date-Commit')
xlabels = xax.get_ticklabels()

for label in xlabels:
    label.set_rotation(45)

ax.plot(x, y, '-bo')
plt.savefig('chart.png', fmt='png')
plt.show()

received chart

Body:
Try having a dummy x-axis and using the dates that you require as just xticklabels

import matplotlib.pyplot as plt

y = [1879994, 1879995, 1891647, 1889925, 1879900]
x = range(len(y))
ticklabels = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5']
plt.xticks(x, ticklabels)
plt.plot(x, y)
plt.show()


问:
Enable press effect on RecyclerView's item in android
I have RecyclerView with list of data:

```<code><android.support.v7.widget.RecyclerView
        android:id="@+id/categoriesList"
        android:layout_width="368dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clickable="true"
        android:focusable="true"
        android:foreground="?android:attr/selectableItemBackground"
        android:background="?android:selectableItemBackground"/>
</code>```

When I tap to any items in this list, I wait pressing effect. I do not have a click handler, but in the standard ListView, any click on an element is visible. And I look like there's nothing to react

I need next:

答:
You need to add these lines to your single row layout instead of recyclerview tag.</p>

```<code>android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
android:background="?android:selectableItemBackground"
</code>```

Body:
I have RecyclerView with list of data:

<android.support.v7.widget.RecyclerView
        android:id="@+id/categoriesList"
        android:layout_width="368dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clickable="true"
        android:focusable="true"
        android:foreground="?android:attr/selectableItemBackground"
        android:background="?android:selectableItemBackground"/>

When I tap to any items in this list, I wait pressing effect. I do not have a click handler, but in the standard ListView, any click on an element is visible. And I look like there's nothing to react

I need next:

Body:
You need to add these lines to your single row layout instead of recyclerview tag.

android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
android:background="?android:selectableItemBackground"


问:
Msg 4104, Level 16, State 1, Procedure cst_priceimporter, Line 37
I have written the following code and getting the below error, I believe its to do with how I am joining to the country table but can't work out how to fix. Can anyone point me in the right direction please</p>

```<code>Msg 4104, Level 16, State 1, Procedure cst_priceimporter, Line 37
The multi-part identifier "country.price" could not be bound.
</code>```

<p> </p>

```<code>create procedure cst_priceimporter as

declare @todayDt datetime
declare @dtfirst int
declare @dtweek int
declare @iswkday bit

select @todayDt = convert(varchar,getdate(),101)

set @dtfirst = @@datefirst - 1
set @dtweek = datepart(weekday, @todayDt) -1

if (@dtfirst + @dtweek) % 7 = 0
    begin

        set @todaydt = @todaydt- 2

        update  SecPriceHist
        set     fxrate = 1 / fxrate
        from    SecPriceHist sph
        join    sec s
        on      sph.id = s.id
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

        update  country
        set     country.price = 1 / country.price
        from    country c
        join    sec s
        on      s.country = c.country
        and     s.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     s.id <> 'SEK'
        join    secpricehist sph
        on      sph.id = s.id
        and     s.country = c.country
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

    end
else
        set @todaydt = @todaydt- 1

        update  SecPriceHist
        set     fxrate = 1 / fxrate
        from    SecPriceHist sph
        join    sec s
        on      sph.id = s.id
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

        update  country
        set     country.price = 1 / country.price
        from    country c
        join    sec s
        on      s.country = c.country
        and     s.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     s.id <> 'SEK'
        join    secpricehist sph
        on      sph.id = s.id
        and     s.country = c.country
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'
</code>```

答:
The SET part of update should NOT have any table name, you can only update one anyway.
Also since you have aliased Country as C, you need to use the alias

```<code>update  country
set     price = 1 / c.price
</code>```

I think it occurs twice

Body:
I have written the following code and getting the below error, I believe its to do with how I am joining to the country table but can't work out how to fix. Can anyone point me in the right direction please

Msg 4104, Level 16, State 1, Procedure cst_priceimporter, Line 37
The multi-part identifier "country.price" could not be bound.

create procedure cst_priceimporter as

declare @todayDt datetime
declare @dtfirst int
declare @dtweek int
declare @iswkday bit

select @todayDt = convert(varchar,getdate(),101)

set @dtfirst = @@datefirst - 1
set @dtweek = datepart(weekday, @todayDt) -1

if (@dtfirst + @dtweek) % 7 = 0
    begin

        set @todaydt = @todaydt- 2

        update  SecPriceHist
        set     fxrate = 1 / fxrate
        from    SecPriceHist sph
        join    sec s
        on      sph.id = s.id
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

        update  country
        set     country.price = 1 / country.price
        from    country c
        join    sec s
        on      s.country = c.country
        and     s.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     s.id <> 'SEK'
        join    secpricehist sph
        on      sph.id = s.id
        and     s.country = c.country
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

    end
else
        set @todaydt = @todaydt- 1

        update  SecPriceHist
        set     fxrate = 1 / fxrate
        from    SecPriceHist sph
        join    sec s
        on      sph.id = s.id
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

        update  country
        set     country.price = 1 / country.price
        from    country c
        join    sec s
        on      s.country = c.country
        and     s.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     s.id <> 'SEK'
        join    secpricehist sph
        on      sph.id = s.id
        and     s.country = c.country
        and     sph.priceSource = 'DFLT'
        and     sph.hdate = @todayDt
        and     sph.dateStamp between DATEADD(mi,-1,getdate()) and getdate()
        and     s.sectype <2 and s.country not in ('SupraNational','ZMultiCountry')
        and     sph.id <> 'SEK'

Body:
The SET part of update should NOT have any table name, you can only update one anyway.
Also since you have aliased Country as C, you need to use the alias

update  country
set     price = 1 / c.price

I think it occurs twice


问:
How to show json inside another array in bootstrap table
I have to the below JSON data in a bootstrap table. I can show the one level data, but I don't know how to show array inside array data in bootstrap table.

```<code>[
    {
        "seriesName": "Indian Bank",
        "dataVlaues": {
            "11/12/2017": 50,
            "11/13/2017": 40,
            "11/14/2017": 60,
            "11/11/2017": 100
        }
    },
    {
        "seriesName": "Indian Bank1",
        "dataVlaues": {
            "11/18/2017": 12,
            "11/17/2017": 27,
            "11/16/2017": 30,
            "11/15/2017": 101
        }
    }
]
</code>```

答:
Please check this jsfiddle link

https://jsfiddle.net/lalitSachdeva1/0xb732e1/1/

I have updated the ul li to table like structure;
your js will remain same and the key concept here is ng-repeat-start and ng-repeat-end

```<code><div ng-app="myApp">
    <div ng-controller="myCtrl">
      <table>
    <thead>
        <tr>
            <td>parent</td>
            <td>option1</td>
            <td>option2</td>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="user in userTypes">
            <td>{{user.type}}</td>
            <td ng-repeat-start="(key,value) in user.options">{{key}}</td>
            <td ng-repeat-end="(key,value) in user.options">{{value}}</td>
        </tr>
    </tbody>
</table>
    </div>
</div>
</code>```

Body:
I have to the below JSON data in a bootstrap table. I can show the one level data, but I don't know how to show array inside array data in bootstrap table.

[
    {
        "seriesName": "Indian Bank",
        "dataVlaues": {
            "11/12/2017": 50,
            "11/13/2017": 40,
            "11/14/2017": 60,
            "11/11/2017": 100
        }
    },
    {
        "seriesName": "Indian Bank1",
        "dataVlaues": {
            "11/18/2017": 12,
            "11/17/2017": 27,
            "11/16/2017": 30,
            "11/15/2017": 101
        }
    }
]

Body:
Please check this jsfiddle link

https://jsfiddle.net/lalitSachdeva1/0xb732e1/1/

I have updated the ul li to table like structure;
your js will remain same and the key concept here is ng-repeat-start and ng-repeat-end

<div ng-app="myApp">
    <div ng-controller="myCtrl">
      <table>
    <thead>
        <tr>
            <td>parent</td>
            <td>option1</td>
            <td>option2</td>
        </tr>
    </thead>
    <tbody>
        <tr data-ng-repeat="user in userTypes">
            <td>{{user.type}}</td>
            <td ng-repeat-start="(key,value) in user.options">{{key}}</td>
            <td ng-repeat-end="(key,value) in user.options">{{value}}</td>
        </tr>
    </tbody>
</table>
    </div>
</div>


问:
Is there a way to monitor kube cron jobs using prometheus
Is there a way to monitor kube cronjob?

I have a kube cronjob which runs every 10mins on my cluster. Is there a way to collect metrics every time my cronjob fails due to some error  or notify when my cronjob has not been completed after a certain period of time?

答: The way to monitoring cronjobs with Prometheus is to have them push a metric indicating the last time they succeeded to the pushgateway. You can then alert on if the cronjob hasn't succeeded recently enough.</p>

ContentLicense: CC BY-SA 4.0


问:
Get index of the delegate currently displayed - QML ListView
I created a ListView, which displays a couple of pages of content defined by the user (plain text). The page displayed is a delegate. Only one page is visible at a time. I decided to use it to get snapping to one item, in the same way the iOS' launcher works. The user simply flicks between the pages. (this is to be used on touch screens)

I need to have the index of the currently displayed page for some operation. currentIndex of the ListView always stays == 0. How can I get it?

For those who prefer code:

```<code> ListView
 {
      onCurrentIndexChanged: console.log(currentIndex) // this gets called only once - at startup
      delegate: Column
      {
           // The page displayed, only one page at a time
      }
 }
</code>```

Thanks

答:
I know this is quite old but I had the same problem and spend some time trying to find a way to get currentIndex that would work for me. In my case sometimes I need to change the width of my ListView so I have to recalculte currentIndex manualy every time I resize it.

But I found a highlightRangeMode property. When it's set to ListView.StrictlyEnforceRange then currentIndex is always updated automaticly and contains correct index of the currently visible item.

```<code>ListView {
    highlightRangeMode: ListView.StrictlyEnforceRange
    // ...
}
</code>```

Body:
I created a ListView, which displays a couple of pages of content defined by the user (plain text). The page displayed is a delegate. Only one page is visible at a time. I decided to use it to get snapping to one item, in the same way the iOS' launcher works. The user simply flicks between the pages. (this is to be used on touch screens)

I need to have the index of the currently displayed page for some operation. currentIndex of the ListView always stays == 0. How can I get it?

For those who prefer code:

 ListView
 {
      onCurrentIndexChanged: console.log(currentIndex) // this gets called only once - at startup
      delegate: Column
      {
           // The page displayed, only one page at a time
      }
 }

Thanks

Body:
I know this is quite old but I had the same problem and spend some time trying to find a way to get currentIndex that would work for me. In my case sometimes I need to change the width of my ListView so I have to recalculte currentIndex manualy every time I resize it.

But I found a highlightRangeMode property. When it's set to ListView.StrictlyEnforceRange then currentIndex is always updated automaticly and contains correct index of the currently visible item.

ListView {
    highlightRangeMode: ListView.StrictlyEnforceRange
    // ...
}


问:
Default namespace and prefixed namespace sharing same URI - Need to remove default namespace URI alone from element using python
The default Namespace and prefixed namespace shares same URI.

XML :

```<code><Envelope xmlns="http://www.ibm.com/mdm/schema" xmlns:sch="http://www.ibm.com/mdm/schema">
<sch:requesterName>cusadmin</sch:requesterName>
<sch:requesterLanguage>100</sch:requesterLanguage>
<sch:requestOrigin>QAOffshore</sch:requestOrigin>
<QuestionId>472</QuestionId>
</Envelope>
</code>```

I need to remove the default namespace alone from the element tag. since both default and prefixed namespace uri are same, the following code removes prefixed namespace too.:(

My code:

```<code>from lxml import etree
import re
df_temp1=[]
root_ns=etree.iterparse(open("D:\\Sample_data\\XML\\data_stack.xml",'r'),events=['start-ns'])
for _, node in root_ns:
    if(node[0]==''):
        df_temp1.append(node[1])
tree=etree.parse(open("D:\\Sample_data\\XML\\data_stack.xml",'r'))
for e in tree.iter():
        #if element has default namespace--remove the default namespace
        if '{' in e.tag:
            names = e.tag.split('}', 1)[0]
            names1=re.sub("[\{\}]","",names)
            if(names1 in df_temp1):
                e.tag=e.tag.split('}', 1)[1]
        print e.tag
</code>```

Output:

```<code>Envelope
requesterName
requesterLanguage
requestOrigin
QuestionId
</code>```

Expected Result:

```<code>Envelope
{http://www.ibm.com/mdm/schema}requesterName
{http://www.ibm.com/mdm/schema}requesterLanguage
{http://www.ibm.com/mdm/schema}requestOrigin
QuestionId
</code>```

Any idea on how to get this expected output?

答:
In order to remove your namespace prefix "sch" you have to register the namespace like below-

```<code>ET.register_namespace('', "http://www.ibm.com/mdm/schema")
</code>```

Body:
The default Namespace and prefixed namespace shares same URI.

XML :

<Envelope xmlns="http://www.ibm.com/mdm/schema" xmlns:sch="http://www.ibm.com/mdm/schema">
<sch:requesterName>cusadmin</sch:requesterName>
<sch:requesterLanguage>100</sch:requesterLanguage>
<sch:requestOrigin>QAOffshore</sch:requestOrigin>
<QuestionId>472</QuestionId>
</Envelope>

I need to remove the default namespace alone from the element tag. since both default and prefixed namespace uri are same, the following code removes prefixed namespace too.:(

My code:

from lxml import etree
import re
df_temp1=[]
root_ns=etree.iterparse(open("D:\\Sample_data\\XML\\data_stack.xml",'r'),events=['start-ns'])
for _, node in root_ns:
    if(node[0]==''):
        df_temp1.append(node[1])
tree=etree.parse(open("D:\\Sample_data\\XML\\data_stack.xml",'r'))
for e in tree.iter():
        #if element has default namespace--remove the default namespace
        if '{' in e.tag:
            names = e.tag.split('}', 1)[0]
            names1=re.sub("[\{\}]","",names)
            if(names1 in df_temp1):
                e.tag=e.tag.split('}', 1)[1]
        print e.tag

Output:

Envelope
requesterName
requesterLanguage
requestOrigin
QuestionId

Expected Result:

Envelope
{http://www.ibm.com/mdm/schema}requesterName
{http://www.ibm.com/mdm/schema}requesterLanguage
{http://www.ibm.com/mdm/schema}requestOrigin
QuestionId

Any idea on how to get this expected output?

Body:
In order to remove your namespace prefix "sch" you have to register the namespace like below-

ET.register_namespace('', "http://www.ibm.com/mdm/schema")


问:
gradlew assembleDebug generates no changes

Problem

I have just finished making a few changes in my React Native app and on the android emulator when reloading ( R, R) then changes appear.

I then ran the command:

```<code>./gradlew assembleDebug
</code>```

to generate a debug apk.

When I run it on the phone then changes aren't there, it still is an old version.

I have tried:

Deleting the apk in:

```<code>./app/build/outputs/apk
</code>```

Deleting the whole:

./app/build directory

Tried the command:

```<code>./gradlew cleanBuildCache
</code>```

Rebooting after cleaning the cache (3) and deleting the build directory (2)

Tried the command:

```<code>gradlew clean
</code>```

However I still get an old version of the apk generated each time.

答:
I think you must generate the bundle manually since you run the app on your real device.

Unable to load script from assets index.android.bundle on windows

Body:
Problem

I have just finished making a few changes in my React Native app and on the android emulator when reloading ( R, R) then changes appear.

I then ran the command:

./gradlew assembleDebug

to generate a debug apk.

When I run it on the phone then changes aren't there, it still is an old version.

I have tried:

Deleting the apk in:

./app/build/outputs/apk

Deleting the whole:

./app/build directory

Tried the command:

./gradlew cleanBuildCache

Rebooting after cleaning the cache (3) and deleting the build directory (2)

Tried the command:

gradlew clean

However I still get an old version of the apk generated each time.


问:
Find closest number in range?
What is the best way to find the closes value in a range...

for example i have an array with 0, 90, 180, 270, 360..
And a number 46...

What is the best way to find 90 in the array?

(in actipnscript 3)

Title: Find closest number in range?

Body:
var range:Array=[0, 90, 180, 270, 360];
trace(range.indexOf(90));


问:
Finite State Automata for a coin change-machine
I'm trying to build a table to describe the behaviour of the FSA for a coin change machine described below.

There is a slot that accepts a 50c coin and 2 buttons that a user can press to get a 20c or 10c coin as change.
As soon as the 50c coin is inserted the machine locks to prevent another coin from being added. When the user presses the 20c button the machine checks that the remaining value is sufficient then gives the user a 20c coin. If the remaining value isnt sufficient the machine "dies" (for simplicity). The 10c button works similarly.

The events of the machine are insert50c, give20c, give10c.

So, from my understanding this FSA has 6 states lets say 0,10,20,30,40,50. The states are represented by the value of money remaining to be returned. I've drawn a rough state diagram here but am i missing any transitions?

答:
your statechart looks good. In the task it said " a user can press to get a 20c or 10c coin". I am missing this user interactions completely. What is if there is an amount of 10c and the user presses 20c?

So if the machine is only allowed to accept 50c for change and not 20c it's ok. Every coin change, money exchange machine has a Cancel button to break up. What is with this?


问:
How would I parse an XML file into a list
List:

```<code>List<string> list = new List<string>();
</code>```

XML File:

```<code><memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>
</code>```

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

答:
Convert your XML to a list of objects....

Use these two mehods:

```<code>public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new ISOEncodingStringWriter();
        var serializer = new XmlSerializer(typeof(T));

        var xns = new XmlSerializerNamespaces();
        xns.Add(string.Empty, string.Empty);

        serializer.Serialize(stringwriter, dataToSerialize, xns);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}
</code>```

Make the following Class where you give the following attributes

```<code>[XmlRoot(ElementName = "Members", Namespace = "")]
public class Members
{
    [XmlElement("Member")]
    public Member[] member { get; set; }
}

public class Member
{
    [XmlElementAttribute("Name")]
    public string Name { get; set; }

    [XmlElementAttribute("Status")]
    public string Status { get; set; }
}
</code>```

Then deserialize your data.

```<code>Members result = Deserialize<Members>(XML_String);
</code>```

You got your members in a array and you ca convert that to a list if you want.

Body:
List:

List<string> list = new List<string>();

XML File:

<memberlist>
 <member>
  <name>Name</name>
  <status>Status</status>
 </member>
</memberlist>

How would I go about parsing this file, lets say (file.xml) into the list?

I've tried many ways but none of them seem to be working.

I want to check to see if the status is 'gold', and if it is, I would like to put the name of that member into the list.

Body:
Convert your XML to a list of objects....

Use these two mehods:

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new ISOEncodingStringWriter();
        var serializer = new XmlSerializer(typeof(T));

        var xns = new XmlSerializerNamespaces();
        xns.Add(string.Empty, string.Empty);

        serializer.Serialize(stringwriter, dataToSerialize, xns);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

Make the following Class where you give the following attributes

[XmlRoot(ElementName = "Members", Namespace = "")]
public class Members
{
    [XmlElement("Member")]
    public Member[] member { get; set; }
}

public class Member
{
    [XmlElementAttribute("Name")]
    public string Name { get; set; }

    [XmlElementAttribute("Status")]
    public string Status { get; set; }
}

Then deserialize your data.

Members result = Deserialize<Members>(XML_String);

You got your members in a array and you ca convert that to a list if you want.


问:
Can a bool var be safely accessed across threads?
This question pertains to Obj-C as the code is Obj-C, but I'd like to understand the difference (if any) in Swift too.

The golden rule in iOS that you shouldn't access an object across threads without using dispatch apis (or other) because this can lead to race conditions and other 'bad things'..

Is it safe however, to access a bool var from multiple threads? Since a bool var can only have one of two states, does that mean the following is always safe:

```<code>@property(nonatomic) BOOL processing;

-(void)callbackWithData(NSData *)data {
  if (_processing) {
    return;
  }
  // set from a background thread here
  _processing = YES;
  NSString *res = [self doSomeWorkThatReturnsString:data];

  dispatch_async(dispatch_get_main_queue(), ^{
    _someOtherCallback(res)
    // set from the main thread here
    _processing = NO;
  });
}
</code>```

callbackWithData gets called 1 or more times, sometimes in quick succession, on a background thread(s). Thus the _processing check to prevent the _someOtherCallback block from being called multiple times.

Maybe changing the property definition to atomic and using the synthesized getter/setter would be safer, but the question about direct access to the bool var still stands.

EDIT: To be clear, the atomic thing is a side question. My question is about where or not the code as shown is safe, or might it somehow produce memory corruption or a race condition/deadlock/other

答:
From my knowledge, atomic properties will generate accessor code that locks the getter versus the setter call. This is only important for retain (and maybe copy) properties, since all others will just simply assign/return a value without prior checking. They won't help you in a more complex scenario, like the one you depicted in your code, when you first check the value and then do something depending on it.

Especially, if your callbackWithData is called by mutiple threads, it might evaluate _processing and see false, but and direcly after this, another thread my set _processing to true. No atomic could have helped you here.

If this might be a problem, you ought to use @synchronized(...) or some NSLock in your callbackWithData to lock the complete / most important parts of your method.

Body:
This question pertains to Obj-C as the code is Obj-C, but I'd like to understand the difference (if any) in Swift too.

The golden rule in iOS that you shouldn't access an object across threads without using dispatch apis (or other) because this can lead to race conditions and other 'bad things'..

Is it safe however, to access a bool var from multiple threads? Since a bool var can only have one of two states, does that mean the following is always safe:

@property(nonatomic) BOOL processing;

-(void)callbackWithData(NSData *)data {
  if (_processing) {
    return;
  }
  // set from a background thread here
  _processing = YES;
  NSString *res = [self doSomeWorkThatReturnsString:data];

  dispatch_async(dispatch_get_main_queue(), ^{
    _someOtherCallback(res)
    // set from the main thread here
    _processing = NO;
  });
}

callbackWithData gets called 1 or more times, sometimes in quick succession, on a background thread(s). Thus the _processing check to prevent the _someOtherCallback block from being called multiple times.

Maybe changing the property definition to atomic and using the synthesized getter/setter would be safer, but the question about direct access to the bool var still stands.

EDIT: To be clear, the atomic thing is a side question. My question is about where or not the code as shown is safe, or might it somehow produce memory corruption or a race condition/deadlock/other


问:
Is there an IP multicasting possible in nanomsg?
How can I achieve an IP Multicasting in nanomsg?

I know that in ZeroMQ messaging, the IP Multicasting is achieved through a Pragmatic General Multicast ( PGM ) protocol.

Is there any way in nanomsg to also achieve the IP Multicasting?

答:
No, not yet.

The currently latest release of the nanomsg ( being 1.1.2. in EoY 2017 ) does not yet have a confirmed support for either a pgm:// or epgm:// transport classes, as you might have known from ZeroMQ toolkit.


问:
Django template tag to truncate text
Django has truncatewords template tag, which cuts the text at the given word count. But there is nothing like truncatechars.

What's the best way to cut the text in the template at given char-length limit?

答:
If you go on creating your own custom template tag, consider to leverage the native Django util Truncator.

The following is a sample usage of the Truncator util:

```<code>>>> from django.utils.text import Truncator
>>> Truncator("Django template tag to truncate text")
<Truncator: <function <lambda> at 0x10ff81b18>>
>>>Truncator("Django template tag to truncate text").words(3)
u'Django template tag...'
Truncator("Django template tag to truncate text").chars(20)
u'Django template t...'
</code>```

And here how you can use it inside a Django template tag:

```<code>from django import template
from django.utils.text import Truncator

register = template.Library()

@register.filter("custom_truncator")
def custom_truncator(value, max_len, trunc_words=False):
    """ Set trunc_words=True to truncate by words instead of by chars."""
    truncator = Truncator(value)
    return truncator.words(max_len) if trunc_words else truncator.chars(max_len)
</code>```

Eventually you can import the custom_truncator in any Django template.

Title: Django template tag to truncate text

Body:
If you go on creating your own custom template tag, consider to leverage the native Django util Truncator.

The following is a sample usage of the Truncator util:

>>> from django.utils.text import Truncator
>>> Truncator("Django template tag to truncate text")
<Truncator: <function <lambda> at 0x10ff81b18>>
>>>Truncator("Django template tag to truncate text").words(3)
u'Django template tag...'
Truncator("Django template tag to truncate text").chars(20)
u'Django template t...'

And here how you can use it inside a Django template tag:

from django import template
from django.utils.text import Truncator

register = template.Library()

@register.filter("custom_truncator")
def custom_truncator(value, max_len, trunc_words=False):
    """ Set trunc_words=True to truncate by words instead of by chars."""
    truncator = Truncator(value)
    return truncator.words(max_len) if trunc_words else truncator.chars(max_len)

Eventually you can import the custom_truncator in any Django template.


问:
JavaMail Message.reply(boolean) does not populate recipients
I'm trying to write a simple routine to reply to an email with a determined from address and subject, however, for whatever reason the reply method is not populating the recipients.

In the following example rep is always null, any attempt to call Transport.send results in an exception stating there were no recipients.

```<code>MimeMessage reply = (MimeMessage) message.reply(false);
Address[] rep = reply.getRecipients(Message.RecipientType.TO);
if (rep == null || rep.length == 0) {
    System.out.println("Reply aborted due to no recipient.");
} else {
    reply.setFrom(from);
    reply.setText(body);
    Transport.send(reply);
}
</code>```

I'm applying the pattern that's demonstrated on the Oracle jGuru pages and copied all over the place in various flavours.

答:
From the docs of reply:

If replyToAll is set, the new Message will be addressed to all recipients of this message. Otherwise, the reply will be addressed to only the sender of this message (using the value of the getReplyTo method).

So the logical next step would be to check what message.getReplyTo() returns. If that returns null, it explains the issue...

Body:
I'm trying to write a simple routine to reply to an email with a determined from address and subject, however, for whatever reason the reply method is not populating the recipients.

In the following example rep is always null, any attempt to call Transport.send results in an exception stating there were no recipients.

MimeMessage reply = (MimeMessage) message.reply(false);
Address[] rep = reply.getRecipients(Message.RecipientType.TO);
if (rep == null || rep.length == 0) {
    System.out.println("Reply aborted due to no recipient.");
} else {
    reply.setFrom(from);
    reply.setText(body);
    Transport.send(reply);
}

I'm applying the pattern that's demonstrated on the Oracle jGuru pages and copied all over the place in various flavours.