问:
How to get optional result in insert statements with Doobie?
I have an optional insert query:

```<code>val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"
</code>```

Running this query with:

```<code>q.update.withUniqueGeneratedKeys[Option[Long]]("id")
</code>```

fails with

Result set exhausted: more rows expected

then condition is false.

How to get Optional[Long] result from insert statements with Doobie?

UPD

.withGeneratedKeys[Long]("id") gives just Long in for comprehension

```<code>val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"
for {
  id <- q.update.withGeneratedKeys[Long]("id")   // id is long
  _ <- if (<id is present>) <some other inserts> else <nothing>
} yield id
</code>```

How to check id?

答:
As @Thilo commented, you can use the use withGeneratedKeys which gives you back a Stream[F, Long] (where F is your effect type)

val result = q.update.withGeneratedKeys[Long]("id")
```

Here is the doc.

Body:
I have an optional insert query:

val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"

Running this query with:

q.update.withUniqueGeneratedKeys[Option[Long]]("id")

fails with

Result set exhausted: more rows expected

then condition is false.

How to get Optional[Long] result from insert statements with Doobie?

UPD

.withGeneratedKeys[Long]("id") gives just Long in for comprehension

val q = sql"insert into some_table (some_field) select 42 where ...(some condition)"
for {
  id <- q.update.withGeneratedKeys[Long]("id")   // id is long
  _ <- if (<id is present>) <some other inserts> else <nothing>
} yield id

How to check id?

Body:
As @Thilo commented, you can use the use withGeneratedKeys which gives you back a Stream[F, Long] (where F is your effect type)

val result = q.update.withGeneratedKeys[Long]("id")

Here is the doc.


来源: stackexchange

问:
Purpose of selecting a CRAN mirror when install.packages() in R?
Most CRAN packages are <100mb and are consistent across mirrors, hence speed and/or consistency would be unlikely candidates.

For context, an extremely simple terminal command like R -e 'install.packages("testthat")' errors with

```<code>Error in contrib.url(repos, "source") :
  trying to use CRAN without setting a mirror
Calls: install.packages -> contrib.url
Execution halted
</code>```

whereas most R users would expect that code to work, since they'll have run it from R scripts, and from the R interpreter (or rstudio).

What is the purpose of forcing mirror selection? (it may sound rhetorical but I am genuinely curious)

答:
Setting a CRAN mirror can explicitly tell R where to retrieve sources from.

Please choose a location close to you.

The above line, from https://cran.r-project.org/mirrors.html, hints that selecting a close mirror is wise. This is because it can increase speed for which you download as well as reducing stress on the CRAN servers. For information on how to do that, see this thread: How to select a CRAN mirror in R

Sure this could be programmed into it, but it is a simple enough step to get people more involved with their R setup.

ContentLicense: CC BY-SA 4.0

Body:
Most CRAN packages are <100mb and are consistent across mirrors, hence speed and/or consistency would be unlikely candidates.

For context, an extremely simple terminal command like R -e 'install.packages("testthat")' errors with

Error in contrib.url(repos, "source") :
  trying to use CRAN without setting a mirror
Calls: install.packages -> contrib.url
Execution halted

whereas most R users would expect that code to work, since they'll have run it from R scripts, and from the R interpreter (or rstudio).

What is the purpose of forcing mirror selection? (it may sound rhetorical but I am genuinely curious)


问:
how can I detect that option value has changed in wordpress?
I am working on a Wordpress plugin and I want to fire a different action based on each option value change. so how can I do that ?

Example:

```<code>$options = get_option('ACP_settings'); if $options['acp-select'] has changed from previous value than I want to fire different action based on selection
</code>```

Please note that $option['acp-select'] is retrieved from select/option html form and has following values for selection:'book','air','SW','HW' and etc....

I hope I have posted my question clearly.

thanks for help

答:
You can use wordpress hooks in the update_option() function.

In your case you can use updated_option or update_option_{$option} hooks.

The code for ACP_settings option would look like:

```<code>add_action( 'update_option_ACP_settings', function($old_value, $value, $option){

    if( $old_value !== $value ){
        // Your option was updated
        // Run your code here
    }

}, 10, 3 );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working on a Wordpress plugin and I want to fire a different action based on each option value change. so how can I do that ?

Example:

$options = get_option('ACP_settings'); if $options['acp-select'] has changed from previous value than I want to fire different action based on selection

Please note that $option['acp-select'] is retrieved from select/option html form and has following values for selection:'book','air','SW','HW' and etc....

I hope I have posted my question clearly.

thanks for help

Body:
You can use wordpress hooks in the update_option() function.

In your case you can use updated_option or update_option_{$option} hooks.

The code for ACP_settings option would look like:

add_action( 'update_option_ACP_settings', function($old_value, $value, $option){

    if( $old_value !== $value ){
        // Your option was updated
        // Run your code here
    }

}, 10, 3 );


问:
Pandas Merge and filter
I used merge to create a dataframe between 2 of my query's.
Now in the dataframe I want to put a filter on a column but I cannot get it to work. I am trying to add filter component date is null or blank.

```<code>    ##reading data from sql
    package = pd.read_sql(sql,con)
    component = pd.read_sql(sqla,con)

    ##doing the left join
    test2 = pd.merge(package,component, on = ['identifier','date'], how='left')

    ##shrinking the dataframe
    test3 = test2[['identifier_x']].copy()
</code>```

i've tried doing the below but cannot get it to work. Getting date_y not defined. I also tried with just date, as when I merge my dataframes the like columns get labelled x and y.

```<code> test2 = pd.merge(package,component, on = ['identifier','date'], how='left'), component.query(date_y == '')
</code>```

Now trying:

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2.query('date_y == \'\'')
</code>```

And

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2[test2.date_y == '']
</code>```

Also tried:

```<code>test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2 = test2.date_y == ''
</code>```

Sample data:

```<code>+------------+------------+------------+------------+
|   date_x   | identifier |   date_y   | identifier |
+------------+------------+------------+------------+
| 13/03/2019 | 3582191409 | 13/03/2019 | 3582191410 |
| 13/03/2019 | 3582191289 | 13/03/2019 | 3582191290 |
| 13/03/2019 | 3582190137 | 13/03/2019 | 3582190138 |
| 13/03/2019 | 3582185931 | 13/03/2019 | 3582185930 |
| 13/03/2019 | 3582184503 |            | 3582184502 |
| 13/03/2019 | 3582195631 |            | 3582195632 |
| 13/03/2019 | 3582191374 |            | 3582191373 |
| 13/03/2019 | 3582185917 |            | 3582185916 |
| 13/03/2019 | 3582185863 |            | 3582185862 |
+------------+------------+------------+------------+
</code>```

Im trying to filter date y = blanks

答:
You're trying to filter strings, but it's not a string - it's a empty datetime.date object. You need to filter by nonempty date object.

You can create a second dataframe as string type and check then:

str_test2 = test2.astype(str)
filtered_test2 = test2[str_test2['date_y'] != '']
```

See more possible solutions here

Title: Pandas Merge and filter

Body:
I used merge to create a dataframe between 2 of my query's.
Now in the dataframe I want to put a filter on a column but I cannot get it to work. I am trying to add filter component date is null or blank.

    ##reading data from sql
    package = pd.read_sql(sql,con)
    component = pd.read_sql(sqla,con)

    ##doing the left join
    test2 = pd.merge(package,component, on = ['identifier','date'], how='left')

    ##shrinking the dataframe
    test3 = test2[['identifier_x']].copy()

i've tried doing the below but cannot get it to work. Getting date_y not defined. I also tried with just date, as when I merge my dataframes the like columns get labelled x and y.

 test2 = pd.merge(package,component, on = ['identifier','date'], how='left'), component.query(date_y == '')

Now trying:

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2.query('date_y == \'\'')

And

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2[test2.date_y == '']

Also tried:

test2 = pd.merge(package,component, on = ['identifier','date'], how='left')
test2 = test2.date_y == ''

Sample data:

+------------+------------+------------+------------+
|   date_x   | identifier |   date_y   | identifier |
+------------+------------+------------+------------+
| 13/03/2019 | 3582191409 | 13/03/2019 | 3582191410 |
| 13/03/2019 | 3582191289 | 13/03/2019 | 3582191290 |
| 13/03/2019 | 3582190137 | 13/03/2019 | 3582190138 |
| 13/03/2019 | 3582185931 | 13/03/2019 | 3582185930 |
| 13/03/2019 | 3582184503 |            | 3582184502 |
| 13/03/2019 | 3582195631 |            | 3582195632 |
| 13/03/2019 | 3582191374 |            | 3582191373 |
| 13/03/2019 | 3582185917 |            | 3582185916 |
| 13/03/2019 | 3582185863 |            | 3582185862 |
+------------+------------+------------+------------+

Im trying to filter date y = blanks

Body:
You're trying to filter strings, but it's not a string - it's a empty datetime.date object. You need to filter by nonempty date object.

You can create a second dataframe as string type and check then:

str_test2 = test2.astype(str)
filtered_test2 = test2[str_test2['date_y'] != '']

See more possible solutions here


问:
How to format XPath for schedule task on event?
I have written a script that i want to trigger any time a user is granted Domain Admin rights. I canno trigger this through event viewer as our Domain Controller is running on Server Core and the option to Attach Task to this Event is grayed out when you connect to Event Viewer remotely. Trying to use SCHTASKS I enter the following:

```<code>SCHTASKS /Create /TN "Event Monitor" /TR $command /SC ONEVENT /RL Highest /RU $cred.Username /RP $password /EC ScriptEvents /MO *[System/EventID=4728]
</code>```

The error I get is The specified channel could not be found. I can't figure out what I need to enter for the XPath for it to trigger properly. Could someone help out? Here is the contents of the Event:

```<code> <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-54784994-a5ba-3e3b0328c30d}" />
  <EventID>4728</EventID>
  <Version>0</Version>
  <Level>0</Level>
  <Task>13826</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2019-05-24T12:11:54.847043800Z" />
  <EventRecordID>1050228</EventRecordID>
  <Correlation />
  <Execution ProcessID="552" ThreadID="1580" />
  <Channel>Security</Channel>
</code>```

答:
For those looking in the future, the problem was in both the formatting of the /MO switch and in the /EC switch. Here is how I solved it:</p>

```<code>SCHTASKS /Create /TN "Event Monitor" /TR $command /SC ONEVENT /RL Highest /RU $cred.Username /RP $password /EC Security /MO "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4728]]"
</code>```

Body:
I have written a script that i want to trigger any time a user is granted Domain Admin rights. I canno trigger this through event viewer as our Domain Controller is running on Server Core and the option to Attach Task to this Event is grayed out when you connect to Event Viewer remotely. Trying to use SCHTASKS I enter the following:

SCHTASKS /Create /TN "Event Monitor" /TR $command /SC ONEVENT /RL Highest /RU $cred.Username /RP $password /EC ScriptEvents /MO *[System/EventID=4728]

The error I get is The specified channel could not be found. I can't figure out what I need to enter for the XPath for it to trigger properly. Could someone help out? Here is the contents of the Event:

 <System>
  <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-54784994-a5ba-3e3b0328c30d}" />
  <EventID>4728</EventID>
  <Version>0</Version>
  <Level>0</Level>
  <Task>13826</Task>
  <Opcode>0</Opcode>
  <Keywords>0x8020000000000000</Keywords>
  <TimeCreated SystemTime="2019-05-24T12:11:54.847043800Z" />
  <EventRecordID>1050228</EventRecordID>
  <Correlation />
  <Execution ProcessID="552" ThreadID="1580" />
  <Channel>Security</Channel>

Body:
For those looking in the future, the problem was in both the formatting of the /MO switch and in the /EC switch. Here is how I solved it:

SCHTASKS /Create /TN "Event Monitor" /TR $command /SC ONEVENT /RL Highest /RU $cred.Username /RP $password /EC Security /MO "*[System[Provider[@Name='Microsoft-Windows-Security-Auditing'] and EventID=4728]]"


问:
Exclude all 0s in foreach count
I want to update all my custom_field by giving specific number to each of my posts. Problem : I don't want to add numbers with 0 inside.

```<code>$i = 1; // Start from 1

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++ );
        // $i++ will be the specific number for each my post.

    endwhile;
endif;
</code>```

Now, my post 1 has the_custom_field 1, my post 2 has the_custom_field 2.... my post 10 has the_custom_field 10

But it should be this way :

the_custom_field of post1 should be 1

the_custom_field of post2 should be 2

the_custom_field of post3 should be 3

...

the_custom_field of post10 should be 11

the_custom_field of post11 should be 12
etc

答:
```<code><?php

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++);
        while (strpos(strval($i),'0') !== false):
            $i++;
        endwhile;

    endwhile;
endif;
</code>```

Well, once we assign the ID, we run a while loop afterwards till the time we get a value which doesn't contain the 0.

Title: Exclude all 0s in foreach count

Body:
I want to update all my custom_field by giving specific number to each of my posts. Problem : I don't want to add numbers with 0 inside.

$i = 1; // Start from 1

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++ );
        // $i++ will be the specific number for each my post.

    endwhile;
endif;

Now, my post 1 has the_custom_field 1, my post 2 has the_custom_field 2.... my post 10 has the_custom_field 10

But it should be this way :

the_custom_field of post1 should be 1

the_custom_field of post2 should be 2

the_custom_field of post3 should be 3

...

the_custom_field of post10 should be 11

the_custom_field of post11 should be 12
etc

Body:
<?php

if ($ajax_query->have_posts()) :
    while ($ajax_query->have_posts()) :
        $ajax_query->the_post();

        update_post_meta( get_the_ID(), 'the_custom_field', $i++);
        while (strpos(strval($i),'0') !== false):
            $i++;
        endwhile;

    endwhile;
endif;

Well, once we assign the ID, we run a while loop afterwards till the time we get a value which doesn't contain the 0.


问:
Using Powershell to remove non present network adapters
I'm trying to automate via PowerShell a number of time consuming tasks that I have to preform to make a new VM template, one of which is removing all of the NICs from the VM and cleaning up the Device Manager of non present devices.

After removing the NICs from the VM, I've tried using the following code snippets, which do the same thing, to clean up Device Manager.

```<code>wmic nic where "(servicename is null)" delete
</code>```

```<code>gwmi win32_networkadapter | ?{$_.ServiceName -eq $null} | rwmi
</code>```

In both cases I receive the error "Provider is not capable of the attempted operation". Reviewing the event logs for WMI-Activity didn't seem to help: ResultCode = 0x80041024; PossibleCause = Unknown.

Has anyone be able to do something similar that removes the non present devices or is able to find an issue with the above commands?

EDIT: I've tried using DevCon to remove the device, but it seems to only work with present devices. I'm now combing through the registry to see if there is a specific key or set of keys that if removed would remove the NIC from Device Manager.

答:
This one bugged me for a while, and I came up with a bit more of manual approach, but it works, so hopefully this will help others:

1) first make sure your list off devices you're about to purge are correct:

```<code>Get-PnpDevice -class net | ? Status -eq Unknown | Select FriendlyName,InstanceId
</code>```

2) If you're happy with the list of Get-NetAdapters you're about to Kaibosh, run the following:

```<code>$Devs = Get-PnpDevice -class net | ? Status -eq Unknown | Select FriendlyName,InstanceId

ForEach ($Dev in $Devs) {
    Write-Host "Removing $($Dev.FriendlyName)" -ForegroundColor Cyan
    $RemoveKey = "HKLM:\SYSTEM\CurrentControlSet\Enum\$($Dev.InstanceId)"
    Get-Item $RemoveKey | Select-Object -ExpandProperty Property | %{ Remove-ItemProperty -Path $RemoveKey -Name $_ -Verbose }
}
Write-Host "Done.  Please restart!" -ForegroundColor Green
</code>```

NOTE: Your list of adapters at step 1 must ONLY contain adapters you want to purge.  If you have extras in there, adjust the filter (? Status -eq XXX, eg: ? FriendlyName -like "Broadcom*") accordingly!

Body:
I'm trying to automate via PowerShell a number of time consuming tasks that I have to preform to make a new VM template, one of which is removing all of the NICs from the VM and cleaning up the Device Manager of non present devices.

After removing the NICs from the VM, I've tried using the following code snippets, which do the same thing, to clean up Device Manager.

wmic nic where "(servicename is null)" delete

gwmi win32_networkadapter | ?{$_.ServiceName -eq $null} | rwmi

In both cases I receive the error "Provider is not capable of the attempted operation". Reviewing the event logs for WMI-Activity didn't seem to help: ResultCode = 0x80041024; PossibleCause = Unknown.

Has anyone be able to do something similar that removes the non present devices or is able to find an issue with the above commands?

EDIT: I've tried using DevCon to remove the device, but it seems to only work with present devices. I'm now combing through the registry to see if there is a specific key or set of keys that if removed would remove the NIC from Device Manager.

Body:
This one bugged me for a while, and I came up with a bit more of manual approach, but it works, so hopefully this will help others:

1) first make sure your list off devices you're about to purge are correct:

Get-PnpDevice -class net | ? Status -eq Unknown | Select FriendlyName,InstanceId

2) If you're happy with the list of Get-NetAdapters you're about to Kaibosh, run the following:

$Devs = Get-PnpDevice -class net | ? Status -eq Unknown | Select FriendlyName,InstanceId

ForEach ($Dev in $Devs) {
    Write-Host "Removing $($Dev.FriendlyName)" -ForegroundColor Cyan
    $RemoveKey = "HKLM:\SYSTEM\CurrentControlSet\Enum\$($Dev.InstanceId)"
    Get-Item $RemoveKey | Select-Object -ExpandProperty Property | %{ Remove-ItemProperty -Path $RemoveKey -Name $_ -Verbose }
}
Write-Host "Done.  Please restart!" -ForegroundColor Green

NOTE: Your list of adapters at step 1 must ONLY contain adapters you want to purge.  If you have extras in there, adjust the filter (? Status -eq XXX, eg: ? FriendlyName -like "Broadcom*") accordingly!


问:
Task Scheduler failed to start. Additional Data: Error Value: 2147943726
I am using windows 10 task scheduler to run tasks that require me using my personal user account (its necessary to use my user and not system user because of permission issues - I am part of an organization).
In windows 7 computers everything worked fine but as we upgraded to win 10 I cant run the tasks without using the System user (as mentioned before it doesn't work because of permissions).
I get the following error

Additional Data: Error Value: 2147943726

all I found online was an advice to use the system user other then that nothing :-(

please save my day.

here is a picture of the settings that I want to change.

答:
We had the same problem with Windows 2012 server machines being cloned on a vmware ESX server. The clone/deployment script used sysprep to make every machine individual. With this the users assigned with the scheduled task got screwed up. Our solution was to re-generate the task via batchfile during startup of the machine:</p>

```<code>REM Delete the task:
SCHTASKS /Delete /TN "NameOfScheduledTask" /f

REM Create a task to run every 5 minutes
SCHTASKS /Create /TN NameOfScheduledTask /SC MINUTE /MO 5 /TR "some command for task" /NP
</code>```

Body:
We had the same problem with Windows 2012 server machines being cloned on a vmware ESX server. The clone/deployment script used sysprep to make every machine individual. With this the users assigned with the scheduled task got screwed up. Our solution was to re-generate the task via batchfile during startup of the machine:

REM Delete the task:
SCHTASKS /Delete /TN "NameOfScheduledTask" /f

REM Create a task to run every 5 minutes
SCHTASKS /Create /TN NameOfScheduledTask /SC MINUTE /MO 5 /TR "some command for task" /NP


问:
MySQL: using calculated counter column as key for sub-query
Sorry, long pre-history, but it is needed to clarify the question.

In my org the computers have names like CNT30[0-9]{3}[1-9a-z], for example cnt300021 or cnt30253a.

Last symbol is a "qualifier", so single workplace may have equally named computers assigned to it, distinguished by this qualifier. For example cnt300021 may mean desktop computer on workplace #002, and cnt30002a may mean notebook assigned for same workplace. Workplaces are "virtual" and their existence made just for our (IT dept) convenience.

Each dept have its own unique range [0-9]{3}. For example, computers of accounting have names starting cnt302751 upto cnt30299z which gives them 25 unique workplaces max, with up to 35 computers per workplace. (IRL most users have one desktop PC, much lesser have desktop and notebook, and only 2 or 3 technicians have more than one notebook at their disposal).

Recently, doing some inventory of computers' passports (unsure about a term: a paper, which means for computer the same, what a passport means for human), I found that there some holes in sequential numbering. For example, we have cnt302531 and cnt302551, but have no cnt302541, which means that there's no workplace #254.

What I want to do? I want to find these gaps without manual searching. For this I need a cycle from 1 to MaxComp=664 (no more workplace numbers assigned yet)

That's what I could write using some pseudo-SQL-BASIC:

for a=0 to MaxComp
  a$="CNT30"+right(a+1000,3)
'comparing only 8 leftmost characters, ignoring 9th one - the qualifier
  b$=(select name from table where left(name,8) like a$)
  print a$;b$
next a
```

<p>That code should give me two colummns: possible names and existing ones. </p>

<p>But I can't figure out how to implement this in SQL-query. What I tried:</p>

<pre class="lang-sql prettyprint-override"><code># because of qualifier there may be several computers with same
# 8 leftmost characters
select @cnum:=@cnum+1 as CompNum, group_concat(name separator ',')
# PCs are inventoried by OCS-NG Inventory software
  from hardware
  cross join (select @cnum:=0) cnt
  where left(hardware.name,8)=concat('CNT30',right(@cnum+1000,3))
  limit 100
</code>```

But this construct returns exactly one row. And I can't understand, if it is possible without using the stored procedures, and what I did wrong if it is possible?

答:
Found working path:

(at first I tried to use stored function)

CREATE FUNCTION `count_comps`(num smallint) RETURNS tinytext CHARSET utf8
BEGIN
    return (select group_concat(name separator ',')
        from hardware where left(hardware.name,8)=concat('CNT30',right(num+1000,3))
        );
END
```

<p>Then I tried hard to replicate function's results in subquery. And I did it! Note: the inner select returns exactly same results as function does </p>

<pre class="lang-sql prettyprint-override"><code># Starting point. May be INcreased to narrow the results list
set @cnum:=0;
select
    @cnum:=@cnum+1 as CompNum,
    concat('CNT30',right(@cnum+1000,3)) as CalcNum,
# this
    count_comps(@cnum) as hwns,
# and this gives equal results
    (select group_concat(name separator ',')
        from hardware where left(name,8)=calcnum
        ) hwn2
    from hardware
# no more dummy tables here
# Ending point. May be DEcreased to narrow the results list
  where @cnum<665;
</code>```

So, the wrong part of "classical" approach was the usage of dummy table, which seems to be not necessary.

Partial results example (starting set @cnum:=479;, finishing where @cnum<530;):

CompNum, CalcNum, hwns, hwn2
'488', 'CNT30488', 'CNT304881', 'CNT304881'
'489', 'CNT30489', 'CNT304892', 'CNT304892'
'490', 'CNT30490', 'CNT304901,CNT304902,CNT304903', CNT304901,CNT304902,CNT304903'
'491', 'CNT30491', NULL, NULL
'492', 'CNT30492', NULL, NULL
'493', 'CNT30493', 'CNT304932', 'CNT304932'
'494', 'CNT30494', 'CNT304941', 'CNT304941'

I found that there no workplaces #491 and #492. On next adding the PCs for the 'October Region' dept (range 480-529), at least two of new PCs will get names CNT304911 and CNT304921, filling this gap.

Body:
Sorry, long pre-history, but it is needed to clarify the question.

In my org the computers have names like CNT30[0-9]{3}[1-9a-z], for example cnt300021 or cnt30253a.

Last symbol is a "qualifier", so single workplace may have equally named computers assigned to it, distinguished by this qualifier. For example cnt300021 may mean desktop computer on workplace #002, and cnt30002a may mean notebook assigned for same workplace. Workplaces are "virtual" and their existence made just for our (IT dept) convenience.

Each dept have its own unique range [0-9]{3}. For example, computers of accounting have names starting cnt302751 upto cnt30299z which gives them 25 unique workplaces max, with up to 35 computers per workplace. (IRL most users have one desktop PC, much lesser have desktop and notebook, and only 2 or 3 technicians have more than one notebook at their disposal).

Recently, doing some inventory of computers' passports (unsure about a term: a paper, which means for computer the same, what a passport means for human), I found that there some holes in sequential numbering. For example, we have cnt302531 and cnt302551, but have no cnt302541, which means that there's no workplace #254.

What I want to do? I want to find these gaps without manual searching. For this I need a cycle from 1 to MaxComp=664 (no more workplace numbers assigned yet)

That's what I could write using some pseudo-SQL-BASIC:

for a=0 to MaxComp
  a$="CNT30"+right(a+1000,3)
'comparing only 8 leftmost characters, ignoring 9th one - the qualifier
  b$=(select name from table where left(name,8) like a$)
  print a$;b$
next a

That code should give me two colummns: possible names and existing ones.

But I can't figure out how to implement this in SQL-query. What I tried:

# because of qualifier there may be several computers with same
# 8 leftmost characters
select @cnum:=@cnum+1 as CompNum, group_concat(name separator ',')
# PCs are inventoried by OCS-NG Inventory software
  from hardware
  cross join (select @cnum:=0) cnt
  where left(hardware.name,8)=concat('CNT30',right(@cnum+1000,3))
  limit 100

But this construct returns exactly one row. And I can't understand, if it is possible without using the stored procedures, and what I did wrong if it is possible?

Body:
Found working path:

(at first I tried to use stored function)

CREATE FUNCTION `count_comps`(num smallint) RETURNS tinytext CHARSET utf8
BEGIN
    return (select group_concat(name separator ',')
        from hardware where left(hardware.name,8)=concat('CNT30',right(num+1000,3))
        );
END

Then I tried hard to replicate function's results in subquery. And I did it! Note: the inner select returns exactly same results as function does

# Starting point. May be INcreased to narrow the results list
set @cnum:=0;
select
    @cnum:=@cnum+1 as CompNum,
    concat('CNT30',right(@cnum+1000,3)) as CalcNum,
# this
    count_comps(@cnum) as hwns,
# and this gives equal results
    (select group_concat(name separator ',')
        from hardware where left(name,8)=calcnum
        ) hwn2
    from hardware
# no more dummy tables here
# Ending point. May be DEcreased to narrow the results list
  where @cnum<665;

So, the wrong part of "classical" approach was the usage of dummy table, which seems to be not necessary.

Partial results example (starting set @cnum:=479;, finishing where @cnum<530;):

CompNum, CalcNum, hwns, hwn2
'488', 'CNT30488', 'CNT304881', 'CNT304881'
'489', 'CNT30489', 'CNT304892', 'CNT304892'
'490', 'CNT30490', 'CNT304901,CNT304902,CNT304903', CNT304901,CNT304902,CNT304903'
'491', 'CNT30491', NULL, NULL
'492', 'CNT30492', NULL, NULL
'493', 'CNT30493', 'CNT304932', 'CNT304932'
'494', 'CNT30494', 'CNT304941', 'CNT304941'

I found that there no workplaces #491 and #492. On next adding the PCs for the 'October Region' dept (range 480-529), at least two of new PCs will get names CNT304911 and CNT304921, filling this gap.


问:
Android emulator screen fills up only some fraction part of actual android emulator screen
First thing first,

Using Android Studio 2.3.3

Problem:

My emulator screen is covering the only partial amount of screen available for emulator, i.e top left of the emulator and rest part is just a black screen.

See the pic I have attached.

Things I tried:

1) Restarting emulator

2) trying different emulator

3) changing pixels, density of emulator device,

4) run -> edit configuration ..blah blah blah...

Nothing helped!!

Note:

My issue is not emulator's size but effective screen size.

please help if somebody could have come across this issue :(

IMPORTANT EDIT: I guess, this issue has something to do with the laptop I am using, DELL Latitude, touch screen (14-inch QHD touch display (2,560×1,440 resolution).
Because the same emulator works properly in other display laptops.

答:
Best and simplest way to do it on Windows 10:

Close your Android Emulator if it is open

Right-click desktop

Click Display Settings

Set Scale and layout to 100%

Open Android Emulator

Revert your Scale and layout to the (Recommended) percentage


问:
How to Copy a complete XML-file in laravel from public to storage folder
In my Laravel project I would like to copy a .xml file named config.xml from the public/xml folder to the storage/Admin/webapp folder.(The storage is symlinked) It seems like I can´t get it to work. I always get a "Cannot create Root directory" exception.

If i dd the variables i get the results i want to see. I tried several ways to get it right by changing / to \ or deleting and adding some / or using several Commands from laravel like asset etc. It seems like i can get the .xml file and even dispaly its content with dd but i get exceptions copying it afterwards? There is a double Root. Two times C:\ but i dont know where its comming from.

I would expect a copy of the config.xml file from the public folder in my storage folder as config.xml file

```<code>public function copyXml()
  {
    //Create Filepath and get XML File
    $content = file_get_contents(public_path('/xml/config.xml'));

    //Set destination path
    $destination = storage_path('/Admin/webapp');

    //Copy xml-file
    Storage::put($content, $destination);
 }
</code>```

答:
By default local disk looks into project_root_folder/storage/app/. You can't access and manipulate files in public folder through Storage facade.

```<code>//Get file content from public path
$content = file_get_contents(public_path('xml/config.xml'));

//Set destination path
$destination = storage_path('admin/webapp/config.xml');

//Put content in the destination path
Storage::put($destination, $content);
</code>```

Body:
In my Laravel project I would like to copy a .xml file named config.xml from the public/xml folder to the storage/Admin/webapp folder.(The storage is symlinked) It seems like I can´t get it to work. I always get a "Cannot create Root directory" exception.

If i dd the variables i get the results i want to see. I tried several ways to get it right by changing / to \ or deleting and adding some / or using several Commands from laravel like asset etc. It seems like i can get the .xml file and even dispaly its content with dd but i get exceptions copying it afterwards? There is a double Root. Two times C:\ but i dont know where its comming from.

I would expect a copy of the config.xml file from the public folder in my storage folder as config.xml file

public function copyXml()
  {
    //Create Filepath and get XML File
    $content = file_get_contents(public_path('/xml/config.xml'));

    //Set destination path
    $destination = storage_path('/Admin/webapp');

    //Copy xml-file
    Storage::put($content, $destination);
 }

Body:
By default local disk looks into project_root_folder/storage/app/. You can't access and manipulate files in public folder through Storage facade.

//Get file content from public path
$content = file_get_contents(public_path('xml/config.xml'));

//Set destination path
$destination = storage_path('admin/webapp/config.xml');

//Put content in the destination path
Storage::put($destination, $content);


问:
How to switch to master and pull latest changes with one shortcut in IntelliJ
I'd like to have single keyboard shortcut do to two things in IntelliJ IDEA:

switch to master branch in Git regardless of current branch (git checkout master)

pull latest changes from origin/master (git pull --rebase --autostash origin master)

Currently I have both configured as External Tool and I have separate shortcuts attached. How can I join these commands so I can prepare my local master branch for further development within one keyboard shortcut?

Or maybe there is a way to do the same without using External Tool feature?

答:
There is no UI action to do what you need, unfortunately. See https://youtrack.jetbrains.com/issue/IDEA-171649 and related.

As a workaround, you can build a git alias (as mentioned in other replies) and use it as an external tool with a shortcut.


问:
How to convert array of objects to object containing that data
I need to convert an array of objects to an object of objects in JavaScript.
The ID of the book should be the ID of each object from the array.

Array that I have:

```<code>[{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]
</code>```

Object that I need:

```<code> {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}
</code>```

答:
You could use reduce:

const arr = [{
  "author": "aaaa",
  "catid": 22,
  "id": 23,
  "name": "Book a",
  "size": 56658
}, {
  "author": "bbbb",
  "catid": 22,
  "id": 24,
  "logo": "logo",
  "name": "Book b",
  "size": 73386
}, {
  "author": "cccc",
  "catid": 22,
  "id": 25,
  "logo": "logo",
  "name": "Book c",
  "size": 84777
}, {
  "author": "ddd",
  "catid": 22,
  "id": 26,
  "logo": "logo",
  "name": "Book d",
  "size": 105139
}]

const obj = arr.reduce((a, {id, ...obj}) => (a[id] = obj, a), {})

console.log(obj)```

Reduce will loop over each object in the array, and the code inside will append the object to the accumulator, by id and then return that as an object.

Body:
I need to convert an array of objects to an object of objects in JavaScript.
The ID of the book should be the ID of each object from the array.

Array that I have:

[{
   "author" : "cccc",
   "catid" : 22,
   "id" : 25,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }, {
   "author" : "ddd",
   "catid" : 22,
   "id" : 26,
   "logo" : "logo",
   "name" : "Book d",
   "size" : 105139
 }]

Object that I need:

 {
 "25":{
   "author" : "bbbb",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book b",
   "size" : 73386
 },
 "26":{
   "author" : "cccc",
   "catid" : 22,
   "logo" : "logo",
   "name" : "Book c",
   "size" : 84777
 }}

Body:
You could use reduce:

const arr = [{
  "author": "aaaa",
  "catid": 22,
  "id": 23,
  "name": "Book a",
  "size": 56658
}, {
  "author": "bbbb",
  "catid": 22,
  "id": 24,
  "logo": "logo",
  "name": "Book b",
  "size": 73386
}, {
  "author": "cccc",
  "catid": 22,
  "id": 25,
  "logo": "logo",
  "name": "Book c",
  "size": 84777
}, {
  "author": "ddd",
  "catid": 22,
  "id": 26,
  "logo": "logo",
  "name": "Book d",
  "size": 105139
}]

const obj = arr.reduce((a, {id, ...obj}) => (a[id] = obj, a), {})

console.log(obj)

Reduce will loop over each object in the array, and the code inside will append the object to the accumulator, by id and then return that as an object.


问:
Making Vega-Lite bar marks adjacent
I'm working on a bar plot in Vega-Lite (generated using Altair). Using the Vega-View API, I've written some code where users can select bars, which changes those bars' colors (along with doing some other stuff elsewhere in the application; the details aren't super important for this question).

My problem is this. Using the default continuousBandSize of 5, when zoomed out the bars seem to "overlap" each other horizontally.
Here's a screenshot of this problem.
This problem is resolvable by setting continuousBandSize to 1, but the problem then is that -- when you zoom in to the chart -- the bars become very thin and hard for users to select. (Furthermore, since I'm coloring the bars gray by default, they become hard to distinguish from the grid behind the visualization; and I'd prefer to keep the grid if I can.) Here's a screenshot of this problem.

Is it possible to make the bar marks in Vega-Lite adjacent at any zoom level? Or is this not feasible?

Prior research on this problem

The problem of bars being too thin is mentioned in an issue on Vega-Lite's GitHub page here, but that issue seems to address a different problem (of the bars going outside of the visualization).

I've looked into using padding, paddingInner, and paddingOuter (as mentioned in the Vega-Lite documentation and in the answer to this question), with no success. The problem of increasing sizes causing bars to overlap is also brought up in an (unanswered) comment on this answer.

Example Vega-Lite Specification

An example specification showing a subset of the plot I'm working on (with continuousBandSize set to 1 to show the "thin-bar" problem) is available in the Vega Editor here (apologies for the long URL). As mentioned above, if you zoom in too far with continuousBandSize set to 1, the gray bars become very thin and hard to see. And if you set continuousBandSize to something like 2 or above and zoom out too far, the bars start to overlap each other (this is demonstrated by the blue bar starting to get slightly "covered" by the gray bar to its right -- this isn't super visible here since this is only a subset of the full plot, but the problem is a lot clearer when there are ~500 bars).

Thanks!

答: I ran into the same issue. FWIW, the documentation does specify this behavior, although it took me a while to find it: effect of datatype on xaxis scales</p>

Title: Making Vega-Lite bar marks adjacent

Body:
I'm working on a bar plot in Vega-Lite (generated using Altair). Using the Vega-View API, I've written some code where users can select bars, which changes those bars' colors (along with doing some other stuff elsewhere in the application; the details aren't super important for this question).

My problem is this. Using the default continuousBandSize of 5, when zoomed out the bars seem to "overlap" each other horizontally.
Here's a screenshot of this problem.
This problem is resolvable by setting continuousBandSize to 1, but the problem then is that -- when you zoom in to the chart -- the bars become very thin and hard for users to select. (Furthermore, since I'm coloring the bars gray by default, they become hard to distinguish from the grid behind the visualization; and I'd prefer to keep the grid if I can.) Here's a screenshot of this problem.

Is it possible to make the bar marks in Vega-Lite adjacent at any zoom level? Or is this not feasible?

Prior research on this problem

The problem of bars being too thin is mentioned in an issue on Vega-Lite's GitHub page here, but that issue seems to address a different problem (of the bars going outside of the visualization).

I've looked into using padding, paddingInner, and paddingOuter (as mentioned in the Vega-Lite documentation and in the answer to this question), with no success. The problem of increasing sizes causing bars to overlap is also brought up in an (unanswered) comment on this answer.

Example Vega-Lite Specification

An example specification showing a subset of the plot I'm working on (with continuousBandSize set to 1 to show the "thin-bar" problem) is available in the Vega Editor <a href="https://vega.github.io/editor/#[encoded data, 12640 characters]" rel="nofollow noreferrer">here (apologies for the long URL). As mentioned above, if you zoom in too far with continuousBandSize set to 1, the gray bars become very thin and hard to see. And if you set continuousBandSize to something like 2 or above and zoom out too far, the bars start to overlap each other (this is demonstrated by the blue bar starting to get slightly "covered" by the gray bar to its right -- this isn't super visible here since this is only a subset of the full plot, but the problem is a lot clearer when there are ~500 bars).

Thanks!


问:
Assign new data frame values with vapply
I'm trying to dynamically update cells in a data frame with an apply-type function. Here's the reproducible example:

```<code>demo.df <- structure(list(node_id = 1:21, depth = c(4, 3, 2, 1, 0, 0,
1, 0, 0, 2, 1, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0), x_position = c(NA, NA,
NA, NA, 1, 2, NA, 3, 4, NA, NA, 5, 6, NA, 7, 8, NA, NA, 9,10, 11), X1
= 1:21, X2 = c(2L, 3L, 4L, 5L, NA, NA, 8L, NA, NA, 11L, 12L, NA, NA,
15L, NA, NA, 18L, 19L, NA, NA, NA), X3 = c(17L, 10L, 7L, 6L, NA, NA,
9L, NA, NA, 14L, 13L, NA, NA, 16L, NA, NA, 21L, 20L, NA, NA, NA)),
class = "data.frame", row.names = c(1L, 2L, 4L, 8L, 16L, 17L, 9L, 18L,
19L, 5L, 10L, 20L, 21L, 11L, 22L, 23L, 3L, 6L, 12L, 13L, 7L))

node_sequence <- c(4,7,11,14,18,3,10,17,2,1)
</code>```

I want to update x_position based on the mean of the following columns, going through the rows in a specified order, so

```<code>x_spot <- function (x)
 {mean(demo.df$x_position[which(demo.df$node_id%in%demo.df[x,c(4:6)])],
 na.rm = TRUE)
 }
</code>```

This clumsy code gets the right result:

```<code>demo.df$x_position[node_sequence[1]] <- x_spot(node_sequence[1])
demo.df$x_position[node_sequence[2]] <- x_spot(node_sequence[2])
demo.df$x_position[node_sequence[3]] <- x_spot(node_sequence[3])
demo.df$x_position[node_sequence[4]] <- x_spot(node_sequence[4])
demo.df$x_position[node_sequence[5]] <- x_spot(node_sequence[5])
demo.df$x_position[node_sequence[6]] <- x_spot(node_sequence[6])
demo.df$x_position[node_sequence[7]] <- x_spot(node_sequence[7])
demo.df$x_position[node_sequence[8]] <- x_spot(node_sequence[8])
demo.df$x_position[node_sequence[9]] <- x_spot(node_sequence[9])
demo.df$x_position[node_sequence[10]] <- x_spot(node_sequence[10])
demo.df$x_position
</code>```

But I can't figure out how to assign new values within vapply for something elegant like

```<code>vapply(1:10, function(x) {demo.df$x_position[node_sequence[x]] <- x_spot(node_sequence[x])}, numeric(1))
</code>```

What am I missing? Maybe return() somewhere in the code?

答:
As the previous values are used for calculating the next value, an option is <<-

```<code>vapply(1:10, function(x) {
  demo.df$x_position[node_sequence[x]] <<- x_spot(node_sequence[x])}, numeric(1))
demo.df$x_position
</code>```

In this case a for loop is much better

```<code>for(i in seq_along(node_sequence)) {
   demo.df$x_position[node_sequence[i]] <- x_spot(node_sequence[i])
 }
</code>```

Body:
I'm trying to dynamically update cells in a data frame with an apply-type function. Here's the reproducible example:

demo.df <- structure(list(node_id = 1:21, depth = c(4, 3, 2, 1, 0, 0,
1, 0, 0, 2, 1, 0, 0, 1, 0, 0, 2, 1, 0, 0, 0), x_position = c(NA, NA,
NA, NA, 1, 2, NA, 3, 4, NA, NA, 5, 6, NA, 7, 8, NA, NA, 9,10, 11), X1
= 1:21, X2 = c(2L, 3L, 4L, 5L, NA, NA, 8L, NA, NA, 11L, 12L, NA, NA,
15L, NA, NA, 18L, 19L, NA, NA, NA), X3 = c(17L, 10L, 7L, 6L, NA, NA,
9L, NA, NA, 14L, 13L, NA, NA, 16L, NA, NA, 21L, 20L, NA, NA, NA)),
class = "data.frame", row.names = c(1L, 2L, 4L, 8L, 16L, 17L, 9L, 18L,
19L, 5L, 10L, 20L, 21L, 11L, 22L, 23L, 3L, 6L, 12L, 13L, 7L))

node_sequence <- c(4,7,11,14,18,3,10,17,2,1)

I want to update x_position based on the mean of the following columns, going through the rows in a specified order, so

x_spot <- function (x)
 {mean(demo.df$x_position[which(demo.df$node_id%in%demo.df[x,c(4:6)])],
 na.rm = TRUE)
 }

This clumsy code gets the right result:

demo.df$x_position[node_sequence[1]] <- x_spot(node_sequence[1])
demo.df$x_position[node_sequence[2]] <- x_spot(node_sequence[2])
demo.df$x_position[node_sequence[3]] <- x_spot(node_sequence[3])
demo.df$x_position[node_sequence[4]] <- x_spot(node_sequence[4])
demo.df$x_position[node_sequence[5]] <- x_spot(node_sequence[5])
demo.df$x_position[node_sequence[6]] <- x_spot(node_sequence[6])
demo.df$x_position[node_sequence[7]] <- x_spot(node_sequence[7])
demo.df$x_position[node_sequence[8]] <- x_spot(node_sequence[8])
demo.df$x_position[node_sequence[9]] <- x_spot(node_sequence[9])
demo.df$x_position[node_sequence[10]] <- x_spot(node_sequence[10])
demo.df$x_position

But I can't figure out how to assign new values within vapply for something elegant like

vapply(1:10, function(x) {demo.df$x_position[node_sequence[x]] <- x_spot(node_sequence[x])}, numeric(1))

What am I missing? Maybe return() somewhere in the code?

Body:
As the previous values are used for calculating the next value, an option is <<-

vapply(1:10, function(x) {
  demo.df$x_position[node_sequence[x]] <<- x_spot(node_sequence[x])}, numeric(1))
demo.df$x_position

In this case a for loop is much better

for(i in seq_along(node_sequence)) {
   demo.df$x_position[node_sequence[i]] <- x_spot(node_sequence[i])
 }


问:
SQL query to get count of unique combinations in the table - MySql
I have a mapping table like below

```<code>c1  c2
--  --
1   1
1   1
1   2
1   3
1   3
2   1
2   2
2   3
3   1
</code>```

and so on. The table has a separate id column (not showed here).
Here is my query so far :

```<code>SELECT `c1`, `c2`, COUNT(*) AS `count_of_uniques` FROM `map_table`
GROUP BY `c1`, `c2`
</code>```

I have also tried with distinct query like this.

```<code>SELECT `c1`, `c2`, COUNT(DISTINCT `c1`, `c2`) AS `count_of_uniques` FROM `map_table`
</code>```

The expected result is

```<code>c1  c2  count_of_uniques
--  --  ----------------
1   1   2
1   2   2
1   3   3
2   2   1
2   3   1
</code>```

My current query shows the correct output when the combination is made of two similar numbers, but when we have something like 1-2 and 2-1, the query does not have the correct output.

distinct shows still fewer results.

Any help is greatly appreciated. Thank you.

答:
I think you might be after something that deals with combinations rather than permutations i.e 1, 2 and 2, 1 should be treated as the same combination. If this is the case you can use a case expression to make sure that c1 is always the lower of the two values, and c2 is the higher of the two. This will group similar pairs together (so 2, 1 will first be reversed to become 1, 2 then grouped with all similar results):

```<code>SELECT c1, c2, COUNT(*) AS `count_of_uniques`
FROM (  SELECT CASE WHEN c1 > c2 THEN c2 ELSE c1 END AS c1,
                CASE WHEN c1 > c2 THEN c1 ELSE c2 END AS c2
        FROM map_table) AS t
GROUP BY c1, c2
</code>```

Output

```<code>c1      c2      count_of_uniques
-------------------------------
1       1       2
1       2       2
1       3       3
2       2       1
2       3       1
</code>```

Example on DB Fiddle

Body:
I have a mapping table like below

c1  c2
--  --
1   1
1   1
1   2
1   3
1   3
2   1
2   2
2   3
3   1

and so on. The table has a separate id column (not showed here).
Here is my query so far :

SELECT `c1`, `c2`, COUNT(*) AS `count_of_uniques` FROM `map_table`
GROUP BY `c1`, `c2`

I have also tried with distinct query like this.

SELECT `c1`, `c2`, COUNT(DISTINCT `c1`, `c2`) AS `count_of_uniques` FROM `map_table`

The expected result is

c1  c2  count_of_uniques
--  --  ----------------
1   1   2
1   2   2
1   3   3
2   2   1
2   3   1

My current query shows the correct output when the combination is made of two similar numbers, but when we have something like 1-2 and 2-1, the query does not have the correct output.

distinct shows still fewer results.

Any help is greatly appreciated. Thank you.

Body:
I think you might be after something that deals with combinations rather than permutations i.e 1, 2 and 2, 1 should be treated as the same combination. If this is the case you can use a case expression to make sure that c1 is always the lower of the two values, and c2 is the higher of the two. This will group similar pairs together (so 2, 1 will first be reversed to become 1, 2 then grouped with all similar results):

SELECT c1, c2, COUNT(*) AS `count_of_uniques`
FROM (  SELECT CASE WHEN c1 > c2 THEN c2 ELSE c1 END AS c1,
                CASE WHEN c1 > c2 THEN c1 ELSE c2 END AS c2
        FROM map_table) AS t
GROUP BY c1, c2

Output

c1      c2      count_of_uniques
-------------------------------
1       1       2
1       2       2
1       3       3
2       2       1
2       3       1

Example on DB Fiddle


问:
How do I return an array from a dataloader?
Here is my GraphQL type:

```<code>const PoliticalEntity = new GraphQLObjectType({
    name: 'PoliticalEntity',
    fields: () => ({
        id: {
            type: GraphQLID,
            resolve: obj => obj.political_entity_id
        },
        algorithmValues: {
            type: new GraphQLList(AlgorithmValue),
            resolve: (obj, args, context) => {
                context
                    .dataloaders
                    .algorithmValueLoader
                    .load(obj.political_entity_id)
            }
        }
    })
});
</code>```

For each PoliticalEntity I have multiple AlgorithmValues.  How do I get the dataloader to return multiple values for each key?

The data loader is being called and the query is returning correctly, but I continue to get the error.  DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.

How do I fix this?

答:
Your batch load function should return a Promise with an array. As the error indicates, the length of the keys passed to the batch load function must match the length of this result array. If your Loader is fetching an array of items for each key, then the Promise must resolve to an array of arrays.</p>

```<code>const backLoadFn = (keys) => {
  return Promise.all(keys.map(key => {
    return Model.findAll({ where: { key } })
  }))
}
</code>```

Body:
Here is my GraphQL type:

const PoliticalEntity = new GraphQLObjectType({
    name: 'PoliticalEntity',
    fields: () => ({
        id: {
            type: GraphQLID,
            resolve: obj => obj.political_entity_id
        },
        algorithmValues: {
            type: new GraphQLList(AlgorithmValue),
            resolve: (obj, args, context) => {
                context
                    .dataloaders
                    .algorithmValueLoader
                    .load(obj.political_entity_id)
            }
        }
    })
});

For each PoliticalEntity I have multiple AlgorithmValues.  How do I get the dataloader to return multiple values for each key?

The data loader is being called and the query is returning correctly, but I continue to get the error.  DataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys.

How do I fix this?

Body:
Your batch load function should return a Promise with an array. As the error indicates, the length of the keys passed to the batch load function must match the length of this result array. If your Loader is fetching an array of items for each key, then the Promise must resolve to an array of arrays.

const backLoadFn = (keys) => {
  return Promise.all(keys.map(key => {
    return Model.findAll({ where: { key } })
  }))
}


问:
How to add external fonts to android application
I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts.

Thank you.

答:
You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()

```<code>TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);
</code>```

Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).

Body:
You need to create fonts folder under assets folder in your project and put your TTF into it. Then in your Activity onCreate()

TextView myTextView=(TextView)findViewById(R.id.textBox);
Typeface typeFace=Typeface.createFromAsset(getAssets(),"fonts/mytruetypefont.ttf");
myTextView.setTypeface(typeFace);

Please note that not all TTF will work. While I was experimenting, it worked just for a subset (on Windows the ones whose name is written in small caps).


问:
Autowire JUnit rule in integration test
I have a piece of code which will be repeated across multiple integration tests. The code will run before and after tests. I have decided that using an JUnit @Rule would be the best way to achieve this.

The problem is that the rule will need to have access to few @Autowired Spring beans. (The tests are run with Spring Integration Test Runner so Autowire works fine.

I have a rule:

public class CustomSpringRule extends ExternalResource {
    private final SomeOtherBean someOtherBean;

    public CustomSpringRule(SomeOtherBean someOtherBean) {
        this.someOtherBean = someOtherBean;
    }

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

    // ...
}
```

<p>I have my context to which I have added my bean:</p>

<pre class="lang-java prettyprint-override"><code>@Bean
public CustomSpringRule getCustomSpringRule(SomeOtherBean someOtherBean) {
   return new CustomSpringRule(someOtherBean);
}
</code>```

Finally I have just autowired the rule bean within test file:

@Autowire
@Rule
public CustomSpringRule customSpringRule;
```

It all works fine but I never really used the @Rule annotation and I am slightly concerned that JUnit reflection and Spring Autowire won't go well together or there will be some issues that are not obvious at first look.

Does anyone have any suggestions whether this is valid and safe?

答:
Using auto-wired rules is fine – there are no problems or limitations with this approach.

Note: I you are using component scanning (which is e.g. enabled in @SpringBootTest), you can simplify the rule implementation like this:

```<code>@Component
public class CustomSpringRule extends ExternalResource {
    @Autowired
    private SomeOtherBean someOtherBean;

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

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

Title: Autowire JUnit rule in integration test

Body:
I have a piece of code which will be repeated across multiple integration tests. The code will run before and after tests. I have decided that using an JUnit @Rule would be the best way to achieve this.

The problem is that the rule will need to have access to few @Autowired Spring beans. (The tests are run with Spring Integration Test Runner so Autowire works fine.

I have a rule:

public class CustomSpringRule extends ExternalResource {
    private final SomeOtherBean someOtherBean;

    public CustomSpringRule(SomeOtherBean someOtherBean) {
        this.someOtherBean = someOtherBean;
    }

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

    // ...
}

I have my context to which I have added my bean:

@Bean
public CustomSpringRule getCustomSpringRule(SomeOtherBean someOtherBean) {
   return new CustomSpringRule(someOtherBean);
}

Finally I have just autowired the rule bean within test file:

@Autowire
@Rule
public CustomSpringRule customSpringRule;

It all works fine but I never really used the @Rule annotation and I am slightly concerned that JUnit reflection and Spring Autowire won't go well together or there will be some issues that are not obvious at first look.

Does anyone have any suggestions whether this is valid and safe?

Body:
Using auto-wired rules is fine – there are no problems or limitations with this approach.

Note: I you are using component scanning (which is e.g. enabled in @SpringBootTest), you can simplify the rule implementation like this:

@Component
public class CustomSpringRule extends ExternalResource {
    @Autowired
    private SomeOtherBean someOtherBean;

    @Override
    public void before() {
        someOtherBean.someMethod();
    }

    // ...
}


问:
Can't truncate PostgreSQL tables with JPA
I'm trying to quickly delete all data from multiple tables using Spring Data JPA. From what I've read, the fastest way to do this is to truncate the tables.

My code looks like this:

@Service
public class DatabaseService {

    ... autowiring ...

    @Transactional
    public void deleteRepository(){
        repository.truncate();
    }
}
```

<pre class="lang-java prettyprint-override"><code>@Repository
public interface repository extends JpaRepository<Trip, Long> {

    @Modifying
    @Query(value = "truncate table my_table",
            nativeQuery = true)
    void truncate();
}
</code>```

However, when I call the deleteRepository() method, I get the following exception:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databasePopulatorJob': Invocation of init method failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: java.sql.SQLException: Connection is closed
...
</code>```

I'm using latest PostgreSQL database with JDBC driver version 42.2.5.

I've also tried other methods to delete the data like DELETE FROM my_table (my_table contains about 2 million records), but it takes way too long. I'd appretiate any tips.

答:
If you have relationship between the tables, you wont be able to TRUNCATE the tables, because is Data Integrit Violation Exception, if you are using the database H2, have i kind of trick thing you can do:

```<code>SET REFERENTIAL_INTEGRITY FALSE;

TRUNCATE TABLE tbtable;

SET REFERENTIAL_INTEGRITY TRUE;
</code>```

.sql

Body:
I'm trying to quickly delete all data from multiple tables using Spring Data JPA. From what I've read, the fastest way to do this is to truncate the tables.

My code looks like this:

@Service
public class DatabaseService {

    ... autowiring ...

    @Transactional
    public void deleteRepository(){
        repository.truncate();
    }
}

@Repository
public interface repository extends JpaRepository<Trip, Long> {

    @Modifying
    @Query(value = "truncate table my_table",
            nativeQuery = true)
    void truncate();
}

However, when I call the deleteRepository() method, I get the following exception:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'databasePopulatorJob': Invocation of init method failed; nested exception is org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: org.hibernate.TransactionException: Unable to rollback against JDBC Connection
...
Caused by: java.sql.SQLException: Connection is closed
...

I'm using latest PostgreSQL database with JDBC driver version 42.2.5.

I've also tried other methods to delete the data like DELETE FROM my_table (my_table contains about 2 million records), but it takes way too long. I'd appretiate any tips.

Body:
If you have relationship between the tables, you wont be able to TRUNCATE the tables, because is Data Integrit Violation Exception, if you are using the database H2, have i kind of trick thing you can do:

SET REFERENTIAL_INTEGRITY FALSE;

TRUNCATE TABLE tbtable;

SET REFERENTIAL_INTEGRITY TRUE;

.sql


问:
How do i retrieve a list of machine on a specific version of windows
I am trying to get a list of PC's where the name is equal to LN-M* and then from the reults filter out the ones which have a ReleaseID (Version of Windows) of 1703

Powershell -

this is a list of the variables i will be using

```<code>$ReleaseID = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseID).ReleaseID
$ComputerName = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name ComputerName).ComputerName
</code>```

This is to filter the machines by name

```<code>$Threshold = (Get-Date).AddDays(-400)

$DesktopPC = Get-ADComputer -Filter * -Properties Name |
    where (
            $_.name -Like "LN-M*"
        )

$results = $DesktopPC | select name
</code>```

These are the results I hope to get

```<code>ForEach-Object {$results -eq
$_.ReleaseID -eq 1703

 $ComputerName.Name

 }
</code>```

答:
The basic example code below will do what you're asking for machines that are online and accessible. You'll need to add error checking and validation logic.</p>

```<code>$targetMachines = New-Object System.Collections.ArrayList

#Filter by name right in your AD query instead of getting all computer objects
$allMachines = Get-ADComputer -Filter 'Name -like "LN-M*"'

$allMachines | foreach {
    $dnsHostname = $_.DNSHostName

    # The remote registry service will need to be running on the the target machine
    $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$dnsHostname)
    $key = $registry.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion")
    $releaseID = $key.GetValue("ReleaseID")

    if ($releaseID -eq 1703)
    {
        $targetMachines.Add($dnsHostname) | Out-Null
    }
}

# These are the machines you are looking for (with Jedi hand wave)
$targetMachines
</code>```

Body:
I am trying to get a list of PC's where the name is equal to LN-M* and then from the reults filter out the ones which have a ReleaseID (Version of Windows) of 1703

Powershell -

this is a list of the variables i will be using

$ReleaseID = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ReleaseID).ReleaseID
$ComputerName = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name ComputerName).ComputerName

This is to filter the machines by name

$Threshold = (Get-Date).AddDays(-400)

$DesktopPC = Get-ADComputer -Filter * -Properties Name |
    where (
            $_.name -Like "LN-M*"
        )

$results = $DesktopPC | select name

These are the results I hope to get

ForEach-Object {$results -eq
$_.ReleaseID -eq 1703

 $ComputerName.Name

 }

Body:
The basic example code below will do what you're asking for machines that are online and accessible. You'll need to add error checking and validation logic.

$targetMachines = New-Object System.Collections.ArrayList

#Filter by name right in your AD query instead of getting all computer objects
$allMachines = Get-ADComputer -Filter 'Name -like "LN-M*"'

$allMachines | foreach {
    $dnsHostname = $_.DNSHostName

    # The remote registry service will need to be running on the the target machine
    $registry = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$dnsHostname)
    $key = $registry.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion")
    $releaseID = $key.GetValue("ReleaseID")

    if ($releaseID -eq 1703)
    {
        $targetMachines.Add($dnsHostname) | Out-Null
    }
}

# These are the machines you are looking for (with Jedi hand wave)
$targetMachines


问:
How to have a method pause and wait for input with Android?
Basically I have created a Blackjack app that uses several methods that get called and pass a long the information that is needed (about cards and actions).  I have 2 buttons displayed on screen that are click able (hit and stand).  Now I have a method called player turn... and this is when I (through static ints) have if a button is selected, things will happen.  However I did this with an infinite while loop thinking it will just keep checking to see if a button is pressed and then only do action when a button is pressed.  This isn't working as  my screen is not refreshing after each textview or imageview change thus as soon as I hit start game the game appears to "freeze" (being due to the method never ending) and I am therefore unable to click said buttons.  Is there a way to call something similar to keyboard listener in java (Which pauses activity and waits for user input), in android?  If not, what would you suggest the workaround be?  Lastly (though not as currently important) how would I properly refresh everything after each change (I believe I need to use invalidate.. though I'm not sure what to have before invalidate so it refreshes the whole thing)?  Thanks a bunch in advance.</p>

答:
Looks like a new Activity (invoked by startActivityForResult), and a Handler (called from the onActivityResult) could solve your problem.

Take a look at the design-snippet bellow:

Let's say the method you are willing to 'sleep' is the doSomething from the MainActivity class. I assume this is invoked from some event handler implementation. You should move all the calls from that method into the BackgroundActivity activity,
- which should  show a ProgressDialog and/or nothing else -.

In your doSomething method you should start an activity by an intent pointing to the BackgroundActivity with

```<code>this.startActivityForResult(new Intent(this, BackgroundActivity.class),
    BG_ACTIVITY_ID);
</code>```

where BG_ACTIVITY_ID is your unique identifier for the started activity, so when it finishes, you can handle it.

Inside the processBackgroundData (or when the background activity is finished processing), you should set the result before calling finish():

```<code>final Intent intent = new Intent();
intent.putExtra(KEY_FOR_DATA_YOU_NEED, dataYouNeed);
setResult(Activity.RESULT_OK, intent);
finish();
</code>```

In your MainActivity you should also override the onActivityResult method, to retrieve the necessary information from the finished BackgroundActivity task:

```<code>@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    //you might also want to check if the resultCode is `Activity.RESULT_OK`...
    switch (requestCode)
    {
        case BG_ACTIVITY_ID:
            //get the data you need
            final String dataYouNeed = data.getStringExtra(KEY_FOR_DATA_YOU_NEED);
            //process the data...
            //if necessary (threads!), call your backgroundHandler's
            //sendMessage with the retrieved informations as obj.parameters
        [...]
            break;
        default:
            [...]
            break;
    }
}
</code>```

And inside your BackgroundHandler's handleMessage method (since you are back to the ui thread: the thread in which your main application is running) you can do all the necessary ui modifications, and also listen forward for the user events.

This way you are getting rid of the infinite loop, and can always be aware of user interactions.

Body:
Looks like a new Activity (invoked by startActivityForResult), and a Handler (called from the onActivityResult) could solve your problem.

Take a look at the design-snippet bellow:

Let's say the method you are willing to 'sleep' is the doSomething from the MainActivity class. I assume this is invoked from some event handler implementation. You should move all the calls from that method into the BackgroundActivity activity,
- which should  show a ProgressDialog and/or nothing else -.

In your doSomething method you should start an activity by an intent pointing to the BackgroundActivity with

this.startActivityForResult(new Intent(this, BackgroundActivity.class),
    BG_ACTIVITY_ID);

where BG_ACTIVITY_ID is your unique identifier for the started activity, so when it finishes, you can handle it.

Inside the processBackgroundData (or when the background activity is finished processing), you should set the result before calling finish():

final Intent intent = new Intent();
intent.putExtra(KEY_FOR_DATA_YOU_NEED, dataYouNeed);
setResult(Activity.RESULT_OK, intent);
finish();

In your MainActivity you should also override the onActivityResult method, to retrieve the necessary information from the finished BackgroundActivity task:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    //you might also want to check if the resultCode is `Activity.RESULT_OK`...
    switch (requestCode)
    {
        case BG_ACTIVITY_ID:
            //get the data you need
            final String dataYouNeed = data.getStringExtra(KEY_FOR_DATA_YOU_NEED);
            //process the data...
            //if necessary (threads!), call your backgroundHandler's
            //sendMessage with the retrieved informations as obj.parameters
        [...]
            break;
        default:
            [...]
            break;
    }
}

And inside your BackgroundHandler's handleMessage method (since you are back to the ui thread: the thread in which your main application is running) you can do all the necessary ui modifications, and also listen forward for the user events.

This way you are getting rid of the infinite loop, and can always be aware of user interactions.


问:
How to compare files from two different branches
I have a script that works fine in one branch and is broken in another. I want to look at the two versions side-by-side and see what's different. Is there a way to do this?

To be clear I'm not looking for a compare tool (I use Beyond Compare). I'm looking for a Git diff command that will allow me to compare the master version to my current branch version to see what has changed. I'm not in the middle of a merge or anything. I just want to say something like

```<code>git diff mybranch/myfile.cs master/myfile.cs
</code>```

答:
Use commit hashes as this:

```<code>git diff <hash1> <hash2> <filename>
</code>```

where hash1 can be any commit from any branch, and the same for hash2.

Body:
I have a script that works fine in one branch and is broken in another. I want to look at the two versions side-by-side and see what's different. Is there a way to do this?

To be clear I'm not looking for a compare tool (I use Beyond Compare). I'm looking for a Git diff command that will allow me to compare the master version to my current branch version to see what has changed. I'm not in the middle of a merge or anything. I just want to say something like

git diff mybranch/myfile.cs master/myfile.cs

Body:
Use commit hashes as this:

git diff <hash1> <hash2> <filename>

where hash1 can be any commit from any branch, and the same for hash2.


问:
Scala - Unexpected Nullable Found - Left Join
I have been receiving an UnexpectedNullableFound error with my Scala application and I was hoping for some assistance on how to correct this.

The error:-

```<code>[error] application - Unable to log user in. An exception was thrown
java.lang.RuntimeException: Left(UnexpectedNullableFound(ColumnName(.language,Some(language))))                                                                                at anorm.MayErr$$anonfun$get$1.apply(MayErr.scala:35) ~[anorm_2.11-2.4.0.jar:2.4.0]                                                                                at anorm.MayErr$$anonfun$get$1.apply(MayErr.scala:34) ~[anorm_2.11-2.4.0.jar:2.4.0]                                                                                at scala.util.Either.fold(Either.scala:98) ~[scala-library-2.11.12.jar:na]                at anorm.MayErr.get(MayErr.scala:34) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at anorm.Row$class.unsafeGet(Row.scala:103) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at anorm.Cursor$ResultRow.unsafeGet(Cursor.scala:77) ~[anorm_2.11-2.4.0.jar:2.4.0]        at anorm.Row$class.apply(Row.scala:80) ~[anorm_2.11-2.4.0.jar:2.4.0]                      at anorm.Cursor$ResultRow.apply(Cursor.scala:77) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at models.UserModel$$anonfun$findUserByEmailAndPassword$1$$anonfun$apply$9.apply(UserModel.scala:162) ~[classes/:na]
        at models.UserModel$$anonfun$findUserByEmailAndPassword$1$$anonfun$apply$9.apply(UserModel.scala:156) ~[classes/:na]
</code>```

And this is the code where I think it might be causing this error:-

```<code>  def findUserByEmailAndPassword(email: String, password: String, browserHeaders: String, ip: String): Option[SocialUser] = DB.withConnection(db) { implicit c =>
    SQL"""
    select * from find_user_by_email_and_password($email, $password, $browserHeaders, inet($ip))
    """().map(row => (row[Option[Long]]("id"),
      row[Option[String]]("email"),
      row[Option[Int]]("verification"),
      row[Option[Boolean]]("on_mailing_list"),
      row[Option[Boolean]]("tfa_enabled"),
      row[Option[String]]("pgp"),
      row[String]("language")) match {
        case (Some(id: Long),
          Some(email: String),
          Some(verification: Int),
          Some(on_mailing_list: Boolean),
          Some(tfa_enabled: Boolean),
          pgp: Option[String],
          language: String) =>
          Some(SocialUser(id, email, verification, language, on_mailing_list, tfa_enabled, pgp))
        case _ =>
          None
      }
    ).head
</code>```

Any help would be greatly appreciated.

答:
You are going to take something row[String]("language") from the column language, but this column contains NULL value.

You need to write it as row[Option[String]]("language") or make the language column NOT NULL in the database scheme.

Body:
I have been receiving an UnexpectedNullableFound error with my Scala application and I was hoping for some assistance on how to correct this.

The error:-

[error] application - Unable to log user in. An exception was thrown
java.lang.RuntimeException: Left(UnexpectedNullableFound(ColumnName(.language,Some(language))))                                                                                at anorm.MayErr$$anonfun$get$1.apply(MayErr.scala:35) ~[anorm_2.11-2.4.0.jar:2.4.0]                                                                                at anorm.MayErr$$anonfun$get$1.apply(MayErr.scala:34) ~[anorm_2.11-2.4.0.jar:2.4.0]                                                                                at scala.util.Either.fold(Either.scala:98) ~[scala-library-2.11.12.jar:na]                at anorm.MayErr.get(MayErr.scala:34) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at anorm.Row$class.unsafeGet(Row.scala:103) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at anorm.Cursor$ResultRow.unsafeGet(Cursor.scala:77) ~[anorm_2.11-2.4.0.jar:2.4.0]        at anorm.Row$class.apply(Row.scala:80) ~[anorm_2.11-2.4.0.jar:2.4.0]                      at anorm.Cursor$ResultRow.apply(Cursor.scala:77) ~[anorm_2.11-2.4.0.jar:2.4.0]
        at models.UserModel$$anonfun$findUserByEmailAndPassword$1$$anonfun$apply$9.apply(UserModel.scala:162) ~[classes/:na]
        at models.UserModel$$anonfun$findUserByEmailAndPassword$1$$anonfun$apply$9.apply(UserModel.scala:156) ~[classes/:na]

And this is the code where I think it might be causing this error:-

  def findUserByEmailAndPassword(email: String, password: String, browserHeaders: String, ip: String): Option[SocialUser] = DB.withConnection(db) { implicit c =>
    SQL"""
    select * from find_user_by_email_and_password($email, $password, $browserHeaders, inet($ip))
    """().map(row => (row[Option[Long]]("id"),
      row[Option[String]]("email"),
      row[Option[Int]]("verification"),
      row[Option[Boolean]]("on_mailing_list"),
      row[Option[Boolean]]("tfa_enabled"),
      row[Option[String]]("pgp"),
      row[String]("language")) match {
        case (Some(id: Long),
          Some(email: String),
          Some(verification: Int),
          Some(on_mailing_list: Boolean),
          Some(tfa_enabled: Boolean),
          pgp: Option[String],
          language: String) =>
          Some(SocialUser(id, email, verification, language, on_mailing_list, tfa_enabled, pgp))
        case _ =>
          None
      }
    ).head

Any help would be greatly appreciated.


问:
XCTestCase stops after failure
I have a XCTestCase, but if the test fail - the app quits right away.
I did change this line to the following:

```<code>continueAfterFailure = true
</code>```

and it still quit the app after failure.
Does anyone know how to keep the app alive after UI test failure? Couldn't find a solution yet.

答:
By default, the app will get quit in the tearDown method after the test case is finished running. We need to override the tearDown method to terminate the app only when we want.

For example XCUITest Class teardown isnt deleting the app. But works if its instance teardown. What am I doing wrong?

Title: XCTestCase stops after failure

Body:
I have a XCTestCase, but if the test fail - the app quits right away.
I did change this line to the following:

continueAfterFailure = true

and it still quit the app after failure.
Does anyone know how to keep the app alive after UI test failure? Couldn't find a solution yet.


问:
CORS issue in .Net Framework 4.5 with Angular 6
I have created API in .Net Framework 4.5 and it's working fine in Postman but When I am implementing with Angular7 then we didn't get Requested Parameters like (Username and Password) in API.

I have already tried these steps:

I have already installed this package
Microsoft.AspNet.WebApi.Cors

DemoController.cs

```<code>using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using TestData.Models;

namespace TestData.Controllers
{
    public class DemoController : ApiController
    {
        [HttpPost]
        [Route("api/Demo/Login")]
        public IHttpActionResult Login(HttpRequestMessage request)
        {
            string username = HttpContext.Current.Request.Form["Username"]; // getting Null
            string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null
            return Ok('Username: ' +username + 'Password :' +pass);
        }
    }
}
</code>```

WebApiConfig.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace TestData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
}
</code>```

I am using some code of Angular

auth.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {

    apiUrl : any = 'http://mydomain/api';

    constructor(private http : HttpClient) { }

    GetHttpHeaders() : HttpHeaders {
        const headers = new HttpHeaders().set('Content-Type', 'application/json');
        return headers;
    }

    loginUser() {
        var data = JSON.stringify({
            "Username" : '3333',
            "Pass" : '123456'
        })
        return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
            console.log(results);
        });
    }
}
</code>```

答:
In UI you have added 'Content-Type', 'application/json', So it is better if you accept parameter of type object in ActionResult.

Try this Solution:

Backend:

```<code>public IHttpActionResult Login(JObject request)
{
    string username = Convert.ToString(request.SelectToken("Username"))
    ...
}
</code>```

UI:

```<code> loginUser(){
    var data = {
      "Username" : '3333',
      "Password" : '123456'
    }
    return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
      console.log(results);
    });
  }
</code>```

Another way is to create a Model Class:

```<code>public class LoginRequestDTO
{
   public string Username{ get; set; }

   public string Password{ get; set; }
}
</code>```

and ActionResult:

```<code>public IHttpActionResult Login(LoginRequestDTO request)
{
    string username = request.Username;
    ...
}
</code>```

Body:
I have created API in .Net Framework 4.5 and it's working fine in Postman but When I am implementing with Angular7 then we didn't get Requested Parameters like (Username and Password) in API.

I have already tried these steps:

I have already installed this package
Microsoft.AspNet.WebApi.Cors

DemoController.cs

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using System.Web.Http.Description;
using TestData.Models;

namespace TestData.Controllers
{
    public class DemoController : ApiController
    {
        [HttpPost]
        [Route("api/Demo/Login")]
        public IHttpActionResult Login(HttpRequestMessage request)
        {
            string username = HttpContext.Current.Request.Form["Username"]; // getting Null
            string pass = HttpContext.Current.Request.Form["Pass"]; // getting Null
            return Ok('Username: ' +username + 'Password :' +pass);
        }
    }
}

WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;

namespace TestData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
}

I am using some code of Angular

auth.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class AuthService {

    apiUrl : any = 'http://mydomain/api';

    constructor(private http : HttpClient) { }

    GetHttpHeaders() : HttpHeaders {
        const headers = new HttpHeaders().set('Content-Type', 'application/json');
        return headers;
    }

    loginUser() {
        var data = JSON.stringify({
            "Username" : '3333',
            "Pass" : '123456'
        })
        return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
            console.log(results);
        });
    }
}

Body:
In UI you have added 'Content-Type', 'application/json', So it is better if you accept parameter of type object in ActionResult.

Try this Solution:

Backend:

public IHttpActionResult Login(JObject request)
{
    string username = Convert.ToString(request.SelectToken("Username"))
    ...
}

UI:

 loginUser(){
    var data = {
      "Username" : '3333',
      "Password" : '123456'
    }
    return this.http.post(this.apiUrl+'/Demo/Login', data, { headers : this.GetHttpHeaders() }).subscribe((results) => {
      console.log(results);
    });
  }

Another way is to create a Model Class:

public class LoginRequestDTO
{
   public string Username{ get; set; }

   public string Password{ get; set; }
}

and ActionResult:

public IHttpActionResult Login(LoginRequestDTO request)
{
    string username = request.Username;
    ...
}


问:
How many MySQL queries should I limit myself to on a page? PHP / MySQL
Okay, so I'm sure plenty of you have built crazy database intensive pages...

I am building a page that I'd like to pull all sorts of unrelated database information from.  Here are some sample different queries for this one page:

article content and info

IF the author is a registered user, their info

UPDATE the article's view counter

retrieve comments on the article

retrieve information for the authors of the comments

if the reader of the article is signed in, query for info on them

etc...

I know these are basically going to be pretty lightning quick, and that I could combine some; but I wanted to make sure that this isn't abnormal?

How many fairly normal and un-heavy queries would you limit yourself to on a page?

答:
Premature optimisation is a problem like people have mentioned before, but that's where you're crapping up your code to make it run 'fast'. But people take this 'maxim' too far.

If you want to design with scalability in mind, just make sure whatever you do to load data is sufficiently abstracted and calls are centralized, this will make it easier when you need to implement a shared memory cache, as you'll only have to change a few things in a few places.

OwnerDisplayName: johnnietheblack

OwnerDisplayName: Saem

ContentLicense: CC BY-SA 2.5


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答:
If you need something quick and dirty simply use Fermat's little theorem.

```<code>def isPrime(p):
    if(p==2): return True
    if(not(p&1)): return False
    return pow(2,p-1,p)==1
</code>```

Although this works quite well for random numbers this will fail for numbers know as "pseudoprimes". (quite scarce)
But If you need something foolproof and simple enough to implement I'd suggest you
read up about Miller Rabin's Primality Test.

PS: pow(a,b,c) takes O(log(b)) time in python.

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break

Body:
If you need something quick and dirty simply use Fermat's little theorem.

def isPrime(p):
    if(p==2): return True
    if(not(p&1)): return False
    return pow(2,p-1,p)==1

Although this works quite well for random numbers this will fail for numbers know as "pseudoprimes". (quite scarce)
But If you need something foolproof and simple enough to implement I'd suggest you
read up about Miller Rabin's Primality Test.

PS: pow(a,b,c) takes O(log(b)) time in python.


问:
SSRS Grand Total should sum subtotals and not source values
I am trying to sum timesheet entries by user, users enter actual duration and the report then applies a minimum 0.5 day rule to each user.

The problem is that the grand total is recalculating based on the source values when it need to sum the user subtotal after the 0.5 day rule is applied.

A day is defined as 7.5 hours

Formula used for rounding Ceiling(((Sum(Fields!minutes.Value)/60)/7.5) / 0.5) *0.5, this is used for the line items, subtotal and grand total.

This uses a Matrix control to display the data

Example

Source Data

user----minutes

Bob-----60

Bob-----60

Alice---1680

Report

user----days

Bob-----0.5

Alice---4

Total---4

What I actually want

Report

user----days

Bob-----0.5

Alice---4

Total---4.5

答:
Based on the comment, it looks like you are summing up the total of using the field which would be the data from your dataset.  You'll need to modify the expression used to grab the data from the report item.  I don't know that I have total understanding of the report and how it works, but if each line item is using that same expression, you should be able to use the following expression to calculate the grand total.

```<code>= SUM(ReportItems!LineItemDays.Value)
</code>```

Basically, you just need to sum the values given for each line item so sub in the name of the textbox that contains each line's day count and it should correct your issue.

Body:
Based on the comment, it looks like you are summing up the total of using the field which would be the data from your dataset.  You'll need to modify the expression used to grab the data from the report item.  I don't know that I have total understanding of the report and how it works, but if each line item is using that same expression, you should be able to use the following expression to calculate the grand total.

= SUM(ReportItems!LineItemDays.Value)

Basically, you just need to sum the values given for each line item so sub in the name of the textbox that contains each line's day count and it should correct your issue.


问:
Privacy policy publish
I created an android application which with ability to sign in with Googpe Play Services and get leaderboard data of player for my game. Now Google said that I must provide privacy policy.
There is problem: privacy policy must be placed in the web site, but I have no site and also I have no skills to create site. I am not web-developer, I am Android developer.
There is services to place my privacy policy in the web?</p>

答:
In my opinion the problem is that you need to add a Privacy Policy to your app and to your Console.

To do this you need to:

create Privacy Policy

Easy way to do this is with the Privacy Policy Generator

Add it to your app and Console

Google Console -> your app -> store presence -> store listing -> Privacy Policy.

Then you need to generate .apk file (Android Studio -> Build > Build > Generate Signed Bundle/APK) with a higher Version code then before.

Add another release to your app – don’t create another app with the same package name.

Console -> your app -> Release management -> App releases

Wait

Usually it takes a few hours for google to unlock the app.

Title: Privacy policy publish


问:
Cannot cast cell as Custom cell
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

```<code>func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }
</code>```

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

```<code>import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}
</code>```

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard

答:
Could not cast value of type 'UITableViewCell' (0x119dffaa0) to 'TelemedIOS.FAQTableViewCell' (0x1105d8688)

You need to assign the class name FAQTableViewCell to cell in xib

Title: Cannot cast cell as Custom cell

Body:
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard


问:
Android Emulator not rendering correctly
A friend of mine (who doesn't have enough reputation to post images) is facing a problem with his emulator. It is not rendering as it should, even though the clicks are where they should be. In order to click on the Back button, he must click down in the black part of the "screen".

He already tried to restart his computer, change monitor resolutions and creating another emulator images.

He uses KDE and is using his NVidia hardware to process graphics.

答:
My answer from this post: Android emulator screen fills up only some fraction part of actual android emulator screen

Best and simplest way to do it on Windows 10:

Close your Android Emulator if it is open

Right-click desktop

Click Display Settings

Set Scale and layout to 100%

Open Android Emulator

Revert your Scale and layout to the (Recommended) percentage