问:
C# Winform application crash on SqlConnection
I have a Winform program that has a lot of SqlConnection function that interacts with a local MDF database.

This is how I create the connection string:

```<code>String dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Bot\DB\BotDB.mdf";
String con = String.Format("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;", dbPath);
return con;
</code>```

And this is one of many calls i made to the Database:

```<code>public bool InsertNewUserToTable(String username)
{
    using (SqlConnection con = new SqlConnection(DataBase.GetConString()))
    {
        con.Open();

        String query = @"INSERT INTO dbo.Users(username) VALUES(@username);";

        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@username", username);

            int count = cmd.ExecuteNonQuery();

            con.Close();

            return (count == 0) ? false : true;
        }
    }
}
</code>```

I have more methods like this one that deletes, update, insert data from the Database.

The program working with multithread that access the database in this way.

The problem is that sometimes I get a crash error(on publish mode):

```<code>Problem signature:
  Problem Event Name:   CLR20r3
  Problem Signature 01: Bot.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 5cbce361
  Problem Signature 04: System.Data
  Problem Signature 05: 4.7.2623.0
  Problem Signature 06: 5a1f67d8
  Problem Signature 07: 1a55
  Problem Signature 08: 5e
  Problem Signature 09: System.Data.SqlClient.Sql
  OS Version:   6.3.9600.2.0.0.272.7
  Locale ID:    1033
  Additional Information 1: 4e4b
  Additional Information 2: 4e4be395a3a959f2a72f71ab9c9204ab
  Additional Information 3: 783e
  Additional Information 4: 783ea04fb900812a4241ad9aeb1b45b6

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt
</code>```

I tried to find a way to find the specific Exception with this information:
https://stackoverflow.com/a/4053325/679099

But I wasn't able to find any specific thing that crash my application.

Any idea what can be the issue? Something else that I'm missing?

答:
Try to define a private SqlConnection and put this code under InitializeComponent();

```<code>con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
con.Open();
</code>```

This connection works for multiple connections opened, because you have MARS=True;

Then for SqlCommand, you need to make only like this:

```<code>SqlCommand cmd = new SqlCommand("query", con);
</code>```

Final code of SqlConnection must look like this:

```<code>private SqlConnection con;
public Form1()
{
    InitializeComponent();
    con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
    con.Open();
}
</code>```

Body:
I have a Winform program that has a lot of SqlConnection function that interacts with a local MDF database.

This is how I create the connection string:

String dbPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Bot\DB\BotDB.mdf";
String con = String.Format("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;", dbPath);
return con;

And this is one of many calls i made to the Database:

public bool InsertNewUserToTable(String username)
{
    using (SqlConnection con = new SqlConnection(DataBase.GetConString()))
    {
        con.Open();

        String query = @"INSERT INTO dbo.Users(username) VALUES(@username);";

        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@username", username);

            int count = cmd.ExecuteNonQuery();

            con.Close();

            return (count == 0) ? false : true;
        }
    }
}

I have more methods like this one that deletes, update, insert data from the Database.

The program working with multithread that access the database in this way.

The problem is that sometimes I get a crash error(on publish mode):

Problem signature:
  Problem Event Name:   CLR20r3
  Problem Signature 01: Bot.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 5cbce361
  Problem Signature 04: System.Data
  Problem Signature 05: 4.7.2623.0
  Problem Signature 06: 5a1f67d8
  Problem Signature 07: 1a55
  Problem Signature 08: 5e
  Problem Signature 09: System.Data.SqlClient.Sql
  OS Version:   6.3.9600.2.0.0.272.7
  Locale ID:    1033
  Additional Information 1: 4e4b
  Additional Information 2: 4e4be395a3a959f2a72f71ab9c9204ab
  Additional Information 3: 783e
  Additional Information 4: 783ea04fb900812a4241ad9aeb1b45b6

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=280262

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

I tried to find a way to find the specific Exception with this information:
https://stackoverflow.com/a/4053325/679099

But I wasn't able to find any specific thing that crash my application.

Any idea what can be the issue? Something else that I'm missing?

Body:
Try to define a private SqlConnection and put this code under InitializeComponent();

con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
con.Open();

This connection works for multiple connections opened, because you have MARS=True;

Then for SqlCommand, you need to make only like this:

SqlCommand cmd = new SqlCommand("query", con);

Final code of SqlConnection must look like this:

private SqlConnection con;
public Form1()
{
    InitializeComponent();
    con = new SqlConnection(@"Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"{0}\";Integrated Security=True;Connection Timeout=10;User Instance=True;MultipleActiveResultSets=True;");
    con.Open();
}


来源: stackexchange

问:
ViewPager2 default position
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

```<code>viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)
</code>```

答:
mViewPager.setCurrentItem(1, true);   ---> this is sufficient as you written above

That should work,
in doubt, just check your position:

```<code>        @Override
        public void onPageSelected(int i) {
            if (LOG_DEBUG) Log.v(TAG, " ++++++++    onPageSelected:  " + i);
            mViewPager.setCurrentItem(i);
            //TODO You can use this position: to write other dependent logic

        }
</code>```

and also check

getItem(int position) in PagerAdapter

or else paste your code.

ContentLicense: CC BY-SA 4.0

Title: ViewPager2 default position

Body:
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)

Body:
mViewPager.setCurrentItem(1, true);   ---> this is sufficient as you written above

That should work,
in doubt, just check your position:

        @Override
        public void onPageSelected(int i) {
            if (LOG_DEBUG) Log.v(TAG, " ++++++++    onPageSelected:  " + i);
            mViewPager.setCurrentItem(i);
            //TODO You can use this position: to write other dependent logic

        }

and also check

getItem(int position) in PagerAdapter

or else paste your code.


问:
missing requirement osgi.wiring.package when starting bundle
thanks in advance for the help!
I'm following an tutorial, and when I try to start the bundle I installed in karaf it wont start... the log is that:

20:12:18.713 ERROR [Karaf local console user karaf] Exception caught while executing command
org.apache.karaf.shell.support.MultiException: Error executing command on bundles:
        Error starting bundle 157: Unable to resolve db-examplejpa [157](R 157.0): missing requirement [db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0))) Unresolved requirements: [[db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0)))]
        at org.apache.karaf.shell.support.MultiException.throwIf(MultiException.java:61) ~[?:?]
        at org.apache.karaf.bundle.command.BundlesCommand.doExecute(BundlesCommand.java:70) ~[?:?]
        at org.apache.karaf.bundle.command.BundlesCommand.execute(BundlesCommand.java:55) ~[?:?]
        at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:84) ~[?:?]
        at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:68) ~[?:?]
        at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:86) ~[?:?]
        at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:599) ~[?:?]
        at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:526) ~[?:?]
        at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:415) ~[?:?]
        at org.apache.felix.gogo.runtime.Pipe.doCall(Pipe.java:416) ~[?:?]
        at org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:229) ~[?:?]
        at org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:59) ~[?:?]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:?]
        at java.lang.Thread.run(Thread.java:748) [?:?]
        Suppressed: java.lang.Exception: Error starting bundle 157: Unable to resolve db-examplejpa [157](R 157.0): missing requirement [db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0))) Unresolved requirements: [[db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0)))]
                at org.apache.karaf.bundle.command.BundlesCommand.doExecute(BundlesCommand.java:67) ~[?:?]
                at org.apache.karaf.bundle.command.BundlesCommand.execute(BundlesCommand.java:55) ~[?:?]
                at org.apache.karaf.shell.impl.action.command.ActionCommand.execute(ActionCommand.java:84) ~[?:?]
                at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:68) ~[?:?]
                at org.apache.karaf.shell.impl.console.osgi.secured.SecuredCommand.execute(SecuredCommand.java:86) ~[?:?]
                at org.apache.felix.gogo.runtime.Closure.executeCmd(Closure.java:599) ~[?:?]
                at org.apache.felix.gogo.runtime.Closure.executeStatement(Closure.java:526) ~[?:?]
                at org.apache.felix.gogo.runtime.Closure.execute(Closure.java:415) ~[?:?]
                at org.apache.felix.gogo.runtime.Pipe.doCall(Pipe.java:416) ~[?:?]
                at org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:229) ~[?:?]
                at org.apache.felix.gogo.runtime.Pipe.call(Pipe.java:59) ~[?:?]
                at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[?:?]
                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:?]
                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:?]
                at java.lang.Thread.run(Thread.java:748) [?:?]
        Caused by: org.osgi.framework.BundleException: Unable to resolve db-examplejpa [157](R 157.0): missing requirement [db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0))) Unresolved requirements: [[db-examplejpa [157](R 157.0)] osgi.wiring.package; (&(osgi.wiring.package=org.apache.felix.service.command)(version>=0.6.0)(!(version>=1.0.0)))]
                at org.apache.felix.framework.Felix.resolveBundleRevision(Felix.java:4149) ~[?:?]
                at org.apache.felix.framework.Felix.startBundle(Felix.java:2119) ~[?:?]
                at org.apache.felix.framework.BundleImpl.start(BundleImpl.java:998) ~[?:?]
                at org.apache.karaf.bundle.command.Start.executeOnBundle(Start.java:38) ~[?:?]
                at org.apache.karaf.bundle.command.BundlesCommand.doExecute(BundlesCommand.java:65) ~[?:?]
                ... 14 more

the tutorial is this one if you are interested:http://liquid-reality.de/Karaf-Tutorial/06/

I thought it was the versiong problem, but I tried to change the version in the pom but it didnt work.
i have seem some answers here but no luck...

edit:Im not using bndtool btw... is it required? the tut doesnt say anything about that

thank you!

答:
The example did not match the current versions of Apache Karaf and JPA anymore.

The issue you see means that we use a package "org.apache.felix.service.command" but there is no bundle that exports this package. In this case the reason is that the annotations from this package are deprecated and are not supported by the current karaf version anymore.

I have adapted the example for current Apache Karaf and also converted to use the lambda based JPA style as well as declarative services instead of blueprint. This makes the example quite a bit simpler.

I hope this helps.


问:
Traversing an array to find the second largest element in linear time
Is there a way in linear time by which we can find which is the second largest element of an array ?
Array elements can be positive, negative or zero.
Elements can be repetitive.
No STLs allowed.
Python can be used.

Solution : Sort the array and take the second element but Sorting not allowed

Modification : By definition second largest element will be the one which is numerically smaller. Like if we have

Arr = {5,5,4,3,1}
Then second largest is 4

Addition
Lets say if i want to generalize the question to kth largest and complexity less than linear like nlogn, what can be the solution.

答:
Pseudo code:

```<code>int max[2] = { array[0], array[1] }

if(max[1] < max[0]) swap them

for (int i = 2; i < array.length(); i++) {
  if(array[i] >= max[0]) max[1] = max[0]; max[0] = array[i]
  else if(array[i] >= max[1]) max[1] = array[i];
}
</code>```

Now, max array contains the max 2 elements.

ContentLicense: CC BY-SA 3.0

Body:
Pseudo code:

int max[2] = { array[0], array[1] }

if(max[1] < max[0]) swap them

for (int i = 2; i < array.length(); i++) {
  if(array[i] >= max[0]) max[1] = max[0]; max[0] = array[i]
  else if(array[i] >= max[1]) max[1] = array[i];
}

Now, max array contains the max 2 elements.


问:
djnago unittest: clien.get error 401 even if I send token
I try to create a unittest for method logout, I have this for this purpose:

```<code>    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)
</code>```

but in my logout controller I have this:

```<code>permission_classes = (IsAuthenticated,)
</code>```

thus I changed my above code to this:

```<code>    response = self.client.post('/api/v1/login', data={'username': 'testuser', 'password': '12345678'})
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.json()['access_token'])
    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)
</code>```

but when I run my test I get 401 as result

```<code>      self.assertEquals(response.status_code, 200)
      AssertionError: 401 != 200
</code>```

I am not sure how can I pass token to my request

答:
tldr, for login use https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

Why ?

unittest as the name suggests should test only a single unit at a time.

Here we're testing two things, even though not explicitly but implicitly we're.

The login logic : We're passing username and password and taking access_token from response [even though we're not asserting here but this will affect next block]

The logout logic : We're using access_token from previous blocking and testing logout functionality based on that.

I strongly think that we should testing only single component at a time in unit test else call it integration test.

For our current scenario we can write two test cases:

Test login logic : Pass username and password and assert correct access_token is returned.

Test the logout logic : Mock the login logic and only test logout logic.

For mocking login we can use something like this https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication

Body:
I try to create a unittest for method logout, I have this for this purpose:

    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)

but in my logout controller I have this:

permission_classes = (IsAuthenticated,)

thus I changed my above code to this:

    response = self.client.post('/api/v1/login', data={'username': 'testuser', 'password': '12345678'})
    client = APIClient()
    client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.json()['access_token'])
    response = client.get('/api/v1/logout')
    self.assertEquals(response.status_code, 200)

but when I run my test I get 401 as result

      self.assertEquals(response.status_code, 200)
      AssertionError: 401 != 200

I am not sure how can I pass token to my request


问:
Why does Opera resize email input fields?
Here is my code: jsFiddle.

I've tested this in the latest versions of Chrome, Opera, FF, and Safari. All seems to appear fine except Opera. It seems as if Opera resizes the email input field because when I change it to text, it works out just fine. Is there a fix for this?

EDIT: Using Opera v11.01 on Mac OS X 10.6.7

答: I'm not aware of anything that says that the default style for an email input should have the same width as the default style for a text input, and you're not explicitly asking for anything other than the browser's default style.</p>


问:
Trying to display any number that is entered into a url, using Django 1.1
I'm currently learning regex patterns, using DJango 1.1. More specifically, I am trying to display whatever number is entered into the url using the '\d+' pattern. I'm brand new to DJango, so I hope that description wasn't too vague. Any help would be greatly appreciated.

My urls.py url pattern is:

url(r'^(?P<number>\d+)$', views.show)
```

<p>My <strong>views.py</strong> method is: </p>

<pre class="lang-py prettyprint-override"><code>def show(request, number):
    return HttpResponse("placeholder to display blog number: {number}")
</code>```

I don't quite understand what i'm missing.

If I enter the number 20 into my url: localhost:0000/20, I'm expecting to see an output of:

placeholder to display number: 20
```

<p>But instead, I get an output of:</p>

<pre class="lang-py prettyprint-override"><code>placeholder to display number: {number}
</code>```

答:
You forgot to format the response. It should be like,

return HttpResponse(f"placeholder to display blog number: {number}")

In python f"strings" are used for integrating a value into a string

Body:
I'm currently learning regex patterns, using DJango 1.1. More specifically, I am trying to display whatever number is entered into the url using the '\d+' pattern. I'm brand new to DJango, so I hope that description wasn't too vague. Any help would be greatly appreciated.

My urls.py url pattern is:

url(r'^(?P<number>\d+)$', views.show)

My views.py method is:

def show(request, number):
    return HttpResponse("placeholder to display blog number: {number}")

I don't quite understand what i'm missing.

If I enter the number 20 into my url: localhost:0000/20, I'm expecting to see an output of:

placeholder to display number: 20

But instead, I get an output of:

placeholder to display number: {number}


问:
Is there a way to search for an edx course using their API?
I have an edX client ID and secret ID, and I'm able to get the list of all edX online courses, but I want to be able to search through all of the edX courses with a query string like "robotics". (Unlike this question, I already understand how to get the list of courses, so this is not a duplicate question...) I tried

```<code>import requests

# I also tried with search_query instead of search
edx_course_search_response = requests.get('https://api.edx.org/catalog/v1/catalogs/'+edx_course_catalog_id+'/courses/'+"?search=robotics", headers=headers)
</code>```

I know the catalog id and headers information is correct because I can get the list of edX courses. Unfortunately, this does not work and instead returns the first 20 online courses in edX's database as usual.

If I can't, I think I'm going to use whoosh.

答:
I don't think so.

query is a response value from this endpoint:  GET /catalog/v1/catalogs/{id}/. The endpoint for retrieving info about a specific catalog. It is not a user passed parameter. The user parameter is catalog id.

You might use this endpoint: /catalog/v1/catalogs/{id}/courses/

That endpoint, as mentioned in comments has an answer covering pagination here. You could then filter the returned dataset with python according to your query term. The results array in response values from that endpoint has fields such as short description/long description/title which might be useful to target.

Body:
I have an edX client ID and secret ID, and I'm able to get the list of all edX online courses, but I want to be able to search through all of the edX courses with a query string like "robotics". (Unlike this question, I already understand how to get the list of courses, so this is not a duplicate question...) I tried

import requests

# I also tried with search_query instead of search
edx_course_search_response = requests.get('https://api.edx.org/catalog/v1/catalogs/'+edx_course_catalog_id+'/courses/'+"?search=robotics", headers=headers)

I know the catalog id and headers information is correct because I can get the list of edX courses. Unfortunately, this does not work and instead returns the first 20 online courses in edX's database as usual.

If I can't, I think I'm going to use whoosh.


问:
Way to understand this code. How is it working?
I was exploring scopes in javascript and came to know this problem. I don't understand how this problem is working.

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())```

My question is this how does javascript compiler decide to return function not variable. Any reference or explanation are welcome.

答:
When we run a code there are two phase of it first is creation phase in this phase the syntax parser will read the code and hoist the function and variables, and second phase is execution phase in which the values are assigned to hoisted variables,

A point to note here is function are stored in memory during creation phase as it is where as the variables are hoisted but values
  are not initialized ( which will be assigned during execution phase )

Compiler will treat your code like this after hoisting

function checkType() {
  var foo = function() {}; //hoisted function
  return foo;
  foo = 10;
  foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())```
</div>
</div>
</p>

<p>If you define your function as variable than it will be hoisted only but will not be initialized with value, you can see the below example</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function checkType() {
  return foo;
  foo = 10;

  var foo = function foo() {};
  var foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())</code>```

Body:
I was exploring scopes in javascript and came to know this problem. I don't understand how this problem is working.

function checkType() {
  return foo;
  foo = 10;

  function foo() {};
  var foo = 11;
};

console.log(typeof checkType())

My question is this how does javascript compiler decide to return function not variable. Any reference or explanation are welcome.

Body:
When we run a code there are two phase of it first is creation phase in this phase the syntax parser will read the code and hoist the function and variables, and second phase is execution phase in which the values are assigned to hoisted variables,

A point to note here is function are stored in memory during creation phase as it is where as the variables are hoisted but values
  are not initialized ( which will be assigned during execution phase )

Compiler will treat your code like this after hoisting

function checkType() {
  var foo = function() {}; //hoisted function
  return foo;
  foo = 10;
  foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())

If you define your function as variable than it will be hoisted only but will not be initialized with value, you can see the below example

function checkType() {
  return foo;
  foo = 10;

  var foo = function foo() {};
  var foo = 11;
};

console.log(typeof checkType(), '\nRturned value from function  --->', checkType())


问:
Mongo $lookup $pipeline with several $expr parameters not returning correct data in $lookup results
I have two mongo collections one containing appointment reminders and the other containing notifications. I'm attempting to return results with all archive: false reminders in a given branchId / clinic_id and include their acknowledged: false notifications. Also, I want to make sure the appointments show up in the results regardless if they have notifications or not.

I need to 'join' the collections by branchId aka clinic_id and then create an array of any unacknowledged notifications for each resulting appointment reminder.

I'm returning correct appointments, but the notif array is not getting filtered by matching patientId / patient_id. Each reminder seems to contain the exact same notif array. Other than this everything else seems to be correct. So, my question is how can I ensure the notif array only contains a patientId that matches the patient_id value of the reminder?

Truncated Appointment Reminder Schema:

```<code>      {
      time: {
        type: Date,
        required: true
      },
  patient_id: {
    type: String,
    required: true
  },
      status: {
        type: String,
        default: 'unconfirmed'
      },
      archive: {
        type: Boolean,
        default: false
      },
      branch: [
    // Incorrectly setup as an array rather than an object.
    // Can $unwind as there is only ever one item in the array
        {
          name: {
            type: String,
            required: true
          },
          clinic_id: { // aka branchId
            type: String,
            required: true
          }
        }
      ]
    }
</code>```

Notification Schema:

```<code>{
  branchId: { type: String, required: true }, // aka clinic_id
  patientId: { type: String, required: true },
  acknowledged: { type: Boolean, default: false },
  date: { type: Date, default: Date.now }
}
</code>```

Aggregation Query:

```<code>[
  { $match: { 'branch.0.clinic_id': '1', archive: false } },
  { $unwind: '$branch' },
  {
    $lookup: {
      from: 'notifications',
      let: { clinic_id: '1', patient_id: '$patientId' }, //<-- issue with patient_id?
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
               { $eq: ["$patientId", "$$patientId"] }, <-- errors $$patientId unknown value. $$patient_id returns 0 results.
                { $eq: ['$branchId', '$$clinic_id'] },
                { $eq: ['$acknowledged', false] }
              ]
            }
          }
        }
      ],
      as: 'notif'
    }
  }
]
</code>```

Example Output with comments on desired output and incorrect output I've experienced:

```<code>  {
  patient_id: '1',
  time: '2019-05-29T11:00:00.000Z',
  status: 'unconfirmed',
  archive: false,
  branch: [
    {
      name: 'Example location',
      clinic_id: '100',
    }
  ],
  notif: [
  {
    // This is correct
    branchId: '100', // branchId matches clinic_id
    patientId: '1',  // patientId matches contacts patient_id
    acknowledged: false, // notification is unacknowledged
    date: '2019-05-18T16:18:05.480Z'
  },
  {
   // This is not correct
    branchId: '100',
    patientId: '2', // PatientId does not match patient_id of reminder
    acknowledged: false,
    date: '2019-05-20T16:18:05.480Z'
  }
  ]
}
</code>```

答:
First you do have to use $$patient_id, thats the correct syntax for using a lookup variable.

The reason why your getting 0 results with the correct syntax is
(i'm assuming as you didnt share the full schema) type different.

Notice that is patientId in your notification schema is defined:

patientId: { type: String, required: true },
which is typed String.

From the "desired" output schema you shared at the end:

{
  patientId: 1,
   ...
}

It looks like your patientId is defined as a Number, hence the reason don't get a match between the documents.

Body:
I have two mongo collections one containing appointment reminders and the other containing notifications. I'm attempting to return results with all archive: false reminders in a given branchId / clinic_id and include their acknowledged: false notifications. Also, I want to make sure the appointments show up in the results regardless if they have notifications or not.

I need to 'join' the collections by branchId aka clinic_id and then create an array of any unacknowledged notifications for each resulting appointment reminder.

I'm returning correct appointments, but the notif array is not getting filtered by matching patientId / patient_id. Each reminder seems to contain the exact same notif array. Other than this everything else seems to be correct. So, my question is how can I ensure the notif array only contains a patientId that matches the patient_id value of the reminder?

Truncated Appointment Reminder Schema:

      {
      time: {
        type: Date,
        required: true
      },
  patient_id: {
    type: String,
    required: true
  },
      status: {
        type: String,
        default: 'unconfirmed'
      },
      archive: {
        type: Boolean,
        default: false
      },
      branch: [
    // Incorrectly setup as an array rather than an object.
    // Can $unwind as there is only ever one item in the array
        {
          name: {
            type: String,
            required: true
          },
          clinic_id: { // aka branchId
            type: String,
            required: true
          }
        }
      ]
    }

Notification Schema:

{
  branchId: { type: String, required: true }, // aka clinic_id
  patientId: { type: String, required: true },
  acknowledged: { type: Boolean, default: false },
  date: { type: Date, default: Date.now }
}

Aggregation Query:

[
  { $match: { 'branch.0.clinic_id': '1', archive: false } },
  { $unwind: '$branch' },
  {
    $lookup: {
      from: 'notifications',
      let: { clinic_id: '1', patient_id: '$patientId' }, //<-- issue with patient_id?
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
               { $eq: ["$patientId", "$$patientId"] }, <-- errors $$patientId unknown value. $$patient_id returns 0 results.
                { $eq: ['$branchId', '$$clinic_id'] },
                { $eq: ['$acknowledged', false] }
              ]
            }
          }
        }
      ],
      as: 'notif'
    }
  }
]

Example Output with comments on desired output and incorrect output I've experienced:

  {
  patient_id: '1',
  time: '2019-05-29T11:00:00.000Z',
  status: 'unconfirmed',
  archive: false,
  branch: [
    {
      name: 'Example location',
      clinic_id: '100',
    }
  ],
  notif: [
  {
    // This is correct
    branchId: '100', // branchId matches clinic_id
    patientId: '1',  // patientId matches contacts patient_id
    acknowledged: false, // notification is unacknowledged
    date: '2019-05-18T16:18:05.480Z'
  },
  {
   // This is not correct
    branchId: '100',
    patientId: '2', // PatientId does not match patient_id of reminder
    acknowledged: false,
    date: '2019-05-20T16:18:05.480Z'
  }
  ]
}


问:
For a shared resource accessed by two threads, how to arrange priority?
Is there a way to give one thread priority over another when accessing the resource?</p>

答:
May be you can use setPriority(int) method of Thread class.

Ex:-

```<code>Threadt = new Thread(this);
t.setPriority(Thread.NORM_PRIORITY);
</code>```

Body:
May be you can use setPriority(int) method of Thread class.

Ex:-

Threadt = new Thread(this);
t.setPriority(Thread.NORM_PRIORITY);


问:
Custom Partitioner for skewed data
I have a whole world data of some usecase. Each country contains 3 to 5 products, which is collected every hour for each user. I want to do bootstrapping to calculate some average and other ratios per country per product per hour.

```<code>input.rdd.map(
      row => (
        (country, product, hour),
        (country, product, hour, user, rating)
        )
    )
val groups = keyGroup.groupByKey()
val output = groups.flatMapValues(x => bootstrap(x)).toDF
</code>```

The problem is some countries data is quite big, which is causing the whole process to take hours and still not finish. I try to get the size which is roughly:

```<code>Partition:count ->Countries

0: 2044816 -> India,Turkey

1: 1466790 -> Turkey,India

2: 783772 -> India,Mexico,Japan,South Korea

3: 431538 -> Japan,Mexico,South Korea,India,Indonesia,Turkey,Brazil,Russian Federation

4: 319824 -> South Korea,Brazil,Russian Federation,India,Mexico,United States of America,Turkey,Japan,Bangladesh

5: 268698 -> Bangladesh,Nigeria,Russian Federation,United States of America

6: 264709 -> Russian Federation,United States of America,Germany,Bangladesh,Nigeria,South Africa

7: 227612 -> South Africa,United States of America,Russian Federation,Brazil,South Korea,Germany
...
...
167: 58 -> Mexico,Chile,Uganda,Thailand,Ivory Coast,Antigua and Barbuda,Palau,Luxembourg,United States of America,British Virgin Islands,Iceland,Andorra,Samoa,Vanuatu,Botswana,Saint Lucia,Kiribati,Greenland

168: 69 -> Greenland,Iceland,Chile,Zambia,Estonia,Vanuatu,Cyprus,Malta,Saudi Arabia,Japan,Uruguay,Qatar,United States of America,Luxembourg,Peru,Belize,Papua New Guinea,Samoa,South Sudan

169: 61 -> Myanmar,Belize,Chile,Somalia,Bhutan,Luxembourg,Liberia,Norway,United Kingdom,Burkina Faso,Lithuania,Macedonia,Belgium,Vanuatu,Burundi,DR Congo,Montenegro,Central African Republic,Bosnia and Herzegovina

170: 36 -> Mauritania,Sierra Leone,Hungary,Zambia,Somalia,Federated States of Micronesia,Serbia,Liberia,Nepal,Chile,Israel,Ukraine,Montenegro,Yemen,Croatia,Central African Republic,Armenia,Andorra,United Arab Emirates,Mauritius,Albania,Lebanon,Macedonia

171: 25 -> Spain,Comoros,Libya,Peru,Latvia,Montenegro,Egypt,Malaysia,Central African Republic,Faroe Islands,Tanzania,Palau,Chad,Guatemala,Kiribati,Burundi,Luxembourg,Equatorial Guinea,Barbados,Belgium

172: 14 -> Vietnam,Tanzania,Hungary,Egypt,Comoros,Equatorial Guinea,Guinea-Bissau,Moldova,Macedonia,Guyana,Federated States of Micronesia,New Zealand,Chad
</code>```

It can be seen that the data is not divided evenly, and it has 173 partitions. The data is around 6 GB which contains a week data. If I try to run single single country by doing repartition of 1000 it works, but together it doesn't work.

I am thinking to write a custom partitioner but I have no clue how should I break that data for bigger countries count. It would be great if someone can help me out.

答:
Before you go down the path of writing your own custom partitioner you can try this:
Since you already know which countries have skewed data you can create a composite key with randomly appended numbers in some range (wider range for more skewed data) for said countries. You can aggregate on said key and later drop the composite key and aggregate further.

```<code>df.withColumn("composite_key",
    when(isSkewDataCountryUDF(col("country")), concat(col("country"), randomNumberSuffix())
    .otherwise(col("country")))
.groupBy("composite_key")
.count
.drop("composite_key")
.groupBy("country")
.count
</code>```

Also try to set a much higher spark.default.parallelism and spark.sql.shuffle.partitions

Title: Custom Partitioner for skewed data

Body:
I have a whole world data of some usecase. Each country contains 3 to 5 products, which is collected every hour for each user. I want to do bootstrapping to calculate some average and other ratios per country per product per hour.

input.rdd.map(
      row => (
        (country, product, hour),
        (country, product, hour, user, rating)
        )
    )
val groups = keyGroup.groupByKey()
val output = groups.flatMapValues(x => bootstrap(x)).toDF

The problem is some countries data is quite big, which is causing the whole process to take hours and still not finish. I try to get the size which is roughly:

Partition:count ->Countries

0: 2044816 -> India,Turkey

1: 1466790 -> Turkey,India

2: 783772 -> India,Mexico,Japan,South Korea

3: 431538 -> Japan,Mexico,South Korea,India,Indonesia,Turkey,Brazil,Russian Federation

4: 319824 -> South Korea,Brazil,Russian Federation,India,Mexico,United States of America,Turkey,Japan,Bangladesh

5: 268698 -> Bangladesh,Nigeria,Russian Federation,United States of America

6: 264709 -> Russian Federation,United States of America,Germany,Bangladesh,Nigeria,South Africa

7: 227612 -> South Africa,United States of America,Russian Federation,Brazil,South Korea,Germany
...
...
167: 58 -> Mexico,Chile,Uganda,Thailand,Ivory Coast,Antigua and Barbuda,Palau,Luxembourg,United States of America,British Virgin Islands,Iceland,Andorra,Samoa,Vanuatu,Botswana,Saint Lucia,Kiribati,Greenland

168: 69 -> Greenland,Iceland,Chile,Zambia,Estonia,Vanuatu,Cyprus,Malta,Saudi Arabia,Japan,Uruguay,Qatar,United States of America,Luxembourg,Peru,Belize,Papua New Guinea,Samoa,South Sudan

169: 61 -> Myanmar,Belize,Chile,Somalia,Bhutan,Luxembourg,Liberia,Norway,United Kingdom,Burkina Faso,Lithuania,Macedonia,Belgium,Vanuatu,Burundi,DR Congo,Montenegro,Central African Republic,Bosnia and Herzegovina

170: 36 -> Mauritania,Sierra Leone,Hungary,Zambia,Somalia,Federated States of Micronesia,Serbia,Liberia,Nepal,Chile,Israel,Ukraine,Montenegro,Yemen,Croatia,Central African Republic,Armenia,Andorra,United Arab Emirates,Mauritius,Albania,Lebanon,Macedonia

171: 25 -> Spain,Comoros,Libya,Peru,Latvia,Montenegro,Egypt,Malaysia,Central African Republic,Faroe Islands,Tanzania,Palau,Chad,Guatemala,Kiribati,Burundi,Luxembourg,Equatorial Guinea,Barbados,Belgium

172: 14 -> Vietnam,Tanzania,Hungary,Egypt,Comoros,Equatorial Guinea,Guinea-Bissau,Moldova,Macedonia,Guyana,Federated States of Micronesia,New Zealand,Chad

It can be seen that the data is not divided evenly, and it has 173 partitions. The data is around 6 GB which contains a week data. If I try to run single single country by doing repartition of 1000 it works, but together it doesn't work.

I am thinking to write a custom partitioner but I have no clue how should I break that data for bigger countries count. It would be great if someone can help me out.

Body:
Before you go down the path of writing your own custom partitioner you can try this:
Since you already know which countries have skewed data you can create a composite key with randomly appended numbers in some range (wider range for more skewed data) for said countries. You can aggregate on said key and later drop the composite key and aggregate further.

df.withColumn("composite_key",
    when(isSkewDataCountryUDF(col("country")), concat(col("country"), randomNumberSuffix())
    .otherwise(col("country")))
.groupBy("composite_key")
.count
.drop("composite_key")
.groupBy("country")
.count

Also try to set a much higher spark.default.parallelism and spark.sql.shuffle.partitions


问:
RecycleView doesen't show any value
My RecyclerView doesn't show any value in alert dialog. I am confused and don't know where should I looking for a problem in my code. I hope some of you guys met with same issue.

This is activity where I am calling my RecycleView andl AlertDialog.

```<code>  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pondeljak = (Button) findViewById(R.id.buttonPonedeljak);
        utorak = (Button) findViewById(R.id.buttonUtorak);
        sreda = (Button) findViewById(R.id.buttonSreda);
        cetvrtak = (Button) findViewById(R.id.buttonCetvrtak);
        petak = (Button) findViewById(R.id.buttonPetak);

        db = new DataDays(this);

        View view  = getLayoutInflater().inflate(R.layout.casovi,null);

        alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setView(view);

        alertDialog = alertDialogBuilder.create();

        recyclerView = (RecyclerView) view.findViewById(R.id.recycleCasoviID);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        casoviList = new ArrayList<>();
        casoviItems = new ArrayList<>();

      //  for (Casovi c: casoviList){

            Casovi casovi = new Casovi();

            //casovi.setId(0);
            casovi.setDan("asas");
            casovi.setRedniBrCasa("ssss");
            casovi.setNzaivCasa("ssddff");

            casoviItems.add(casovi);

        recycleViewAdapter = new RecycleViewAdapter(this, casoviItems);
        recyclerView.setAdapter(recycleViewAdapter);
        recycleViewAdapter.notifyDataSetChanged();

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

                if (db.casoviCountPondeljak() == 0){
                    Intent intent = new Intent(MainActivity.this, Unos_casova.class);
                    intent.putExtra("Dan", "Pondeljak");
                    startActivity(intent);

                }else {
                    alertDialog.show();

                }
</code>```

This is RecycleView class. I am not sure, maybe here is some problem?

```<code>public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {

    private Context context;
    private List<Casovi> casoviItems;

    public RecycleViewAdapter(Context context, List<Casovi> casoviItems) {
        this.context = context;
        this.casoviItems = casoviItems;
    }

    @Override
    public RecycleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prikaz_casova, parent,false);

        return new ViewHolder(view, context);
    }

    @Override
    public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {

        Casovi casovi = new Casovi();

        holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
        holder.nazivCasPrikaz.setText(casovi.getRedniBrCasa());

    }

    @Override
    public int getItemCount() {

        return casoviItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView redniBrCasPrikaz;
        public TextView nazivCasPrikaz;
        public Button delteBtn;
        public Button editBtn;
        public CardView cardView;

        public ViewHolder(View view, Context ctx) {
            super(view);

            context = ctx;

            redniBrCasPrikaz = (TextView) view.findViewById(R.id.rednibrojCasaID);
            nazivCasPrikaz = (TextView) view.findViewById(R.id.nazivcasaID);
            delteBtn = (Button) view.findViewById(R.id.obrisiCasBtnID);
            editBtn = (Button) view.findViewById(R.id.izmeniCasBtnID);
            cardView = (CardView) view.findViewById(R.id.carViewID);

        }
    }
</code>```

Layout casovi. That RecycleView on witch prikaz casova should be attached.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleCasoviID"
        android:layout_width="match_parent"
        android:layout_height="574dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.283" />
</android.support.constraint.ConstraintLayout>
</code>```

Layout prikaz_casova. This layout should show values from db. In this exemple I've posted there is hadrdoced values tho be showen.

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/carViewID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="133dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="470dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.471">

        <RelativeLayout
            android:id="@+id/relativniID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/rednibrojCasaID"
                android:layout_width="126dp"
                android:layout_height="wrap_content"
                android:text="redni broj casa"
                android:textSize="14dp"
                android:textStyle="italic"

                />

            <TextView
                android:id="@+id/nazivcasaID"
                android:layout_width="338dp"
                android:layout_height="105dp"
                android:layout_below="@+id/rednibrojCasaID"
                android:layout_marginTop="1dp"
                android:text="Naziv casa"
                android:textSize="24dp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/obrisiCasBtnID"
                android:layout_width="40dp"
                android:layout_height="37dp"
                android:layout_below="@+id/rednibrojCasaID"
                android:layout_toRightOf="@+id/nazivcasaID"
                android:background="@drawable/delete" />

            <Button
                android:id="@+id/izmeniCasBtnID"
                android:layout_width="40dp"
                android:layout_height="37dp"
                android:layout_below="@+id/obrisiCasBtnID"
                android:layout_marginLeft="3dp"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@+id/nazivcasaID"
                android:background="@drawable/edit" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>
</code>```

答:
Here the error you made, in your RecyclerView Adapter class.

```<code> @Override
public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {
</code>```

Casovi casovi = new Casovi();

It should be

```<code>Casovi casovi = casoviItems.get(position);

    holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
    holder.nazivCasPrikaz.setText(casovi.getRedniBrCasa());

}
</code>```

You are all done

Title: RecycleView doesen't show any value

Body:
My RecyclerView doesn't show any value in alert dialog. I am confused and don't know where should I looking for a problem in my code. I hope some of you guys met with same issue.

This is activity where I am calling my RecycleView andl AlertDialog.

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pondeljak = (Button) findViewById(R.id.buttonPonedeljak);
        utorak = (Button) findViewById(R.id.buttonUtorak);
        sreda = (Button) findViewById(R.id.buttonSreda);
        cetvrtak = (Button) findViewById(R.id.buttonCetvrtak);
        petak = (Button) findViewById(R.id.buttonPetak);

        db = new DataDays(this);

        View view  = getLayoutInflater().inflate(R.layout.casovi,null);

        alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setView(view);

        alertDialog = alertDialogBuilder.create();

        recyclerView = (RecyclerView) view.findViewById(R.id.recycleCasoviID);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        casoviList = new ArrayList<>();
        casoviItems = new ArrayList<>();

      //  for (Casovi c: casoviList){

            Casovi casovi = new Casovi();

            //casovi.setId(0);
            casovi.setDan("asas");
            casovi.setRedniBrCasa("ssss");
            casovi.setNzaivCasa("ssddff");

            casoviItems.add(casovi);

        recycleViewAdapter = new RecycleViewAdapter(this, casoviItems);
        recyclerView.setAdapter(recycleViewAdapter);
        recycleViewAdapter.notifyDataSetChanged();

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

                if (db.casoviCountPondeljak() == 0){
                    Intent intent = new Intent(MainActivity.this, Unos_casova.class);
                    intent.putExtra("Dan", "Pondeljak");
                    startActivity(intent);

                }else {
                    alertDialog.show();

                }

This is RecycleView class. I am not sure, maybe here is some problem?

public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {

    private Context context;
    private List<Casovi> casoviItems;

    public RecycleViewAdapter(Context context, List<Casovi> casoviItems) {
        this.context = context;
        this.casoviItems = casoviItems;
    }

    @Override
    public RecycleViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prikaz_casova, parent,false);

        return new ViewHolder(view, context);
    }

    @Override
    public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {

        Casovi casovi = new Casovi();

        holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
        holder.nazivCasPrikaz.setText(casovi.getRedniBrCasa());

    }

    @Override
    public int getItemCount() {

        return casoviItems.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView redniBrCasPrikaz;
        public TextView nazivCasPrikaz;
        public Button delteBtn;
        public Button editBtn;
        public CardView cardView;

        public ViewHolder(View view, Context ctx) {
            super(view);

            context = ctx;

            redniBrCasPrikaz = (TextView) view.findViewById(R.id.rednibrojCasaID);
            nazivCasPrikaz = (TextView) view.findViewById(R.id.nazivcasaID);
            delteBtn = (Button) view.findViewById(R.id.obrisiCasBtnID);
            editBtn = (Button) view.findViewById(R.id.izmeniCasBtnID);
            cardView = (CardView) view.findViewById(R.id.carViewID);

        }
    }

Layout casovi. That RecycleView on witch prikaz casova should be attached.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycleCasoviID"
        android:layout_width="match_parent"
        android:layout_height="574dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.283" />
</android.support.constraint.ConstraintLayout>

Layout prikaz_casova. This layout should show values from db. In this exemple I've posted there is hadrdoced values tho be showen.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.CardView
        android:id="@+id/carViewID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="133dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="470dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.471">

        <RelativeLayout
            android:id="@+id/relativniID"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/rednibrojCasaID"
                android:layout_width="126dp"
                android:layout_height="wrap_content"
                android:text="redni broj casa"
                android:textSize="14dp"
                android:textStyle="italic"

                />

            <TextView
                android:id="@+id/nazivcasaID"
                android:layout_width="338dp"
                android:layout_height="105dp"
                android:layout_below="@+id/rednibrojCasaID"
                android:layout_marginTop="1dp"
                android:text="Naziv casa"
                android:textSize="24dp"
                android:textStyle="bold" />

            <Button
                android:id="@+id/obrisiCasBtnID"
                android:layout_width="40dp"
                android:layout_height="37dp"
                android:layout_below="@+id/rednibrojCasaID"
                android:layout_toRightOf="@+id/nazivcasaID"
                android:background="@drawable/delete" />

            <Button
                android:id="@+id/izmeniCasBtnID"
                android:layout_width="40dp"
                android:layout_height="37dp"
                android:layout_below="@+id/obrisiCasBtnID"
                android:layout_marginLeft="3dp"
                android:layout_marginTop="15dp"
                android:layout_toRightOf="@+id/nazivcasaID"
                android:background="@drawable/edit" />

        </RelativeLayout>
    </android.support.v7.widget.CardView>
</android.support.constraint.ConstraintLayout>

Body:
Here the error you made, in your RecyclerView Adapter class.

 @Override
public void onBindViewHolder( RecycleViewAdapter.ViewHolder holder, int position) {

Casovi casovi = new Casovi();

It should be

Casovi casovi = casoviItems.get(position);

    holder.redniBrCasPrikaz.setText(casovi.getRedniBrCasa());
    holder.nazivCasPrikaz.setText(casovi.getRedniBrCasa());

}

You are all done


问:
Spark repartitionAndSortWithinPartitions with tuples
I'm trying to follow this example to partition hbase rows: https://www.opencore.com/blog/2016/10/efficient-bulk-load-of-hbase-using-spark/

However, I have data already stored in (String, String, String) where the first is the rowkey, second is column name, and third is column value.

I tried writing an implicit ordering to achieve the OrderedRDD implicit

```<code> implicit val caseInsensitiveOrdering: Ordering[(String, String, String)] = new Ordering[(String, String, String)] {
    override def compare(x: (String, String, String), y: (String, String, String)): Int = ???
  }
</code>```

but repartitionAndSortWithinPartitions is still not available. Is there a way I can use this method with this tuple?

答:
RDD must have key and value, not only values, for ex.:</p>

```<code>val data = List((("5", "6", "1"), (1)))
val rdd : RDD[((String, String, String), Int)] = sparkContext.parallelize(data)
implicit val caseInsensitiveOrdering = new Ordering[(String, String, String)] {
  override def compare(x: (String, String, String), y: (String, String, String)): Int = 1
}
rdd.repartitionAndSortWithinPartitions(..)
</code>```

Body:
I'm trying to follow this example to partition hbase rows: https://www.opencore.com/blog/2016/10/efficient-bulk-load-of-hbase-using-spark/

However, I have data already stored in (String, String, String) where the first is the rowkey, second is column name, and third is column value.

I tried writing an implicit ordering to achieve the OrderedRDD implicit

 implicit val caseInsensitiveOrdering: Ordering[(String, String, String)] = new Ordering[(String, String, String)] {
    override def compare(x: (String, String, String), y: (String, String, String)): Int = ???
  }

but repartitionAndSortWithinPartitions is still not available. Is there a way I can use this method with this tuple?

Body:
RDD must have key and value, not only values, for ex.:

val data = List((("5", "6", "1"), (1)))
val rdd : RDD[((String, String, String), Int)] = sparkContext.parallelize(data)
implicit val caseInsensitiveOrdering = new Ordering[(String, String, String)] {
  override def compare(x: (String, String, String), y: (String, String, String)): Int = 1
}
rdd.repartitionAndSortWithinPartitions(..)


问:
has() returns false for Set of multidimensional array?
I created a Set of 2D arrays like this:

```<code>let set = new Set([[1, 2], [4, 6]]);
</code>```

now when I am doing set.has([1, 2]) it returns false.
How can I achieve this?

答:
If you're going to compare objects or arrays (which aren't primitives, and so aren't ===), stringify everything in the Set first:

const set = new Set([[1, 2], [4, 6]]);
const setStringified = new Set([...set].map(JSON.stringify));

console.log(setStringified.has(JSON.stringify([1, 2])));```

Body:
I created a Set of 2D arrays like this:

let set = new Set([[1, 2], [4, 6]]);

now when I am doing set.has([1, 2]) it returns false.
How can I achieve this?


问:
RxAlamofire make post call with json body
I want to make post call using RxAlamofire not able to find any method to do so

tried using requestJSON method but there is no paramter to pass post json in

```<code> RxAlamofire.requestJSON(.post, url)
</code>```

how to make post call and pass json data to post call in RxAlamofire

答:
Use following code</p>

```<code>  var request = URLRequest(url: URL(string: "https://some_url")!)
    //Following code to pass post json
    request.httpBody = json
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    RxAlamofire.request(request as URLRequestConvertible).responseJSON().asObservable()
</code>```

Body:
I want to make post call using RxAlamofire not able to find any method to do so

tried using requestJSON method but there is no paramter to pass post json in

 RxAlamofire.requestJSON(.post, url)

how to make post call and pass json data to post call in RxAlamofire

Body:
Use following code

  var request = URLRequest(url: URL(string: "https://some_url")!)
    //Following code to pass post json
    request.httpBody = json
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    RxAlamofire.request(request as URLRequestConvertible).responseJSON().asObservable()


问:
How can I get a data from socket and make a protobuf file?
How to receive a file from socket in swift and converting it to swift protobuf?

First of all I'm using blue socket from IBM .

I try to receive the size of the protobuf in String format, then convert it to int and then I open a buffer of the size I get from server.

The problem is that socket won't fill the data of the size it should be.

How can I make a data with fixed size (size I get in string format) and wait for it to get filled with data and then convert in to protobuf?

And is there other ways?

答:
Ok after months and days of working on this thing I found the right way to do it and it's not with socket.

To send and receive protobuf to server they have something called BinaryDelimited.

To receive protobuf from server you will use :

```<code>BinaryDelimited.parse(messageType: ProtoFile.self, from: inputStream )
</code>```

ProtoFile.self is your custom protobuf class that you compiled.

To send protobuf to server you will use :

```<code>BinaryDelimited.serialize(message: proto, to: outputStream)
</code>```

and to initialize the input and out put and connect it to your server use

```<code>var inputStream : InputStream!
var outPutStream : OutputStream!

func setupNetworkCommunication() {
        var readStream: Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                           "localhost" as CFString,
                                           port,
                                           &readStream,
                                           &writeStream)

        inputStream = readStream!.takeRetainedValue()
        outputStream = writeStream!.takeRetainedValue()

        inputStream.delegate = self
        outputStream.delegate = self

        inputStream.schedule(in: .main, forMode: .common)
        outputStream.schedule(in: .main, forMode: .common)

        inputStream.open()
        outputStream.open()
    }
</code>```

Body:
Ok after months and days of working on this thing I found the right way to do it and it's not with socket.

To send and receive protobuf to server they have something called BinaryDelimited.

To receive protobuf from server you will use :

BinaryDelimited.parse(messageType: ProtoFile.self, from: inputStream )

ProtoFile.self is your custom protobuf class that you compiled.

To send protobuf to server you will use :

BinaryDelimited.serialize(message: proto, to: outputStream)

and to initialize the input and out put and connect it to your server use

var inputStream : InputStream!
var outPutStream : OutputStream!

func setupNetworkCommunication() {
        var readStream: Unmanaged<CFReadStream>?
        var writeStream: Unmanaged<CFWriteStream>?

        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                           "localhost" as CFString,
                                           port,
                                           &readStream,
                                           &writeStream)

        inputStream = readStream!.takeRetainedValue()
        outputStream = writeStream!.takeRetainedValue()

        inputStream.delegate = self
        outputStream.delegate = self

        inputStream.schedule(in: .main, forMode: .common)
        outputStream.schedule(in: .main, forMode: .common)

        inputStream.open()
        outputStream.open()
    }


问:
docx4j or Apache-POI: How to get paragraph IDs from docx file containing images and languages other than English?
I want to get paragraph ids from .docx file. I am not able to  get ids when there is file with language other than english or an image.

I have tried to read paragraphs by docx4j and apache-poi as below. But unable to get paragraph Ids.

```<code> List<CLMParagraph> clmParagraphs = new ArrayList<CLMParagraph>();

    List<XWPFParagraph> paragraphs =
  document.getParagraphs();

    for (int i = 0; i < xmlfragmentlist.getLength(); i++) {

        Node node = xmlfragmentlist.item(i);

        CLMParagraph paragraph = new CLMParagraph();

        // do something for each node

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            Element e = (Element) node;

            if (e.hasAttribute("w14:paraId")) {

                paragraph.setParaId(e.getAttribute("w14:paraId"));

                paragraph.setParaText(paragraphs.get(i).getText());

                paragraph.setSentences(getParaSentences(document, paragraphs.get(i)));

                clmParagraphs.add(paragraph);

            }

        }

    }
</code>```

I want to get paragraph ids for the images and text in other than english language.

答:
In docx4j, with paragraph object P p, it is just p.getParaId()

See further https://github.com/plutext/docx4j/blob/master/docx4j-openxml-objects/src/main/java/org/docx4j/wml/P.java#L364

Whether there are images or LOTE is irrelevant.

Body:
I want to get paragraph ids from .docx file. I am not able to  get ids when there is file with language other than english or an image.

I have tried to read paragraphs by docx4j and apache-poi as below. But unable to get paragraph Ids.

 List<CLMParagraph> clmParagraphs = new ArrayList<CLMParagraph>();

    List<XWPFParagraph> paragraphs =
  document.getParagraphs();

    for (int i = 0; i < xmlfragmentlist.getLength(); i++) {

        Node node = xmlfragmentlist.item(i);

        CLMParagraph paragraph = new CLMParagraph();

        // do something for each node

        if (node.getNodeType() == Node.ELEMENT_NODE) {

            Element e = (Element) node;

            if (e.hasAttribute("w14:paraId")) {

                paragraph.setParaId(e.getAttribute("w14:paraId"));

                paragraph.setParaText(paragraphs.get(i).getText());

                paragraph.setSentences(getParaSentences(document, paragraphs.get(i)));

                clmParagraphs.add(paragraph);

            }

        }

    }

I want to get paragraph ids for the images and text in other than english language.


问:
NTRUEncrypt: can't properly find GCD of two polynomials using decribed in open source standard algorithms, fail to define if inverse of poly exists
I've implemented algorithms for finding an inverse of a polynomial as described at onboard security resourses, but these algorithms imply that GCD of poly that I want to invert and X^N - 1 is 1.

For proper NTRU implementation I need to randomly generate small polynomials and define if their inverse exist, for now I don't have such functionality.
In order to get it work i tried to implement Euclidean algorithm as described in documentation for NTRU Open Source project. But I found some things very inconsistent which bugs me off.
Division and Euclidean algorithms can be found on page 19 of named document.

So, in division algorithm the inputs are polynomials a and b. It is stated that polynomial b must be of degree N-1.

Pseudocode for division algorithm (taken from this answer):

```<code>a)  Set r := a and q := 0
b)  Set u := (b_N)^–1 mod p
c)  While deg r >= N do
    1)    Set d := deg r(X)
    2)    Set v := u × r_d × X^(d–N)
    3)    Set r := r – v × b
    4)    Set q := q + v
d)  Return q, r
</code>```

In order to find GCD of two polynomials, one must call Euclidean algorithm with inputs a (some polynomial) and X^N-1. These inputs are then passed to division algorighm.

Question is: how can X^N - 1 be passed into division algorithm if it is clearly stated that second parameter should be poly with degree N-1 ?

Ignoring this issue, there's still things I do not understand:

what is N in division algorithm? Is it N from NTRU parameters or is it degree of polynomial b?

either way, how can condition c) ever be true? NTRU operates with polynomials of degree less than N

For the greater context, here is my C++ implementation of Euclidean and Division algorithms. Given the inputs a = {-1, 1, 1, 0, -1, 0, 1, 0, 0, 1, -1}, b = {-1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1}, p = 3 and N = 11 it enters endless loop inside division algorithm

```<code>using tPoly = std::deque<int>;

std::pair<tPoly, tPoly> divisionAlg(tPoly a, tPoly b, int p, int N)
{
    tPoly r = a;
    tPoly q{0};
    int b_degree = degree(b);
    int u = Helper::getInverseNumber(b[b_degree], p);

    while (degree(r) >= N)
    {
        int d = degree(r);
        tPoly v = genXDegreePoly(d-N); // X^(d-N)
        v[d-N] = u*r[d]; // coefficient of v
        r -= multiply(v, b, N);
        q += v;
    }
    return {q, r};
}

struct sEucl
{
    sEucl(int U=0, int V=0, int D=0)
        : u{U}
        , v{V}
        , d{D}
    {}

    tPoly u;
    tPoly v;
    tPoly d;
};

sEucl euclidean(tPoly a, tPoly b, int p, int N)
{
    sEucl res;
    if ((degree(b) == 0) && (b[0] == 0))
    {
        res = sEucl(1, 0);
        res.d = a;
        Helper::printPoly(res.d);
        return res;
    }

    tPoly u{1};
    tPoly d = a;
    tPoly v1{0};
    tPoly v3 = b;

    while ((0 != degree(v3)) && (0 != v3[0]))
    {
        std::pair<tPoly, tPoly> division = divisionAlg(d, v3, p, N);
        tPoly q = division.first;
        tPoly t3 = division.second;
        tPoly t1 = u;
        t1 -= PolyMath::multiply(q, v1, N);
        u = v1;
        d = v3;
        v1 = t1;
        v3 = t3;
    }
    d -= multiply(a, u, N);
    tPoly v = divide(d, b).first;

    res.u = u;
    res.v = v;
    res.d = d;
    return res;
}
</code>```

Additionally, polynomial operations used in this listing may be found at github page

答:
I accidentally googled the answer. I don't really need to calculate GCD to pick a random invertable polynomial, I just need to choose the right amount of 1 and 0 (for binary) or -1, 0 and 1 (for ternary) for my random poly.

Please, consider this question solved.

Body:
I've implemented algorithms for finding an inverse of a polynomial as described at onboard security resourses, but these algorithms imply that GCD of poly that I want to invert and X^N - 1 is 1.

For proper NTRU implementation I need to randomly generate small polynomials and define if their inverse exist, for now I don't have such functionality.
In order to get it work i tried to implement Euclidean algorithm as described in documentation for NTRU Open Source project. But I found some things very inconsistent which bugs me off.
Division and Euclidean algorithms can be found on page 19 of named document.

So, in division algorithm the inputs are polynomials a and b. It is stated that polynomial b must be of degree N-1.

Pseudocode for division algorithm (taken from this answer):

a)  Set r := a and q := 0
b)  Set u := (b_N)^–1 mod p
c)  While deg r >= N do
    1)    Set d := deg r(X)
    2)    Set v := u × r_d × X^(d–N)
    3)    Set r := r – v × b
    4)    Set q := q + v
d)  Return q, r

In order to find GCD of two polynomials, one must call Euclidean algorithm with inputs a (some polynomial) and X^N-1. These inputs are then passed to division algorighm.

Question is: how can X^N - 1 be passed into division algorithm if it is clearly stated that second parameter should be poly with degree N-1 ?

Ignoring this issue, there's still things I do not understand:

what is N in division algorithm? Is it N from NTRU parameters or is it degree of polynomial b?

either way, how can condition c) ever be true? NTRU operates with polynomials of degree less than N

For the greater context, here is my C++ implementation of Euclidean and Division algorithms. Given the inputs a = {-1, 1, 1, 0, -1, 0, 1, 0, 0, 1, -1}, b = {-1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1}, p = 3 and N = 11 it enters endless loop inside division algorithm

using tPoly = std::deque<int>;

std::pair<tPoly, tPoly> divisionAlg(tPoly a, tPoly b, int p, int N)
{
    tPoly r = a;
    tPoly q{0};
    int b_degree = degree(b);
    int u = Helper::getInverseNumber(b[b_degree], p);

    while (degree(r) >= N)
    {
        int d = degree(r);
        tPoly v = genXDegreePoly(d-N); // X^(d-N)
        v[d-N] = u*r[d]; // coefficient of v
        r -= multiply(v, b, N);
        q += v;
    }
    return {q, r};
}

struct sEucl
{
    sEucl(int U=0, int V=0, int D=0)
        : u{U}
        , v{V}
        , d{D}
    {}

    tPoly u;
    tPoly v;
    tPoly d;
};

sEucl euclidean(tPoly a, tPoly b, int p, int N)
{
    sEucl res;
    if ((degree(b) == 0) && (b[0] == 0))
    {
        res = sEucl(1, 0);
        res.d = a;
        Helper::printPoly(res.d);
        return res;
    }

    tPoly u{1};
    tPoly d = a;
    tPoly v1{0};
    tPoly v3 = b;

    while ((0 != degree(v3)) && (0 != v3[0]))
    {
        std::pair<tPoly, tPoly> division = divisionAlg(d, v3, p, N);
        tPoly q = division.first;
        tPoly t3 = division.second;
        tPoly t1 = u;
        t1 -= PolyMath::multiply(q, v1, N);
        u = v1;
        d = v3;
        v1 = t1;
        v3 = t3;
    }
    d -= multiply(a, u, N);
    tPoly v = divide(d, b).first;

    res.u = u;
    res.v = v;
    res.d = d;
    return res;
}

Additionally, polynomial operations used in this listing may be found at github page


问:
What is the most elegant way to cast a variable you just received as an argument?
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

```<code>public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}
</code>```

Or am I missing the point here? Is there a better way to handle this in general?

答:
```<code>Graphics2D g2 = Graphics2D.class.cast(g);
</code>```

OwnerDisplayName: spligak

ContentLicense: CC BY-SA 2.5

Body:
More specifically, what's the most elegant way to cast the Graphics object in a paint() call up to a Graphics2D object?

public void paint(Graphics g) {
    // How do I convert/cast/etc the g variable to a Graphics2D object?
}

Or am I missing the point here? Is there a better way to handle this in general?

OwnerDisplayName: Pierre


问:
Configuration Manager
I'me new to powershell so don't bit me up :)
My question is this:
I have to setup two types of machine x86 and x64.
During this setup I have to check the version of .NET Framework install on the machine.
I'm doing it by invoking Test-Path:
Test-Key "HKLM:\Software\Wow6432Node\Microsoft\NET Framework Setup\NDP\v1.1.4322" "Install"
what I'd like to do is this:
    # Check if the system is x64 architecture
    # in case of positive answere change the registry
    # to Wow6432Node
    if($os_architecture -eq "x64")
    {
        $dot_net_registry_root_path = "HKLM:\SOFTWARE\Wow6432Node"
    }

```<code># Add common framework path
$dot_net_registry_path = $dot_net_registry_root_path + "\NET Framework Setup\NDP\"

# Check 1.0 version of .NET Framework
$dot_net_1_0_registry_path = $dot_net_registry_root_path + "\Microsoft\.NETFramework\v1.0\SBSDisabled"

if(!(Test-Key $dot_net_1_0_registry_path "Install"))
{
    Write-Output ".NET Framework v1.0.3705 is NOT installed"
}
else
{
    Write-Output ".NET Framework v1.0.3705 is installed"
}

# Check 1.1 version of .NET Framework
$dot_net_1_1_registry_path = "'" + $dot_net_registry_path + "v1.1.4322"  + "'"

if (!(Test-Key $dot_net_1_1_registry_path "Install"))
{
    Write-Output "Please install .NET Framework v1.1.4322"
}
else
{
    Write-Output ".NET Framework v1.1.4322 is installed"
}
</code>```

where Test-Key

```<code>function Test-Key([string]$path, [string]$key)
{
    if(!(Test-Path -LiteralPath $path)) { return $false }

    if ((Get-ItemProperty $path).$key -eq $null) { return $false }

    return $true
}
</code>```

The problem is that when I'm using variable instead of quoted string Test-Path fail because of spaces into the path: "\NET Framework Setup"

What should do to fix this?

答:
I often end up putting "" around paths just to be certain, tried adding them to the Test-Path and Get-ItemProperty calls in the function above:

if(!(Test-Path -LiteralPath "$path"))

if ((Get-ItemProperty "$path").$key

You can get the architecture of a machine with the command

(Get-WmiObject Win32_OperatingSystem).OSArchitecture

Title: Configuration Manager

Body:
I'me new to powershell so don't bit me up :)
My question is this:
I have to setup two types of machine x86 and x64.
During this setup I have to check the version of .NET Framework install on the machine.
I'm doing it by invoking Test-Path:
Test-Key "HKLM:\Software\Wow6432Node\Microsoft\NET Framework Setup\NDP\v1.1.4322" "Install"
what I'd like to do is this:
    # Check if the system is x64 architecture
    # in case of positive answere change the registry
    # to Wow6432Node
    if($os_architecture -eq "x64")
    {
        $dot_net_registry_root_path = "HKLM:\SOFTWARE\Wow6432Node"
    }

# Add common framework path
$dot_net_registry_path = $dot_net_registry_root_path + "\NET Framework Setup\NDP\"

# Check 1.0 version of .NET Framework
$dot_net_1_0_registry_path = $dot_net_registry_root_path + "\Microsoft\.NETFramework\v1.0\SBSDisabled"

if(!(Test-Key $dot_net_1_0_registry_path "Install"))
{
    Write-Output ".NET Framework v1.0.3705 is NOT installed"
}
else
{
    Write-Output ".NET Framework v1.0.3705 is installed"
}

# Check 1.1 version of .NET Framework
$dot_net_1_1_registry_path = "'" + $dot_net_registry_path + "v1.1.4322"  + "'"

if (!(Test-Key $dot_net_1_1_registry_path "Install"))
{
    Write-Output "Please install .NET Framework v1.1.4322"
}
else
{
    Write-Output ".NET Framework v1.1.4322 is installed"
}

where Test-Key

function Test-Key([string]$path, [string]$key)
{
    if(!(Test-Path -LiteralPath $path)) { return $false }

    if ((Get-ItemProperty $path).$key -eq $null) { return $false }

    return $true
}

The problem is that when I'm using variable instead of quoted string Test-Path fail because of spaces into the path: "\NET Framework Setup"

What should do to fix this?


问:
How to get index of a nested json objects array state in react knowing one property value?
My function works in vanilla but not in react with a state.
My state is an array of json objects.
I have a value from an object property and I want the index value from the array.

```<code>    var result = Object.keys(this.state.categories).find(key => {
      var tableau=this.state.categories[key].catID;
        if(tableau === val)
            return key;
    });
    return result;
}
</code>```

I expect an integer but I don't have any error message.

答:
I expect an integer...

Two problems:

Your code uses find on the result of Object.keys, so what gets found will be a string, not an integer (or number), because Object.keys returns an array of the string-named properties of the object you call it on. (Objects can have properties name with strings or Symbols, but Object.keys ignores the Symbol-named ones.)

You're returning key, when you should return true or false. The return value of a find callback tells find whether to return the entry being visited, or keep looping looking for the item to return.

If this.state.categories is an array, you want findIndex without Object.keys:

```<code>var result = this.state.categories.findIndex(
    entry => entry.catID === val
);
</code>```

Result will be the index of the first entry where entry.catID === val was true.

If you want the object for that catID rather than the index, you would use find, just not on Object.keys:

```<code>var result = this.state.categories.find(
    entry => entry.catID === val
);
</code>```

result will be the first entry for which entry.catID === val was true.

Body:
My function works in vanilla but not in react with a state.
My state is an array of json objects.
I have a value from an object property and I want the index value from the array.

    var result = Object.keys(this.state.categories).find(key => {
      var tableau=this.state.categories[key].catID;
        if(tableau === val)
            return key;
    });
    return result;
}

I expect an integer but I don't have any error message.

Body:
I expect an integer...

Two problems:

Your code uses find on the result of Object.keys, so what gets found will be a string, not an integer (or number), because Object.keys returns an array of the string-named properties of the object you call it on. (Objects can have properties name with strings or Symbols, but Object.keys ignores the Symbol-named ones.)

You're returning key, when you should return true or false. The return value of a find callback tells find whether to return the entry being visited, or keep looping looking for the item to return.

If this.state.categories is an array, you want findIndex without Object.keys:

var result = this.state.categories.findIndex(
    entry => entry.catID === val
);

Result will be the index of the first entry where entry.catID === val was true.

If you want the object for that catID rather than the index, you would use find, just not on Object.keys:

var result = this.state.categories.find(
    entry => entry.catID === val
);

result will be the first entry for which entry.catID === val was true.


问:
Zxing QR code scanner code is not working in a fragment
I am trying to develop QR code scanner App using Zxing library in Kotlin. I am able to open the camera and scan the QR code but not getting response.

I also tried this tutorial for implementation but did not get helped.

```<code>class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val mScanner = IntentIntegrator(activity)
        mScanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        mScanner.setBeepEnabled(true)
        mScanner.initiateScan()

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(activity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(activity, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}
</code>```

I want to get response in a toast but when I tried to use debugger I am unable to go to onActivityResult() and the camera closes quickly.

答:
The issue is, the scanner is sending info to your Activity's onActivityResult method, instead of to your fragment method. So the possible solution could be that in your fragment pass "this" as context instead of passing your activity as context. Like in your fragment

```<code> val mScanner = IntentIntegrator(this); // pass fragment context
</code>```

And in fragment wherever you are initializing the scanner pass Fragment as context instead of passing activity as context.

Body:
I am trying to develop QR code scanner App using Zxing library in Kotlin. I am able to open the camera and scan the QR code but not getting response.

I also tried this tutorial for implementation but did not get helped.

class HomeFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home, container, false)
    }
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val mScanner = IntentIntegrator(activity)
        mScanner.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE)
        mScanner.setBeepEnabled(true)
        mScanner.initiateScan()

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        val result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
        if (result != null) {
            if (result.contents == null) {
                Toast.makeText(activity, "Cancelled", Toast.LENGTH_LONG).show()
            } else {
                Toast.makeText(activity, "Scanned: " + result.contents, Toast.LENGTH_LONG).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

I want to get response in a toast but when I tried to use debugger I am unable to go to onActivityResult() and the camera closes quickly.

Body:
The issue is, the scanner is sending info to your Activity's onActivityResult method, instead of to your fragment method. So the possible solution could be that in your fragment pass "this" as context instead of passing your activity as context. Like in your fragment

 val mScanner = IntentIntegrator(this); // pass fragment context

And in fragment wherever you are initializing the scanner pass Fragment as context instead of passing activity as context.


问:
Cypress get element length returns double
I am trying to test the insertion of an item and check the length of the items found before and after the addition operation. Here is the element

```<code><metadata class="chartbase" issubtitle="false" iscontent="true" graphictype="icon" name="barSimpleRectangle">
<metadata class="chartitem" index="0" name="" value="25"></metadata>
<metadata class="chartitem" index="1" name="" value="30"></metadata>
<metadata class="chartitem" name="" index="2" value="36"></metadata>
</code>```

I try to get the chartitems before the addition, increment it by 1 and then call the addition which inserts an chartitem. Now i compare the size with the earlier size using the said code

```<code>cy.get('.chartitem').its('length').then((size)=>{
    cy.log("chart items length is ",size);
    size++;
    cy.log("totalChartItems is ",size);
    cy.get('.insertNewChartItem').eq(0).click({force:true});
    cy.wait(2000);
    cy.get('.chartitem').its('length').then((newsize)=>{
        cy.log("new chart items length is ",newsize);
    })
})
</code>```

size returned here is 3, But newsize returns me 8. Is this a cypress bug?

答:
Cannot repro. Are you sure there isn't a bug in your item insertion? Also, I'm not sure why you're manually incrementing the size (what's the difference between items length and totalChartItems?).

cy.document().then( doc => {
    doc.body.innerHTML = `
        <metadata class="chartbase" issubtitle="false" iscontent="true" graphictype="icon" name="barSimpleRectangle">
        <metadata class="chartitem" index="0" name="" value="25"></metadata>
        <metadata class="chartitem" index="1" name="" value="30"></metadata>
        <metadata class="chartitem" name="" index="2" value="36"></metadata>
    `;
});
cy.get(`.chartitem`).its(`length`).then((size) => {
    expect(size).to.eq(3);
    cy.document().then( doc => {
        doc.body.innerHTML = doc.body.innerHTML +
            `<metadata class="chartitem" name="" index="3" value="37"></metadata>`;
    });
    cy.get(`.chartitem`).its(`length`).then((newsize) => {
        expect(newsize).to.eq(4);
    });
});
```

Body:
I am trying to test the insertion of an item and check the length of the items found before and after the addition operation. Here is the element

<metadata class="chartbase" issubtitle="false" iscontent="true" graphictype="icon" name="barSimpleRectangle">
<metadata class="chartitem" index="0" name="" value="25"></metadata>
<metadata class="chartitem" index="1" name="" value="30"></metadata>
<metadata class="chartitem" name="" index="2" value="36"></metadata>

I try to get the chartitems before the addition, increment it by 1 and then call the addition which inserts an chartitem. Now i compare the size with the earlier size using the said code

cy.get('.chartitem').its('length').then((size)=>{
    cy.log("chart items length is ",size);
    size++;
    cy.log("totalChartItems is ",size);
    cy.get('.insertNewChartItem').eq(0).click({force:true});
    cy.wait(2000);
    cy.get('.chartitem').its('length').then((newsize)=>{
        cy.log("new chart items length is ",newsize);
    })
})

size returned here is 3, But newsize returns me 8. Is this a cypress bug?


问:
Second best solution to an assignmentproblem using the Hungarian Algorithm
For finding the best solution in the assignment problem it's easy to use the Hungarian Algorithm.
For example:

```<code>A |  3  4  2
B |  8  9  1
C |  7  9  5
</code>```

When using the Hungarian Algorithm on this you become:

```<code>A |  0  0  1
B |  5  5  0
C |  0  1  0
</code>```

Which means A gets assigned to 'job' 2, B to job 3 and C to job 1.
However, I want to find the second best solution, meaning I want the best solution with a cost strictly greater that the cost of the optimal solution. According to me I just need to find the assignment with the minimal sum in the last matrix without it being the same as the optimal. I could do this by just searching in a tree (with pruning) but I'm worried about the complexity (being O(n!)). Is there any efficient method for this I don't know about?

I was thinking about a search in which I sort the rows first and then greedily choose the lowest cost first assuming most of the lowest costs will make up for the minimal sum + pruning. But assuming the Hungarian Algorithm can produce a matrix with a lot of zero's, the complexity is terrible again...

答:
In r there is now an implementation of Murty's algorithm in the muRty package.

CRAN

GitHub

It covers:

Optimization in both minimum and maximum direction;

output by rank (similar to dense rank in SQL), and

the use of either Hungarian algorithm (as implemented in clue) or linear programming (as implemented in lpSolve) for solving the initial assignment(s).

Disclaimer: I'm the author of the package.

Body:
For finding the best solution in the assignment problem it's easy to use the Hungarian Algorithm.
For example:

A |  3  4  2
B |  8  9  1
C |  7  9  5

When using the Hungarian Algorithm on this you become:

A |  0  0  1
B |  5  5  0
C |  0  1  0

Which means A gets assigned to 'job' 2, B to job 3 and C to job 1.
However, I want to find the second best solution, meaning I want the best solution with a cost strictly greater that the cost of the optimal solution. According to me I just need to find the assignment with the minimal sum in the last matrix without it being the same as the optimal. I could do this by just searching in a tree (with pruning) but I'm worried about the complexity (being O(n!)). Is there any efficient method for this I don't know about?

I was thinking about a search in which I sort the rows first and then greedily choose the lowest cost first assuming most of the lowest costs will make up for the minimal sum + pruning. But assuming the Hungarian Algorithm can produce a matrix with a lot of zero's, the complexity is terrible again...


问:
IE8 window size problem
I'm using this javascript code :

```<code>function openQueryWindow(val)
{
    var wName       = "....";
    var srcHeight = screen.Height - 100;
    var srcWeight = screen.width  - 100;
    var dLeft = 50
    var dTop=25
    var sFile=".....";
    window.open(sFile,wName,"scrollbars=1,location=0,status=0,menubar=0,toolbar=0,directories=0,resizable=0,width=" + srcWeight + ",height=" + srcHeight + ",top="+dTop+",left="+dLeft+",alwaysRaised")
}
</code>```

this code works in pop-up window in IE7 but doesn't work in IE8 and the pop-up window seems uncontrollable! How to solve this?

答:
You can force IE8 to render HTML as IE7 does...
add this in  as close to opening  tag as possible

```<code><meta http-equiv="X-UA-Compatible" content="IE=7" />
</code>```

here full article

Title: IE8 window size problem

Body:
I'm using this javascript code :

function openQueryWindow(val)
{
    var wName       = "....";
    var srcHeight = screen.Height - 100;
    var srcWeight = screen.width  - 100;
    var dLeft = 50
    var dTop=25
    var sFile=".....";
    window.open(sFile,wName,"scrollbars=1,location=0,status=0,menubar=0,toolbar=0,directories=0,resizable=0,width=" + srcWeight + ",height=" + srcHeight + ",top="+dTop+",left="+dLeft+",alwaysRaised")
}

this code works in pop-up window in IE7 but doesn't work in IE8 and the pop-up window seems uncontrollable! How to solve this?

Body:
You can force IE8 to render HTML as IE7 does...
add this in  as close to opening  tag as possible

<meta http-equiv="X-UA-Compatible" content="IE=7" />

here full article


问:
Implementing from trait and specialization
According to the specialization RFC, I should be able to have multiple impls of the same trait on a struct by specifying one as default.

I have the code:

#![feature(specialization)]
struct A(u32);

trait Dummy {}

impl<T> From<T> for A
where
    T: Into<u32>,
{
    default fn from(item: T) -> Self {
        A(item.into())
    }
}

impl<T> From<T> for A
where
    T: Dummy,
{
    fn from(item: T) -> Self {
        A(2)
    }
}
```

Even though one of the implementations is default, the compiler still tells me that the two are conflicting implementations.

答:
Your second implementation is not a specialization of the first. It's an alternative implementation that conflicts with the first.

Specialization requires that all types matching your second impl also match your first impl. In other words the bounds of your specialization need to be a strict subset of the bounds of the default implementation. From the RFC:

This RFC proposes a design for specialization, which permits multiple impl blocks to apply to the same type/trait, so long as one of the blocks is clearly "more specific" than the other.

Changing your trait definition to

```<code>trait Dummy: Into<u32> {}
</code>```

makes your code compile.

Check out https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md for more details.

Body:
According to the specialization RFC, I should be able to have multiple impls of the same trait on a struct by specifying one as default.

I have the code:

#![feature(specialization)]
struct A(u32);

trait Dummy {}

impl<T> From<T> for A
where
    T: Into<u32>,
{
    default fn from(item: T) -> Self {
        A(item.into())
    }
}

impl<T> From<T> for A
where
    T: Dummy,
{
    fn from(item: T) -> Self {
        A(2)
    }
}

Even though one of the implementations is default, the compiler still tells me that the two are conflicting implementations.

Body:
Your second implementation is not a specialization of the first. It's an alternative implementation that conflicts with the first.

Specialization requires that all types matching your second impl also match your first impl. In other words the bounds of your specialization need to be a strict subset of the bounds of the default implementation. From the RFC:

This RFC proposes a design for specialization, which permits multiple impl blocks to apply to the same type/trait, so long as one of the blocks is clearly "more specific" than the other.

Changing your trait definition to

trait Dummy: Into<u32> {}

makes your code compile.

Check out https://github.com/rust-lang/rfcs/blob/master/text/1210-impl-specialization.md for more details.