答:
You want to stop your timer at 3 hence the following.

You can make it better by introducing a function which returns the wanted message and then concatenate it to the default message

```<code>let messageNum = 0;
const id = setInterval(function() {
  messageNum++;
  document.write("Message " + writeMessage(messageNum));
  // stop the timer
  if (messageNum === 3) clearInterval(id);
}, 1000);

function writeMessage(num) {
  switch (num) {
    case 1:
      return "ONE";

    case 2:
      return "TWO";

    case 3:
      return "THREE";

    default:
      return null;
  }
}
</code>```

Title: SetInterval messages not changing

Body:
You want to stop your timer at 3 hence the following.

You can make it better by introducing a function which returns the wanted message and then concatenate it to the default message

let messageNum = 0;
const id = setInterval(function() {
  messageNum++;
  document.write("Message " + writeMessage(messageNum));
  // stop the timer
  if (messageNum === 3) clearInterval(id);
}, 1000);

function writeMessage(num) {
  switch (num) {
    case 1:
      return "ONE";

    case 2:
      return "TWO";

    case 3:
      return "THREE";

    default:
      return null;
  }
}


来源: stackexchange

问:
Highlighted item on listview gone when new message arrived Android Studio
I have a listview and it automatically filter all sim messages from mobile then I highlighted the items on the listview through clicking and it works, but the problem is when there's new message all of the highlighted item gone.Is theres any solution to remain the highlighted item when new message arrived? I use the following code. Thanks I appreciate your response.

layout : activitymain.xml

```<code><ListView
    android:id="@+id/textlistview"
    android:layout_width="match_parent"
    android:choiceMode="multipleChoice"
    android:listSelector="@drawable/default_color"
    android:layout_height="match_parent" />
</code>```

Broadcast Receiver : SMSReceiver.java

```<code>public class SMSReceiver extends BroadcastReceiver {
public static  final String SMS_BUNDLE = "pdus";

public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();

    if(intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
        if (bundle != null) {
            Object[] sms = (Object[]) bundle.get(SMS_BUNDLE);
            String smsMsg = "";
            SmsMessage smsMessage;
            for (int i = 0; i < sms.length; i++) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    String format = bundle.getString("format");

                    smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], format);
                }
                else {
                    smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
                }

                String msgBody = smsMessage.getMessageBody().toString();
                smsMsg +=msgBody;
            }
                text_message inst = text_message.Instance();
                inst.receive_data(smsMsg);
        }
    }
}}
</code>```

MainActivity : text_message.java

```<code>public void receive_data (final String smsMsg) {
        arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
        text_listview.setAdapter(arrayAdapter);
        arrayAdapter.add(smsMsg);
        arrayAdapter.notifyDataSetChanged();
}
</code>```

Filter messages : text_message.java

```<code> public  void refreshInbox(){
    arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
    ContentResolver cResolver = getContentResolver();
    Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
    int indexBody = smsInboxCursor.getColumnIndex("body");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;

    do{
        str = smsInboxCursor.getString(indexBody) ;
        arrayAdapter.add(str);
    }while (smsInboxCursor.moveToNext());
      }
</code>```

答:
Create a global array called isSelected like this

```<code>private boolean[] isSelected;
</code>```

Then assign your array with the size like this

```<code> isSelected=new boolean[arrayAdapter.getCount()]; // Do this after setting adapter
</code>```

and .setOnItemClickListener on listview and when the click happens to make sure selected of that index is set to true like this

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               isSelected[position]=!isSelected[position];
           }
       });
</code>```

And in receive_data() select those selected positions again

```<code>public void receive_data (final String smsMsg) {
        arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
        text_listview.setAdapter(arrayAdapter);
        arrayAdapter.add(smsMsg);
        arrayAdapter.notifyDataSetChanged();
        boolean[] tempSelected=new boolean[arrayAdapter.getCount()];

        for(int i=0;i<isSelected.length;i++)
        {
             tempSelected[i]=isSelected[i];
             if(tempSelected[i])
             {
               text_listview.setItemChecked(i,true);
             }
        }

        isSelected=tempSelected;

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a listview and it automatically filter all sim messages from mobile then I highlighted the items on the listview through clicking and it works, but the problem is when there's new message all of the highlighted item gone.Is theres any solution to remain the highlighted item when new message arrived? I use the following code. Thanks I appreciate your response.

layout : activitymain.xml

<ListView
    android:id="@+id/textlistview"
    android:layout_width="match_parent"
    android:choiceMode="multipleChoice"
    android:listSelector="@drawable/default_color"
    android:layout_height="match_parent" />

Broadcast Receiver : SMSReceiver.java

public class SMSReceiver extends BroadcastReceiver {
public static  final String SMS_BUNDLE = "pdus";

public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();

    if(intent.getAction().equalsIgnoreCase("android.provider.Telephony.SMS_RECEIVED")) {
        if (bundle != null) {
            Object[] sms = (Object[]) bundle.get(SMS_BUNDLE);
            String smsMsg = "";
            SmsMessage smsMessage;
            for (int i = 0; i < sms.length; i++) {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    String format = bundle.getString("format");

                    smsMessage = SmsMessage.createFromPdu((byte[]) sms[i], format);
                }
                else {
                    smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
                }

                String msgBody = smsMessage.getMessageBody().toString();
                smsMsg +=msgBody;
            }
                text_message inst = text_message.Instance();
                inst.receive_data(smsMsg);
        }
    }
}}

MainActivity : text_message.java

public void receive_data (final String smsMsg) {
        arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
        text_listview.setAdapter(arrayAdapter);
        arrayAdapter.add(smsMsg);
        arrayAdapter.notifyDataSetChanged();
}

Filter messages : text_message.java

 public  void refreshInbox(){
    arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list_items);
    ContentResolver cResolver = getContentResolver();
    Cursor smsInboxCursor = cResolver.query(Uri.parse("content://sms/inbox"),null,null,null,null);
    int indexBody = smsInboxCursor.getColumnIndex("body");
    if (indexBody < 0 || !smsInboxCursor.moveToFirst()) return;

    do{
        str = smsInboxCursor.getString(indexBody) ;
        arrayAdapter.add(str);
    }while (smsInboxCursor.moveToNext());
      }

Body:
Create a global array called isSelected like this

private boolean[] isSelected;

Then assign your array with the size like this

 isSelected=new boolean[arrayAdapter.getCount()]; // Do this after setting adapter

and .setOnItemClickListener on listview and when the click happens to make sure selected of that index is set to true like this

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
           @Override
           public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               isSelected[position]=!isSelected[position];
           }
       });

And in receive_data() select those selected positions again

public void receive_data (final String smsMsg) {
        arrayAdapter = new ArrayAdapter(this,R.layout.list_item, list_items);
        text_listview.setAdapter(arrayAdapter);
        arrayAdapter.add(smsMsg);
        arrayAdapter.notifyDataSetChanged();
        boolean[] tempSelected=new boolean[arrayAdapter.getCount()];

        for(int i=0;i<isSelected.length;i++)
        {
             tempSelected[i]=isSelected[i];
             if(tempSelected[i])
             {
               text_listview.setItemChecked(i,true);
             }
        }

        isSelected=tempSelected;

}


问:
Nginx restrict domains
Please find the below setting which is placed in /etc/nginx/sites-enabled under my site domain name. (mysite.lk)

```<code>server {
   listen   80;
   server_name mysite.lk www.mysite.lk;

   location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

}
</code>```

The application is running on port 8080 and here I'm redirecting all the 80 traffic to 8080.
My website only uses mysite.lk and www.mysite.lk domain names.

Hence, I want to restrict/block all other domains (except mysite.lk and www.mysite.lk) which are coming to this server IP. What is the change that I need to do to achieve this?

I tried numerous things such as answers given in the
Why is nginx responding to any domain name?, but was getting errors at the nginx startup.

Please help me out!
Thanks.

Update

Found the Answer. A catch-all server block should needed in the top of the config before the given config like below. The code block should be like this.

```<code>server {
    return 403;
}

server {
    listen   80;
    server_name mysite.lk www.mysite.lk;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

}
</code>```

答:
I have a player script with a Firewall that blocks the websites that are not on my whitelist but it turns out that if I have the Firewall activated, the videos stop working in my Android application, they know how I can modify my Firewall to work with package names Android applications to add my application to the white list and be able to play videos in my app with the Firewall active since I must have it disabled to be able to play the videos in my application.</p>

```<code>/**
 * Disable access baseed on referer
 */
if (Data::Get("accs_restriction") == "enable") {
    $domains = explode(",", Data::Get("allowed_domains"));
    $referer = parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST);
    if (empty($referer) || !in_array($referer, $domains)) {
        header('HTTP/1.0 403 Forbidden');
        require TEMPLATES . "pages/access_denied.php";
        exit;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Nginx restrict domains

Body:
Please find the below setting which is placed in /etc/nginx/sites-enabled under my site domain name. (mysite.lk)

server {
   listen   80;
   server_name mysite.lk www.mysite.lk;

   location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

}

The application is running on port 8080 and here I'm redirecting all the 80 traffic to 8080.
My website only uses mysite.lk and www.mysite.lk domain names.

Hence, I want to restrict/block all other domains (except mysite.lk and www.mysite.lk) which are coming to this server IP. What is the change that I need to do to achieve this?

I tried numerous things such as answers given in the
Why is nginx responding to any domain name?, but was getting errors at the nginx startup.

Please help me out!
Thanks.

Update

Found the Answer. A catch-all server block should needed in the top of the config before the given config like below. The code block should be like this.

server {
    return 403;
}

server {
    listen   80;
    server_name mysite.lk www.mysite.lk;
    location / {
        proxy_set_header   X-Forwarded-For $remote_addr;
        proxy_set_header   Host $http_host;
        proxy_pass "http://127.0.0.1:8080";
   }

}

Body:
I have a player script with a Firewall that blocks the websites that are not on my whitelist but it turns out that if I have the Firewall activated, the videos stop working in my Android application, they know how I can modify my Firewall to work with package names Android applications to add my application to the white list and be able to play videos in my app with the Firewall active since I must have it disabled to be able to play the videos in my application.

/**
 * Disable access baseed on referer
 */
if (Data::Get("accs_restriction") == "enable") {
    $domains = explode(",", Data::Get("allowed_domains"));
    $referer = parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST);
    if (empty($referer) || !in_array($referer, $domains)) {
        header('HTTP/1.0 403 Forbidden');
        require TEMPLATES . "pages/access_denied.php";
        exit;
    }
}


问:
What's difference between Math.pow(9, 18) and 9^18
when I use Math.pow(9, 18) =150094635296999136

when I use web Calculator 9^18 = 150094635296999121  (http://web2.0calc.com/)

when I use Google calculator 9^18 = 1.50094635 × 10^17

why it is different ?

答:
At that range, the difference between successive double values is 32. 150094635296999121 is the correct answer as an integer, but that number cannot be exactly represented as a double.

You can use BigInteger to get the exact answer:

```<code>Math.pow(9, 18) == 150094635296999136
BigInteger.valueOf(9).pow(18) == 150094635296999121
</code>```

Body:
At that range, the difference between successive double values is 32. 150094635296999121 is the correct answer as an integer, but that number cannot be exactly represented as a double.

You can use BigInteger to get the exact answer:

Math.pow(9, 18) == 150094635296999136
BigInteger.valueOf(9).pow(18) == 150094635296999121


问:
Select from a comma separated list in a colum
I have a table, Table 1,

and I want to select all regions that are neighbours of region 3. What would be my query for this? The NEIGHBOUR column is a CHAR column.

I know the table should not be set up this way, but that is what I have to work with, as I don't have the rights to the database.

答:
You can use STRING_SPLIT() as

```<code>SELECT *
FROM Data
WHERE Region IN
(
  SELECT Value
  FROM STRING_SPLIT((SELECT Neighbor FROM Data WHERE Region = 3), ',')
);
</code>```

The query 'll returns 0 rows because there is no region in the table marked as a neighbor for region 3.

If you change (3, 'Name3', '5,8,12'), to (3, 'Name3', '1,2'),, then it'll returns the regions 1 and 2 because they 're neighbors of region 3.

Here is a db<>fiddle.

Another way without using a string splitter

```<code>SELECT *
FROM Data D
JOIN (VALUES((SELECT Neighbor FROM Data WHERE Region = 3))) T(V)
ON CONCAT(',', T.V, ',') LIKE CONCAT('%,', D.Region,',%');
</code>```

Body:
You can use STRING_SPLIT() as

SELECT *
FROM Data
WHERE Region IN
(
  SELECT Value
  FROM STRING_SPLIT((SELECT Neighbor FROM Data WHERE Region = 3), ',')
);

The query 'll returns 0 rows because there is no region in the table marked as a neighbor for region 3.

If you change (3, 'Name3', '5,8,12'), to (3, 'Name3', '1,2'),, then it'll returns the regions 1 and 2 because they 're neighbors of region 3.

Here is a db<>fiddle.

Another way without using a string splitter

SELECT *
FROM Data D
JOIN (VALUES((SELECT Neighbor FROM Data WHERE Region = 3))) T(V)
ON CONCAT(',', T.V, ',') LIKE CONCAT('%,', D.Region,',%');


问:
How to add DbContext at runtime
I am trying to add a DbContext at runtime. The reason I'm doing is because the clients use different database schemas. By so doing I cannot add it in ConfigureServices method of the StartUp because I need to know the client first then try to create a connection string with the appropriate schema in it since the Configure method is called every time a request is made. I have tried accessing the IServiceCollection but the container says no service of type IServiceCollection has been registered. I now tried registering IServiceCollection itself in the startUp's ConfigureServices method then the application refuses to start entirely. Is there a better way to add this at runtime?

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceCollection services)
        {
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseMvc();

            IClientValidator clientValidator = app.ApplicationServices.GetRequiredService<IClientValidator>();
            services.AddDbContext<ClientDbContext>(options =>
                options.UseSqlServer(clientValidator.GetConnectionString()));
        }
</code>```

The client validator is in charge of resolving the clients connection string.

答:
Okay I resolved that re-initialization problem by adding the QueryTrackingBehaviour.NoTracking overload of the AddDbContext

```<code>services.AddDbContext<DatabaseContext>(options =>
{
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    options.UseSqlServer(databaseSettings.DefaultConnection);
});
</code>```

The bottom line is that instead of doing that in the startup file I initialized the connection by overriding the OnConfiguring method of DbContext But I found a better solution prior to those discussed above. The solution is below

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connectionString).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
}
</code>```

Title: How to add DbContext at runtime

Body:
I am trying to add a DbContext at runtime. The reason I'm doing is because the clients use different database schemas. By so doing I cannot add it in ConfigureServices method of the StartUp because I need to know the client first then try to create a connection string with the appropriate schema in it since the Configure method is called every time a request is made. I have tried accessing the IServiceCollection but the container says no service of type IServiceCollection has been registered. I now tried registering IServiceCollection itself in the startUp's ConfigureServices method then the application refuses to start entirely. Is there a better way to add this at runtime?

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceCollection services)
        {
            // global cors policy
            app.UseCors(x => x
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());

            app.UseAuthentication();
            app.UseMvc();

            IClientValidator clientValidator = app.ApplicationServices.GetRequiredService<IClientValidator>();
            services.AddDbContext<ClientDbContext>(options =>
                options.UseSqlServer(clientValidator.GetConnectionString()));
        }

The client validator is in charge of resolving the clients connection string.

Body:
Okay I resolved that re-initialization problem by adding the QueryTrackingBehaviour.NoTracking overload of the AddDbContext

services.AddDbContext<DatabaseContext>(options =>
{
    options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
    options.UseSqlServer(databaseSettings.DefaultConnection);
});

The bottom line is that instead of doing that in the startup file I initialized the connection by overriding the OnConfiguring method of DbContext But I found a better solution prior to those discussed above. The solution is below

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connectionString).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
}


问:
Unzip all the items from the output of rglob() method using pathlib module
I have a folder that contains zip files in subfolders. I want to unzip all the files using this python code. code shows no error but the files are not extracted can't figure out the problem. Thanks in Advance.</p>

```<code>from zipfile import ZipFile
from pathlib import Path

entries = Path('E:\\Bootcamp')
for entry in entries.rglob('*.zip'):
    with ZipFile(entry, 'r') as zip:
        print('Check1')
        zip.extractall()
    print('check2')

</code>```

答: The extracted files will be located in the folder where your python file has been saved</p>

Body:
I have a folder that contains zip files in subfolders. I want to unzip all the files using this python code. code shows no error but the files are not extracted can't figure out the problem. Thanks in Advance.

from zipfile import ZipFile
from pathlib import Path

entries = Path('E:\\Bootcamp')
for entry in entries.rglob('*.zip'):
    with ZipFile(entry, 'r') as zip:
        print('Check1')
        zip.extractall()
    print('check2')


问:
How to count the numbers where the absolute value is greater than LOG2 cutoff with COUNTIFS in Excel?
I have an excel sheet with some numbers and I want to count the numbers where its absolute value is >=LOG(y,2).

I know COUNTIFS can be used to find the numbers greater than a value, but I don't know how to include the LOG  and ABS functions into the formula.

For example my numbers, x= 12,34,-15,-23,-5,45,-50
and I want to count the numbers where the ABS(x)>=LOG(y,2) where Y can be variable, for example y=3.

答:
This is the best way I found:
There is not seems to be any other way.
You can hide the =ABS column if it helps...


问:
how can i ignore error in python properly?
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

```<code>a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)
</code>```

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

```<code>try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None
</code>```

looks ridiculous, doesnt it?

how can i handle it gracefully?

答:
in your case you should use:</p>

```<code>try:
    f = soup.find(something).find(something)
except AttributeError:
    f = None
</code>```

Body:
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None

looks ridiculous, doesnt it?

how can i handle it gracefully?

Body:
in your case you should use:

try:
    f = soup.find(something).find(something)
except AttributeError:
    f = None


问:
Hibernate Composite primary key contains foreign key which is subset of other tables primary key, how to map?
The scenario is as follows

Table A has a composite PK.

```
Table A <br>-------- <br> a1 (pk)<br> a2 (pk)<br> a3 (pk)<br> foo<br> bar<br> LastUpdateDate<br> LastUpdateUser
======== ```

Table B has a composite PK too which is actually subset of A's PK, here is working as FK as well. There is no forced FK constraint.

```
Table B <br>--------
 a1 (fk,pk)
 a2 (fk,pk)
 foo
 bar
 LastUpdateDate
 LastUpdateUser
========
```

I tried several ways, and none of them works. Can anyone tell a working Hibernate mapping solution? better in annotation style.

Thanks a lot.

Viv

答:
I can see following set up. Although it may be tricky to get to work and, based on my experience, it's unnecessary complexity.

```<code>class A implements Serializable {
   @Id
   private PK id = new PK();
   @Embeddable
    public static final class PK implements Serializable {
        @ManyToOne
        @JoinColumns ({
        @JoinColumn(name="A1_COL", referencedColumnName = "id.a1"),
        @JoinColumn(name="A2_COL", referencedColumnName = "id.a2"),

        })
         B b;
        @Basic String a3;
    }
 }

class B implements Serializable {
   @Id
   private PK id = new PK();
   @Embeddable
    public static final class PK implements Serializable {
        @Basic String a1;
        @Basic String a2;
        @Basic String a3;
    }
 }
</code>```

You should be able to access be via

```<code>a.getId().getB()
</code>```

Add setters/getters as necessary.

Usually this type of problems requires a lot of trial and error, so don't expect this to work right away. But that should give you a direction for digging. Once you nail down final configuration, please add it to you question so somebody can benefit from it in future.

Body:
The scenario is as follows

Table A has a composite PK.

Table A
--------
 a1 (pk)
 a2 (pk)
 a3 (pk)
 foo
 bar
 LastUpdateDate
 LastUpdateUser
========

Table B has a composite PK too which is actually subset of A's PK, here is working as FK as well. There is no forced FK constraint.

Table B
--------
 a1 (fk,pk)
 a2 (fk,pk)
 foo
 bar
 LastUpdateDate
 LastUpdateUser
========

I tried several ways, and none of them works. Can anyone tell a working Hibernate mapping solution? better in annotation style.

Thanks a lot.

Viv

Body:
I can see following set up. Although it may be tricky to get to work and, based on my experience, it's unnecessary complexity.

class A implements Serializable {
   @Id
   private PK id = new PK();
   @Embeddable
    public static final class PK implements Serializable {
        @ManyToOne
        @JoinColumns ({
        @JoinColumn(name="A1_COL", referencedColumnName = "id.a1"),
        @JoinColumn(name="A2_COL", referencedColumnName = "id.a2"),

        })
         B b;
        @Basic String a3;
    }
 }

class B implements Serializable {
   @Id
   private PK id = new PK();
   @Embeddable
    public static final class PK implements Serializable {
        @Basic String a1;
        @Basic String a2;
        @Basic String a3;
    }
 }

You should be able to access be via

a.getId().getB()

Add setters/getters as necessary.

Usually this type of problems requires a lot of trial and error, so don't expect this to work right away. But that should give you a direction for digging. Once you nail down final configuration, please add it to you question so somebody can benefit from it in future.


问:
how to make my Calculator with tkinter calculate everything in the Entry?
so i wanted to make a simple calculator with tkinter, but got stuck in a issue. and the issue is that i don't really know how to make tkinter take everything from the entry calculate it and that ouputs it in the same entry. everytime i try to save everything that the user inputs in the entry in a variable (i do this by trying to save the text from function set_text) either i get a name error = (NameError: name 'data_from_entry' is not defined)(even when i use
global data_from_entry) or it only saves the last part of the users input(i thing this happens because the text in the function set_text changes everytime i click another button, so at the end it only has the last string that i use)

i also tried calculating with eval, but that also didn't work.

so here's my code, feel free to copy it and modify anything u want, all tips are welcome

```<code>'''from tkinter import *

root = Tk()
root.title('Calculator')
root.iconbitmap('abc.ico') #my icon

HEIGHT = 530
WIDTH = 325

canvas = Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame1 = Frame(root, bg='#BEBDB8', bd=5)
frame1.place(relx=0.5, rely=0, relwidth=1, relheight=0.3, anchor='n')

entry1 = Entry(frame1, bg='#BEBDB8')
entry1.place(relx=0.5, rely=0, relwidth=0.97, relheight=0.97, anchor='n')
entry1.config(font=("Courier", 44))

def CombinedFunctions(): # i use this so i can give a button multiply commands
    set_text('')
    Result()

global text2 # now text2 is not a local variable anymore

def set_text(text):
    entry1.insert(END, text)
    text2 =''
    text2 = str(text) # tryna save the text in text2 so it's easier and so i make sure it's a string
global data # global again
data = ''
data = data + text2
def Result():
    print(str(data)) # here im using just print to check if the real problem is eval or just my bad #code skills
    #calculate = str(eval(str(data))) #here is where i tried eval
    #entry1.delete(0, END)
    #entry1.insert(0, calculate)

#global database2, database

#def Database(text):                   # some other things i tried
#   database2 = ""
#   database2 = database2 + database

def delete():
    entry1.delete(0, END)   # deleting strings with the delete button

frame2 = Frame(root, bg='#BEBDB8', bd=5)
frame2.place(relx=0, rely=0.3, relwidth=1, relheight=0.7)

button1 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=1, font=('Courier', 30), command=lambda: set_text(1))
button1.place(relx=0.015, rely=0, relwidth=0.225, relheight=0.150)

button2 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=2, font=('Courier', 30), command=lambda: set_text(2))
button2.place(relx=0.270, rely=0, relwidth=0.225, relheight=0.150)

button3 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=3, font=('Courier', 30), command=lambda: set_text(3))
button3.place(relx=0.525, rely=0, relwidth=0.225, relheight=0.150)

button_delete = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='<-', font=('Courier', 30), command=lambda: delete())
button_delete.place(relx=0.77, rely=0, relwidth=0.225, relheight=0.150)

button4 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=4, font=('Courier', 30), command=lambda: set_text(4))
button4.place(relx=0.015, rely=0.160, relwidth=0.225, relheight=0.150)

button5 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=5, font=('Courier', 30), command=lambda: set_text(5))
button5.place(relx=0.270, rely=0.160, relwidth=0.225, relheight=0.150)

button6 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=6, font=('Courier', 30), command=lambda: set_text(6))
button6.place(relx=0.525, rely=0.160, relwidth=0.225, relheight=0.150)

button_multiply = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='x', font=('Courier', 30), command=lambda: set_text('*'))
button_multiply.place(relx=0.77, rely=0.160, relwidth=0.105, relheight=0.150)

button_devide = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=':', font=('Courier', 30), command=lambda: set_text(':'))
button_devide.place(relx=0.89, rely=0.160, relwidth=0.105, relheight=0.150)

button7 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=7, font=('Courier', 30), command=lambda: set_text(7))
button7.place(relx=0.015, rely=0.320, relwidth=0.225, relheight=0.150)

button8 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=8, font=('Courier', 30), command=lambda: set_text(8))
button8.place(relx=0.270, rely=0.320, relwidth=0.225, relheight=0.150)

button9 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=9, font=('Courier', 30), command=lambda: set_text(9))
button9.place(relx=0.525, rely=0.320, relwidth=0.225, relheight=0.150)

button_add = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='+', font=('Courier', 30), command=lambda: set_text('+'))
button_add.place(relx=0.77, rely=0.320, relwidth=0.105, relheight=0.150)

button_minus = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='-', font=('Courier', 30), command=lambda: set_text('-'))
button_minus.place(relx=0.89, rely=0.320, relwidth=0.105, relheight=0.150)

button_date = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='date', font=('Courier', 20), command=lambda: set_text('you forgot this'))
button_date.place(relx=0.015, rely=0.480, relwidth=0.225, relheight=0.150)

button0 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=0, font=('Courier', 30), command=lambda: set_text(0))
button0.place(relx=0.270, rely=0.480, relwidth=0.225, relheight=0.150)

button_float = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=',', font=('Courier', 30), command=lambda: set_text('.'))
button_float.place(relx=0.525, rely=0.480, relwidth=0.225, relheight=0.150)

button_result = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='=', font=('Courier', 30), command=lambda: CombinedFunctions()) # here i call the combinedfunction which calls #other 2 functions
button_result.place(relx=0.77, rely=0.480, relwidth=0.225, relheight=0.150)'''
</code>```

any help is welcome :)

答:
you should use eval() expression like this (with a string inside)

x='56*78'
eval(x)

# 4368
```

Body:
so i wanted to make a simple calculator with tkinter, but got stuck in a issue. and the issue is that i don't really know how to make tkinter take everything from the entry calculate it and that ouputs it in the same entry. everytime i try to save everything that the user inputs in the entry in a variable (i do this by trying to save the text from function set_text) either i get a name error = (NameError: name 'data_from_entry' is not defined)(even when i use
global data_from_entry) or it only saves the last part of the users input(i thing this happens because the text in the function set_text changes everytime i click another button, so at the end it only has the last string that i use)

i also tried calculating with eval, but that also didn't work.

so here's my code, feel free to copy it and modify anything u want, all tips are welcome

'''from tkinter import *

root = Tk()
root.title('Calculator')
root.iconbitmap('abc.ico') #my icon

HEIGHT = 530
WIDTH = 325

canvas = Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

frame1 = Frame(root, bg='#BEBDB8', bd=5)
frame1.place(relx=0.5, rely=0, relwidth=1, relheight=0.3, anchor='n')

entry1 = Entry(frame1, bg='#BEBDB8')
entry1.place(relx=0.5, rely=0, relwidth=0.97, relheight=0.97, anchor='n')
entry1.config(font=("Courier", 44))

def CombinedFunctions(): # i use this so i can give a button multiply commands
    set_text('')
    Result()

global text2 # now text2 is not a local variable anymore

def set_text(text):
    entry1.insert(END, text)
    text2 =''
    text2 = str(text) # tryna save the text in text2 so it's easier and so i make sure it's a string
global data # global again
data = ''
data = data + text2
def Result():
    print(str(data)) # here im using just print to check if the real problem is eval or just my bad #code skills
    #calculate = str(eval(str(data))) #here is where i tried eval
    #entry1.delete(0, END)
    #entry1.insert(0, calculate)

#global database2, database

#def Database(text):                   # some other things i tried
#   database2 = ""
#   database2 = database2 + database

def delete():
    entry1.delete(0, END)   # deleting strings with the delete button

frame2 = Frame(root, bg='#BEBDB8', bd=5)
frame2.place(relx=0, rely=0.3, relwidth=1, relheight=0.7)

button1 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=1, font=('Courier', 30), command=lambda: set_text(1))
button1.place(relx=0.015, rely=0, relwidth=0.225, relheight=0.150)

button2 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=2, font=('Courier', 30), command=lambda: set_text(2))
button2.place(relx=0.270, rely=0, relwidth=0.225, relheight=0.150)

button3 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=3, font=('Courier', 30), command=lambda: set_text(3))
button3.place(relx=0.525, rely=0, relwidth=0.225, relheight=0.150)

button_delete = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='<-', font=('Courier', 30), command=lambda: delete())
button_delete.place(relx=0.77, rely=0, relwidth=0.225, relheight=0.150)

button4 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=4, font=('Courier', 30), command=lambda: set_text(4))
button4.place(relx=0.015, rely=0.160, relwidth=0.225, relheight=0.150)

button5 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=5, font=('Courier', 30), command=lambda: set_text(5))
button5.place(relx=0.270, rely=0.160, relwidth=0.225, relheight=0.150)

button6 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=6, font=('Courier', 30), command=lambda: set_text(6))
button6.place(relx=0.525, rely=0.160, relwidth=0.225, relheight=0.150)

button_multiply = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='x', font=('Courier', 30), command=lambda: set_text('*'))
button_multiply.place(relx=0.77, rely=0.160, relwidth=0.105, relheight=0.150)

button_devide = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=':', font=('Courier', 30), command=lambda: set_text(':'))
button_devide.place(relx=0.89, rely=0.160, relwidth=0.105, relheight=0.150)

button7 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=7, font=('Courier', 30), command=lambda: set_text(7))
button7.place(relx=0.015, rely=0.320, relwidth=0.225, relheight=0.150)

button8 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=8, font=('Courier', 30), command=lambda: set_text(8))
button8.place(relx=0.270, rely=0.320, relwidth=0.225, relheight=0.150)

button9 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=9, font=('Courier', 30), command=lambda: set_text(9))
button9.place(relx=0.525, rely=0.320, relwidth=0.225, relheight=0.150)

button_add = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='+', font=('Courier', 30), command=lambda: set_text('+'))
button_add.place(relx=0.77, rely=0.320, relwidth=0.105, relheight=0.150)

button_minus = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='-', font=('Courier', 30), command=lambda: set_text('-'))
button_minus.place(relx=0.89, rely=0.320, relwidth=0.105, relheight=0.150)

button_date = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='date', font=('Courier', 20), command=lambda: set_text('you forgot this'))
button_date.place(relx=0.015, rely=0.480, relwidth=0.225, relheight=0.150)

button0 = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=0, font=('Courier', 30), command=lambda: set_text(0))
button0.place(relx=0.270, rely=0.480, relwidth=0.225, relheight=0.150)

button_float = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text=',', font=('Courier', 30), command=lambda: set_text('.'))
button_float.place(relx=0.525, rely=0.480, relwidth=0.225, relheight=0.150)

button_result = Button(frame2, bg='#D9DDDC', relief='flat', activebackground='#BEBDB8', text='=', font=('Courier', 30), command=lambda: CombinedFunctions()) # here i call the combinedfunction which calls #other 2 functions
button_result.place(relx=0.77, rely=0.480, relwidth=0.225, relheight=0.150)'''

any help is welcome :)


问:
Angular AuthGuard is not working
I am using angular CanActivate Authguard interface to protect my component.

```<code>@Injectable()
export class AuthGuard implements CanActivate{

constructor(private router: Router, private authService: AuthenticationService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {

    this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {

        if(!isLoggedIn){
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    })

    this.router.navigate(['/login']);
    return false;
   }
}
</code>```

i added it to my router configuration like this.

```<code>const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]
</code>```

I also added it to providers array.

```<code>@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})
</code>```

But when i run the application its giving following error

StaticInjectorError(AppModule)[AuthGuard]:

  StaticInjectorError(Platform: core)[AuthGuard]:  NullInjectorError: No
  provider for AuthGuard!

I think i implemented it courrectly but its not working . what i am doing wrong???

答:
You should add AuthGuard to app.module in providers

```<code>Providers:[AuthGuard]
</code>```

app.module

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from 'src/app/core/auth.guard';

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  declarations: [
    AppComponent,
  ],
  providers: [AuthGuard], // Add AuthGuard here
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Title: Angular AuthGuard is not working

Body:
I am using angular CanActivate Authguard interface to protect my component.

@Injectable()
export class AuthGuard implements CanActivate{

constructor(private router: Router, private authService: AuthenticationService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | Observable<boolean> | Promise<boolean> {

    this.authService.isLoggedIn.take(1).map((isLoggedIn : boolean) => {

        if(!isLoggedIn){
            this.router.navigate(['/login']);
            return false;
        }

        return true;
    })

    this.router.navigate(['/login']);
    return false;
   }
}

i added it to my router configuration like this.

const appRoutes: Routes = [
{path : '',redirectTo : 'login',pathMatch : 'full'},
{ path: 'home', component: HomeComponent,canActivate : [AuthGuard] }
]

I also added it to providers array.

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
providers: [AuthGuard,
ExpenseService,SellDetailService,AuthenticationService],
styleUrls: ['./app.component.css']
})

But when i run the application its giving following error

StaticInjectorError(AppModule)[AuthGuard]:

  StaticInjectorError(Platform: core)[AuthGuard]:  NullInjectorError: No
  provider for AuthGuard!

I think i implemented it courrectly but its not working . what i am doing wrong???

Body:
You should add AuthGuard to app.module in providers

Providers:[AuthGuard]

app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthGuard } from 'src/app/core/auth.guard';

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule,
  ],
  declarations: [
    AppComponent,
  ],
  providers: [AuthGuard], // Add AuthGuard here
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
C99: Custom implementations of non-standard functions
In my project, I want to use a non-standard library function, which which may not be defined on certain systems. In my case, it is strlcpy.

From man strcpy:

```<code>Some systems (the BSDs, Solaris, and others) provide the following function:

    size_t strlcpy(char *dest, const char *src, size_t size);

...
</code>```

My system does not implement strlcpy, so I rolled my own. All is well, until compiling on a system that already has strlcpy defined: error: conflicting types for strlcpy.

My question: how can I implement a function that may cause naming conflicts down the road? Can I use some directive like #ifdef some_macro(strlcpy), or am I simply left with renaming strlcpy to my_strlcpy?

答:
check if you need to include.

Example - the list of systems will be much longer I think

```<code>#if !defined(__FreeBSD__)
#include "mystring.h"
#endif
</code>```

Body:
In my project, I want to use a non-standard library function, which which may not be defined on certain systems. In my case, it is strlcpy.

From man strcpy:

Some systems (the BSDs, Solaris, and others) provide the following function:

    size_t strlcpy(char *dest, const char *src, size_t size);

...

My system does not implement strlcpy, so I rolled my own. All is well, until compiling on a system that already has strlcpy defined: error: conflicting types for strlcpy.

My question: how can I implement a function that may cause naming conflicts down the road? Can I use some directive like #ifdef some_macro(strlcpy), or am I simply left with renaming strlcpy to my_strlcpy?

Body:
check if you need to include.

Example - the list of systems will be much longer I think

#if !defined(__FreeBSD__)
#include "mystring.h"
#endif


问:
Python package not found, no module named "coroapi"
I created a package and uploaded the package to PyPi, installed it with PIP and when I try to test and import it, it can't find the my package
called coroapi, and it's its GitHub - coronavirus-api

Who can try to download and use because maybe I made a mistake there, because it's only a second time that I create a package, or just check it out please, because I'm stuck on it, and I want to finally release it.

Example

```<code>import coroapi

instance = coroapi.Corona()
usa_infected_people = instance.get_country_infected('usa', text=False)
print(usa_infected_people)

>> No module named "coroapi"
</code>```

Pip output:

```<code>> pip3 install coroapi
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: coroapi in ./.local/lib/python3.8/site-packages (1.1)
Requirement already satisfied: beautifulsoup4 in ./.local/lib/python3.8/site-packages (from coroapi) (4.9.0)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from coroapi) (2.22.0)
Requirement already satisfied: soupsieve>1.2 in ./.local/lib/python3.8/site-packages (from beautifulsoup4->coroapi) (2.0)
</code>```

答:
The problem is your package is not installing all of the files in your project. If you run pip3 show -f coroapi, you'll see that it is showing only a directory called coroapi-1.1.dist-info, not one for coroapi.

You can also see this on your PyPi page. If you download your tar.gz file, you'll notice it doesn't include your coroapi folder at all:

I cloned your Github repo and ran python3 setup.py sdist bdist_wheel, and it created a dist directory with a tar.gz file including everything correctly. So maybe you just published an old version of your package to PyPi. Try rebuilding and uploading again. Follow this page as a guide.

Body:
I created a package and uploaded the package to PyPi, installed it with PIP and when I try to test and import it, it can't find the my package
called coroapi, and it's its GitHub - coronavirus-api

Who can try to download and use because maybe I made a mistake there, because it's only a second time that I create a package, or just check it out please, because I'm stuck on it, and I want to finally release it.

Example

import coroapi

instance = coroapi.Corona()
usa_infected_people = instance.get_country_infected('usa', text=False)
print(usa_infected_people)

>> No module named "coroapi"

Pip output:

> pip3 install coroapi
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: coroapi in ./.local/lib/python3.8/site-packages (1.1)
Requirement already satisfied: beautifulsoup4 in ./.local/lib/python3.8/site-packages (from coroapi) (4.9.0)
Requirement already satisfied: requests in /usr/lib/python3/dist-packages (from coroapi) (2.22.0)
Requirement already satisfied: soupsieve>1.2 in ./.local/lib/python3.8/site-packages (from beautifulsoup4->coroapi) (2.0)


问:
Tableau data layer to one state only
I'm looking to mask all of the detail in Tableau maps other than the state I'm filtered on.  The data layer can seemingly only be applied to all or nothing.  I'm unable to filter or limit to the dataset to which I'm working.  Seems simple, yet 30min of google search can't find answer.  Thank you!

答:
I don’t believe that the map server can alter what it displays as a data layer based on the filters you choose in Tableau. The map server is a separate program that returns image tiles upon request. The map server doesn’t know about your filters on the client side - or even that the client app is called Tableau. It just knows that some client application asked for an image representing a map within a particular coordinate bounding box, with whatever style and data layer options that the client application passed.

That doesn’t mean you can’t accomplish your goal, just that you have to find a way to accomplish it on the Tableau side instead the map server side — unless you want to develop your own map server with that functionality, which would be an effort even with a tool like Mapbox.

You could

Decide what “data layers” the map server is providing that you want to retain and at what level of detail, say Avg(Income) per County

Go get that data, possibly from the census bureau

Uncheck the box for your data layers in the Map Layers pane

Use the data you downloaded above to color the map sections as desired

Add other marks to represent additional info as needed using a dual-axis and possibly data blending

Then voila, your data layers will obey your filter. You just had to move where that info was drawn. Of course, you had to find the necessary data instead of relying on the whoever built the map server to do that, but that isn’t too tough.

To handle the Tableau side of things, especially assuming you want to combine the layer we’ve been discussing with other data on your map, you will need to learn about a few other Tableau concepts. So read up on dual-axis maps, level of detail and possibly data blending.

Title: Tableau data layer to one state only


问:
How to correctly update TabBarItem's badge value?
I have a three tableViewController and they’re managed by the tabBarController. And each tabBarItem must be alerted about overdue items like any others apps. In my first tableViewController I’ve tried to show overdue items count inside of the tabBarItem’s badgeValue. These values are comes from the fetchedResultsController’s fetchedObjects.count, it well working condition.

```<code>func tabBarBadgeUpdater() {

    for viewController in (self.tabBarController?.viewControllers)! {

        let overdue = self.fetchedResultsController.fetchedObjects?.filter({ (record) -> Bool in
            return (record.date?.compare(Date()) != .orderedDescending)
        })

        print(overdue!.count)

        if viewController.tabBarItem.tag == 1 {

            if overdue!.count != 0 {
                DispatchQueue.main.async(execute: {
                    viewController.tabBarItem.badgeValue = "\(overdue!.count)"
                    viewController.tabBarItem.badgeColor = UIColor.init(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
                    self.tableView.reloadData()
                })
            } else {
                DispatchQueue.main.async(execute: {
                    viewController.tabBarItem.badgeValue = ""
                    viewController.tabBarItem.badgeColor = .clear
                    self.tableView.reloadData()
                })
            }
        }
    }
}
</code>```

But my problem line is deleting them. When I tried to delete last object from the model and it’s still shows value 1.

How to correctly show TabBarItem's badgeValue ?

答:
I found a Swift 5 solution to setting the tabBar item when you want to be able to move your tabBar Items around and it doesn't just mark the badge of a fixed tabBar item position.
Here is my solution that works wherever your UiView is placed in the tabBar:

```<code>// set badge value on your own nav controller

self.navigationController?.tabBarItem.badgeValue = scoreBoxLabelOutlet.text

// Then use a nil value to remove the Badge Item.
self.navigationController?.tabBarItem.badgeValue = nil
</code>```

Where I used an outlet called scoreBoxLabelOutlet.text to collect the information.

Body:
I have a three tableViewController and they’re managed by the tabBarController. And each tabBarItem must be alerted about overdue items like any others apps. In my first tableViewController I’ve tried to show overdue items count inside of the tabBarItem’s badgeValue. These values are comes from the fetchedResultsController’s fetchedObjects.count, it well working condition.

func tabBarBadgeUpdater() {

    for viewController in (self.tabBarController?.viewControllers)! {

        let overdue = self.fetchedResultsController.fetchedObjects?.filter({ (record) -> Bool in
            return (record.date?.compare(Date()) != .orderedDescending)
        })

        print(overdue!.count)

        if viewController.tabBarItem.tag == 1 {

            if overdue!.count != 0 {
                DispatchQueue.main.async(execute: {
                    viewController.tabBarItem.badgeValue = "\(overdue!.count)"
                    viewController.tabBarItem.badgeColor = UIColor.init(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
                    self.tableView.reloadData()
                })
            } else {
                DispatchQueue.main.async(execute: {
                    viewController.tabBarItem.badgeValue = ""
                    viewController.tabBarItem.badgeColor = .clear
                    self.tableView.reloadData()
                })
            }
        }
    }
}

But my problem line is deleting them. When I tried to delete last object from the model and it’s still shows value 1.

How to correctly show TabBarItem's badgeValue ?

Body:
I found a Swift 5 solution to setting the tabBar item when you want to be able to move your tabBar Items around and it doesn't just mark the badge of a fixed tabBar item position.
Here is my solution that works wherever your UiView is placed in the tabBar:

// set badge value on your own nav controller

self.navigationController?.tabBarItem.badgeValue = scoreBoxLabelOutlet.text

// Then use a nil value to remove the Badge Item.
self.navigationController?.tabBarItem.badgeValue = nil

Where I used an outlet called scoreBoxLabelOutlet.text to collect the information.


问:
setting div as a background

I have a div like which has an background, i like to set this div as an transparent background to certain dialog, like a jquery dialog. But the issue here is when the user scrolls the transparent div is also moving. i want this transparent div to be fixed even the scroll bar   moves. How can i achieve this? Thanks.

Sample Code:

doc is an instance of html document. [doc  instanceof HTMLDocument]

```<code><div id=hiox1002  align=center style='display: none; z-index:3;opacity:0.4;\
            filter:alpha(opacity=40);background-image:url(http://funflys.com/images/bg.png);background-repeat:repeat;\
            width: "+doc.defaultView.innerWidth+"px; height: "+doc.defaultView.innerHeight+"px;/></div>
</code>```

I am trying this for an firefox add on

答: Try adding a position:fixed style.

Title: setting div as a background

Body:
I have a div like which has an background, i like to set this div as an transparent background to certain dialog, like a jquery dialog. But the issue here is when the user scrolls the transparent div is also moving. i want this transparent div to be fixed even the scroll bar   moves. How can i achieve this? Thanks.

Sample Code:

doc is an instance of html document. [doc  instanceof HTMLDocument]

I am trying this for an firefox add on

Body: Try adding a position:fixed style.


问:
how to download file in jsp and servlet?
I am working on the jsp project. I have an option to download files or images. but the problem is after downloading the file it seems unsupported file format.how to solve that issue?</p>

答:
First, create a simple link in your jsp page that redirects you to the servlet. instead of jpg, you can put any type of file.

```<code><a href="ServletName?value=filename.jpg">Downlaod</a>
</code>```

here is the servlet code for download any file from your web directory. Don't forget to create "files" folder in your web-pages directory and paste the file.

```<code>try (PrintWriter out = response.getWriter()) {
        //fetch the file name from the url
        String name = request.getParameter("value");
        //get the directory of the file.
        String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
        //set the content type
        response.setContentType("APPLICATION/OCTET-STREAM");
        //force to download dialog
        response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");

        FileInputStream ins = new FileInputStream(path);

        int i;
        while ((i = ins.read()) != -1) {
            out.write(i);
        }
        ins.close();
        out.close();
    }
</code>```

that's all. you can check this Download File in jsp and servlet youtube video for more.

Body:
First, create a simple link in your jsp page that redirects you to the servlet. instead of jpg, you can put any type of file.

<a href="ServletName?value=filename.jpg">Downlaod</a>

here is the servlet code for download any file from your web directory. Don't forget to create "files" folder in your web-pages directory and paste the file.

try (PrintWriter out = response.getWriter()) {
        //fetch the file name from the url
        String name = request.getParameter("value");
        //get the directory of the file.
        String path = getServletContext().getRealPath("/" + "files" + File.separator + name);
        //set the content type
        response.setContentType("APPLICATION/OCTET-STREAM");
        //force to download dialog
        response.setHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");

        FileInputStream ins = new FileInputStream(path);

        int i;
        while ((i = ins.read()) != -1) {
            out.write(i);
        }
        ins.close();
        out.close();
    }

that's all. you can check this Download File in jsp and servlet youtube video for more.


问:
Discord.js serverinfo offline online dnd error

const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};
```

<p>// hey I need help with this could someone tell me what's wrong here is error message =></p>

<p>// Logged in as Zorek!</p>

<pre class="lang-js prettyprint-override"><code>(node:29228) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
    at module.exports.run (C:\Users\xdswe\Desktop\Zero\src\commands\Utilities\Serverinfo.js:23:43)
    at MenuDocsClient.<anonymous> (C:\Users\xdswe\Desktop\Zero\src\Structures\MenuDocsClient.js:38:13)
    at MenuDocsClient.emit (events.js:311:20)
    at MessageCreateAction.handle (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:311:20)
</code>```

答:
Instead of guild.members.filter(), do, for example, message.guild.members.filter()

```<code>const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${message.guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${message.guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${message.guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};
</code>```

Body:
const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};

// hey I need help with this could someone tell me what's wrong here is error message =>

// Logged in as Zorek!

(node:29228) UnhandledPromiseRejectionWarning: ReferenceError: guild is not defined
    at module.exports.run (C:\Users\xdswe\Desktop\Zero\src\commands\Utilities\Serverinfo.js:23:43)
    at MenuDocsClient.<anonymous> (C:\Users\xdswe\Desktop\Zero\src\Structures\MenuDocsClient.js:38:13)
    at MenuDocsClient.emit (events.js:311:20)
    at MessageCreateAction.handle (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
    at WebSocketShard.onPacket (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
    at WebSocketShard.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
    at WebSocket.onMessage (C:\Users\xdswe\Desktop\Zero\node_modules\ws\lib\event-target.js:125:16)
    at WebSocket.emit (events.js:311:20)

Body:
Instead of guild.members.filter(), do, for example, message.guild.members.filter()

const Command = require('../../Structures/Command');
const Discord = require('discord.js');

module.exports = class extends Command {

    constructor(...args) {
        super(...args, {
            aliases: ['si']
        });
    }

    async run(message) {
            let sicon = message.guild.iconURL;
            const embed = new Discord.MessageEmbed()
            .setTitle(`Name Of Server:  ${message.guild}`)
            .setColor(0xFF0000)
            .addField('Name', message.guild.name, true)
            .addField('ID', message.guild.id, true)
            .addField('Owner', message.guild.owner, true)
            .addField('Owner ID', message.guild.owner.id, true)
            .addField('Region', message.guild.region, true)
            .addField('Members', message.guild.memberCount, true)
            .addField("Users Online:", `${message.guild.members.filter(m => m.user.presence.status === "online").size}`)
            .addField("Users DND:", `${message.guild.members.filter(m => m.user.presence.status === "dnd").size}`)
            .addField("Users Offline:", `${message.guild.members.filter(m => m.user.presence.status === "offline").size}`)
            .addField('You Joined', message.member.joinedAt, true)
            .addField('Created At', message.guild.createdAt, true)
            .setThumbnail(sicon);
            message.channel.send(embed);
    }

};


问:
Spring Security Configuration is not applied
I have the below configuration where i need to configure HTTPBasic authentication for /api/v1/** endpoints and i want to configure form authentication for /users/ url pattern. When i run with the below configuration, the configuration for web requests is working correctly but the configuration for API is not working. No security is being applied. Where am I going wrong?

```<code>@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Order(1)
    @Configuration
    public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        public BCryptPasswordEncoder getBCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.
                    antMatcher("/users/**")
                    .csrf()
                        .and()
                    .authorizeRequests()
                    .antMatchers(
                            "/resources/**", "/users/register", "/users/signup", "/users/confirm", "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**")
                    .permitAll()
                    .antMatchers("/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password");

            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .httpBasic();
        }
    }
</code>```

答:
I have put your code to work with this configuration bellow:

```<code>@EnableWebSecurity
public class SecurityConfiguration {

public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/v1/users/**")
           .authorizeRequests().anyRequest()
           .hasRole("USER").and().httpBasic();
    }

}

@Configuration
@Order(2)
public class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().and().authorizeRequests()
                .antMatchers("/resources/**", "/users/register", "/users/signup", "/users/confirm",
                        "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**").permitAll()
        .antMatchers("/users/**").hasRole("USER")
        .and()
        .formLogin().usernameParameter("username").passwordParameter("password");
    }
}

}
</code>```

View docs for Spring Security and sample code here.

Body:
I have the below configuration where i need to configure HTTPBasic authentication for /api/v1/** endpoints and i want to configure form authentication for /users/ url pattern. When i run with the below configuration, the configuration for web requests is working correctly but the configuration for API is not working. No security is being applied. Where am I going wrong?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    @Order(1)
    @Configuration
    public static class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Bean
        public BCryptPasswordEncoder getBCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.
                    antMatcher("/users/**")
                    .csrf()
                        .and()
                    .authorizeRequests()
                    .antMatchers(
                            "/resources/**", "/users/register", "/users/signup", "/users/confirm", "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**")
                    .permitAll()
                    .antMatchers("/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password");

            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/users/**")
                    .hasRole("USER")
                    .anyRequest()
                    .authenticated()
                    .and()
                    .httpBasic();
        }
    }

Body:
I have put your code to work with this configuration bellow:

@EnableWebSecurity
public class SecurityConfiguration {

public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/api/v1/users/**")
           .authorizeRequests().anyRequest()
           .hasRole("USER").and().httpBasic();
    }

}

@Configuration
@Order(2)
public class MVCSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().and().authorizeRequests()
                .antMatchers("/resources/**", "/users/register", "/users/signup", "/users/confirm",
                        "/users/user-action", "/users/reset-password", "/confirm", "/webjars/**").permitAll()
        .antMatchers("/users/**").hasRole("USER")
        .and()
        .formLogin().usernameParameter("username").passwordParameter("password");
    }
}

}

View docs for Spring Security and sample code here.


问:
Counting non-filtered value_counts along with filtered values in pandas
Assuming that I have a dataframe of pastries

```<code>       Pastry      Flavor      Qty
0     Cupcake      Cheese      3
1   Cakeslice   Chocolate      2
2        Tart       Honey      2
3   Croissant   Raspberry      1
</code>```

And I get the value count of a specific flavor per pastry

```<code>df[df['Flavor'] == 'Cheese']['Pastry'].value_counts()
</code>```

```<code>Cupcake    4
Tart       4
Cakeslice  3
Turnover   3
Creampie   2
Danish     2
Bear Claw  2
</code>```

Then to get the percentile of that flavor qty, I could do this

```<code>df[df['Flavor'] == 'Cheese']['Pastry'].value_counts().describe(percentiles=[.75, .85, .95])
</code>```

And I'd get something like this (from full dataframe)

```<code>count    35.00000
mean     1.485714
std      0.853072
min      1.000000
50%      1.000000
75%      2.000000
85%      2.000000
95%      3.300000
max      4.000000
</code>```

Where the total different pastries that are cheese flavored is 35, so the total cheese qty is distributed amongst those 35 pastries. The mean of qty is 1.48, max qty is 4 (cupcake and tart)  etc, etc.

What I want to do is bring that 95th percentile down by counting all other values which are not 'Cheese' in the flavor column, however value_counts() is only counting the ones that are 'Cheese' because I filtered the dataframe. How can I also count the non Cheese rows, so that my percentiles will go down and will represent the distribution of Cheese total in the entire dataframe?

This is an example output:

```<code>Cupcake    4
Tart       4
Cakeslice  3
Turnover   3
Creampie   2
Danish     2
Bear Claw  2
Swiss Roll 1
Baklava    0
Cannoli    0
</code>```

Where the non-cheese flavor pastries are being included with 0 as qty, from there I can just get the percentiles and they will be reduced since there are 0 values now diluting them.

答:
I decided to go and try the long way to try and solve this question and my result gave me the same answer as this question

Here is the long way, in case anyone is curious.

```<code>pastries = {}

for p in df['Pastry'].unique():
  pastries[p] = df[(df['Flavor'] == 'Cheese') & (df['Pastry'] == p)]['Pastry'].count()

newdf = pd.DataFrame.from_dict(pastries.items())

newdf.describe(percentiles=[.75, .85, .95])
</code>```

Body:
Assuming that I have a dataframe of pastries

       Pastry      Flavor      Qty
0     Cupcake      Cheese      3
1   Cakeslice   Chocolate      2
2        Tart       Honey      2
3   Croissant   Raspberry      1

And I get the value count of a specific flavor per pastry

df[df['Flavor'] == 'Cheese']['Pastry'].value_counts()

Cupcake    4
Tart       4
Cakeslice  3
Turnover   3
Creampie   2
Danish     2
Bear Claw  2

Then to get the percentile of that flavor qty, I could do this

df[df['Flavor'] == 'Cheese']['Pastry'].value_counts().describe(percentiles=[.75, .85, .95])

And I'd get something like this (from full dataframe)

count    35.00000
mean     1.485714
std      0.853072
min      1.000000
50%      1.000000
75%      2.000000
85%      2.000000
95%      3.300000
max      4.000000

Where the total different pastries that are cheese flavored is 35, so the total cheese qty is distributed amongst those 35 pastries. The mean of qty is 1.48, max qty is 4 (cupcake and tart)  etc, etc.

What I want to do is bring that 95th percentile down by counting all other values which are not 'Cheese' in the flavor column, however value_counts() is only counting the ones that are 'Cheese' because I filtered the dataframe. How can I also count the non Cheese rows, so that my percentiles will go down and will represent the distribution of Cheese total in the entire dataframe?

This is an example output:

Cupcake    4
Tart       4
Cakeslice  3
Turnover   3
Creampie   2
Danish     2
Bear Claw  2
Swiss Roll 1
Baklava    0
Cannoli    0

Where the non-cheese flavor pastries are being included with 0 as qty, from there I can just get the percentiles and they will be reduced since there are 0 values now diluting them.

Body:
I decided to go and try the long way to try and solve this question and my result gave me the same answer as this question

Here is the long way, in case anyone is curious.

pastries = {}

for p in df['Pastry'].unique():
  pastries[p] = df[(df['Flavor'] == 'Cheese') & (df['Pastry'] == p)]['Pastry'].count()

newdf = pd.DataFrame.from_dict(pastries.items())

newdf.describe(percentiles=[.75, .85, .95])


问:
What modules does mod_rewrite depend on?
proxy? proxy_http? what else?

When I include all of the available modules, rewrite works, but I'm having a hard time figuring out which ones are actually making the difference.

ANSWER: vhost_alias was one. seems to work now.

答: mod_rewrite in itself does not have any direct dependencies. There are a few directives that  can delegate work to other modules (like RewriteRule .... [P], which uses mod_proxy to execute the request) thus requiring additional modules.</p>

OwnerDisplayName: ThomasGHenry

OwnerDisplayName: jjungnickel

ContentLicense: CC BY-SA 2.5


问:
How to replace double quotes in derived column transformation?
I have flat file. I am loading data from flat file to source table using ssis.And one of the column has following values:

```<code><Somecol1 =""1"" col1values= ""223,567,890,653"">
</code>```

I want following column output:

```<code><Somecol1 ="1" col1values= "223,567,890,653">
</code>```

I have tried to replace in derived column.

```<code>REPLACE( COLA, "\"","\")
</code>```

but this doesnt work.

答: This may not work if your other columns don't have this same issue, but if this is the only text column you are importing or they are all like this, you could change your text identifier to be two double quotes instead of one.  Then SSIS would bring it out of the flat file correctly and you wouldn't have to deal with trying to clean it up later.</p>

Body:
I have flat file. I am loading data from flat file to source table using ssis.And one of the column has following values:

<Somecol1 =""1"" col1values= ""223,567,890,653"">

I want following column output:

<Somecol1 ="1" col1values= "223,567,890,653">

I have tried to replace in derived column.

REPLACE( COLA, "\"","\")

but this doesnt work.


问:
Using C++ objects from C
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

```<code>class MyData {
  ...
};
</code>```

From C:

```<code>struct MyData {
  ...
};
</code>```

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

答:
Write a class that is legal in both C and C++:

```<code>struct MyData {
    int member;
};
</code>```

You can use this class/struct definition in both languages and pass instances of it back and forth.

If class has C++ features such as member functions, bases, non-trivial members etc. then you can use it in C only through an opaque pointer, which won't allow you to access members.

Title: Using C++ objects from C

Body:
I would like to use C/C++ mixed code. I also need access to C++ object member variables from C code.

It works (at least in gcc), that I pass pointer to the object and handle it as a struct.

From C++:

class MyData {
  ...
};

From C:

struct MyData {
  ...
};

(Of course, I do not duplicate code in the final header file)

1, I am not sure that this would work using any of the compilers. Is there any reasons why I should not rely on this?

2, If MyData class has virtual member functions, this would not work, but a pointer to the first member variable could solve the problem. Is this safe, or may I get into trouble with this?

Body:
Write a class that is legal in both C and C++:

struct MyData {
    int member;
};

You can use this class/struct definition in both languages and pass instances of it back and forth.

If class has C++ features such as member functions, bases, non-trivial members etc. then you can use it in C only through an opaque pointer, which won't allow you to access members.


问:
How to get last index in a map with some null items
I got a Map(int,List<String>) and some of the lists inside are null for example:

{1 = [example1, 2000, May 22, 2020] , 2 = [example2, 120, May 30, 2020] ,  4 = [example3, 120, May 30, 2020]}

so in my example the list in index 3 is null.

so I want do get the highest index in the map in my example it'll be 4.

答:
You can use keySet() to get all key and use Collections.max to get max index

```<code>int maxSet = Collections.max(map.keySet());
</code>```

Body:
You can use keySet() to get all key and use Collections.max to get max index

int maxSet = Collections.max(map.keySet());


问:
Formatting a date is giving me a different one from the passed one
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="date" name="start" class="form-control" id="start" required autofocus>
<label for="start">Start Date</label></code>```

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);
```

<p>This is how I format the date to looks like <code>yyyy/mm/dd</code> in this part is where I get another wrong date from the passed one:</p>

<pre class="lang-js prettyprint-override"><code>firstday = firstday.toISOString().slice(0,10);
</code>```

答: Timezones are tricky! Any given timestamp could look like a different date  depending on your timezone. ISO strings ignore timezone. So for starters, you could just do new Date().toString().

Body:
I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;

<input type="date" name="start" class="form-control" id="start" required autofocus>
Start Date

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);

This is how I format the date to looks like yyyy/mm/dd in this part is where I get another wrong date from the passed one:

firstday = firstday.toISOString().slice(0,10);


问:
how can i ignore error in python properly?
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

```<code>a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)
</code>```

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

```<code>try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None
</code>```

looks ridiculous, doesnt it?

how can i handle it gracefully?

答:
Would breaking this up into two steps solve the problem?

Something like:

```<code>a = soup.find(something)
if a is not None:
    a = a.find(something)
</code>```

If not, I agree with the AttributeError suggestion.

You may find this question about exception handling interesting/helpful.

Body:
I'm trying to web scraping.

using BeautifulSoup, i'm parsing several objects and confronted with a problem.

The problem is, i can't predict where the error occur using "find" method.

it looks like

a = soup.find(something).find(something)
b = soup.find(something)
...
f = soup.find(something).find(something)

among a,b,c,d,e,f, error can happen anywhere and their code should not be revised.

the variable 'b' is not matter because it would be None, which is ok.

but variable 'a' or 'f' is problem, because it would end the script.

i know there is "try - exception" grammar but that's not what i want.
of course it can be written like this:

try :
 a = soup.find(something).find(something)
except Exception:
 a = None
...
try :
 f = soup.find(something).find(something)
except Exception:
 f = None

looks ridiculous, doesnt it?

how can i handle it gracefully?

Body:
Would breaking this up into two steps solve the problem?

Something like:

a = soup.find(something)
if a is not None:
    a = a.find(something)

If not, I agree with the AttributeError suggestion.

You may find this question about exception handling interesting/helpful.


答:
That happens because firstday.toISOString() returns date in UTC timezone so if you're located somewhere else you can expect the shifts in dates.

Unfortunately there is no go-to solution if you're not using something like moment.js (and it does not seem to be appropriate for such a simple task). I'd recommend you something like:

```<code>const [day, month, year] = firstday.toLocaleDateString('en-US').split('.');
firstday = [year, month, day].join('/')
</code>```

Title: Formatting a date is giving me a different one from the passed one

Body:
That happens because firstday.toISOString() returns date in UTC timezone so if you're located somewhere else you can expect the shifts in dates.

Unfortunately there is no go-to solution if you're not using something like moment.js (and it does not seem to be appropriate for such a simple task). I'd recommend you something like:

const [day, month, year] = firstday.toLocaleDateString('en-US').split('.');
firstday = [year, month, day].join('/')


问:
a solution for counting sequential events in pandas
I have the following example data, and I'd like to count action(page_number=2) and action(page_number=3) one time for each try if it is available. I have attached the result I mean. I want to do using pandas dataframe but I don't know how it is.

```<code>import pandas as pd
df = pd.DataFrame({'action': ['enter', 'next', 'prev', 'error', 'exit'],
                   'page_number': [0, 1, 2, 3]})
</code>```

For example, we have this data

```<code>action     page_number
enter
next        1
prev        2
next        1
next        2
exit        3
enter
next        1
error
next        1
error
error
error
next        2
prev        3
prev        2
next        1
prev        2
prev        1
exit        0
enter
exit
</code>```

The result I want to achieve is (for session 1):

```<code>action
enter                     1
next(page number = 1)     1
next(page number = 2)     1
prev(page number = 2)     1
exit                      1
</code>```

next(page number = 1)  appears twice in the first session but I want to count it just once. Even if it occurs 3 times in the first session but I want to count it just once. I'd like to have this rule in all the sessions for all the actions. Each action counts just once in each session.

Thank you in advance for any guidance

答:
First we create a new column 'extended_action' and then groupby this new column:

```<code>df['extended_action'] = (df.action + ' (page number = ' + df.page_number.astype(str) + ')').where(df.action.isin(('next', 'prev')), df.action)
df.groupby('extended_action').extended_action.count()
</code>```

Result (for the whole example dataframe):

```<code>extended_action
enter                     3
error                     4
exit                      3
next (page number = 1)    5
next (page number = 2)    2
prev (page number = 1)    1
prev (page number = 2)    3
prev (page number = 3)    1
</code>```

You can rename the columns after the groupby to get the output in the requested format:

```<code>df.groupby('extended_action',as_index=False).action.count().rename(columns={'extended_action': 'action', 'action': 'count'})
</code>```

Result:

```<code>                   action  count
0                   enter      3
1                   error      4
2                    exit      3
3  next (page number = 1)      5
4  next (page number = 2)      2
5  prev (page number = 1)      1
6  prev (page number = 2)      3
7  prev (page number = 3)      1
</code>```

UPDATE as per comment below:

If you need the count per session (a session lasts from enter to exit) then you need to insert a session number column and group by session and extended_action:

```<code>df['session'] = df.action.eq('enter').cumsum()
df.groupby(['session','extended_action']).extended_action.count()
</code>```

Result:

```<code>session  extended_action
1        enter                     1
         exit                      1
         next (page number = 1)    2
         next (page number = 2)    1
         prev (page number = 2)    1
2        enter                     1
         error                     4
         exit                      1
         next (page number = 1)    3
         next (page number = 2)    1
         prev (page number = 1)    1
         prev (page number = 2)    2
         prev (page number = 3)    1
3        enter                     1
         exit                      1
</code>```

UPDATE 2 as per changed question and comment below:
If you want to count each event only once you just need to drop_duplicates before the grouping:

```<code>df.drop_duplicates().groupby(['session','extended_action']).extended_action.count()
</code>```

Result:

```<code>session  extended_action
1        enter                     1
         exit                      1
         next (page number = 1)    1
         next (page number = 2)    1
         prev (page number = 2)    1
2        enter                     1
         error                     1
         exit                      1
         next (page number = 1)    1
         next (page number = 2)    1
         prev (page number = 1)    1
         prev (page number = 2)    1
         prev (page number = 3)    1
3        enter                     1
         exit                      1
</code>```

Body:
I have the following example data, and I'd like to count action(page_number=2) and action(page_number=3) one time for each try if it is available. I have attached the result I mean. I want to do using pandas dataframe but I don't know how it is.

import pandas as pd
df = pd.DataFrame({'action': ['enter', 'next', 'prev', 'error', 'exit'],
                   'page_number': [0, 1, 2, 3]})

For example, we have this data

action     page_number
enter
next        1
prev        2
next        1
next        2
exit        3
enter
next        1
error
next        1
error
error
error
next        2
prev        3
prev        2
next        1
prev        2
prev        1
exit        0
enter
exit

The result I want to achieve is (for session 1):

action
enter                     1
next(page number = 1)     1
next(page number = 2)     1
prev(page number = 2)     1
exit                      1

next(page number = 1)  appears twice in the first session but I want to count it just once. Even if it occurs 3 times in the first session but I want to count it just once. I'd like to have this rule in all the sessions for all the actions. Each action counts just once in each session.

Thank you in advance for any guidance

Body:
First we create a new column 'extended_action' and then groupby this new column:

df['extended_action'] = (df.action + ' (page number = ' + df.page_number.astype(str) + ')').where(df.action.isin(('next', 'prev')), df.action)
df.groupby('extended_action').extended_action.count()

Result (for the whole example dataframe):

extended_action
enter                     3
error                     4
exit                      3
next (page number = 1)    5
next (page number = 2)    2
prev (page number = 1)    1
prev (page number = 2)    3
prev (page number = 3)    1

You can rename the columns after the groupby to get the output in the requested format:

df.groupby('extended_action',as_index=False).action.count().rename(columns={'extended_action': 'action', 'action': 'count'})

Result:

                   action  count
0                   enter      3
1                   error      4
2                    exit      3
3  next (page number = 1)      5
4  next (page number = 2)      2
5  prev (page number = 1)      1
6  prev (page number = 2)      3
7  prev (page number = 3)      1

UPDATE as per comment below:

If you need the count per session (a session lasts from enter to exit) then you need to insert a session number column and group by session and extended_action:

df['session'] = df.action.eq('enter').cumsum()
df.groupby(['session','extended_action']).extended_action.count()

Result:

session  extended_action
1        enter                     1
         exit                      1
         next (page number = 1)    2
         next (page number = 2)    1
         prev (page number = 2)    1
2        enter                     1
         error                     4
         exit                      1
         next (page number = 1)    3
         next (page number = 2)    1
         prev (page number = 1)    1
         prev (page number = 2)    2
         prev (page number = 3)    1
3        enter                     1
         exit                      1

UPDATE 2 as per changed question and comment below:
If you want to count each event only once you just need to drop_duplicates before the grouping:

df.drop_duplicates().groupby(['session','extended_action']).extended_action.count()

Result:

session  extended_action
1        enter                     1
         exit                      1
         next (page number = 1)    1
         next (page number = 2)    1
         prev (page number = 2)    1
2        enter                     1
         error                     1
         exit                      1
         next (page number = 1)    1
         next (page number = 2)    1
         prev (page number = 1)    1
         prev (page number = 2)    1
         prev (page number = 3)    1
3        enter                     1
         exit                      1