text:
Q: Benefits in using the Visual State Manager over handling Current_SizeChanged event in code (WinRT, XAML) I'm writing my first WinRT app for Windows 8 in C#/XAML managed code and I obviously have to handle the UI in the different sizes and orientations that could occur (FullScreenLandscape, FullScreenPortrait, Filled and Snapped).
Most people seem to suggest handling the UI changes through the Visual State Manager in XAML, however me being more comfortable with writing the code-behind rather than XAML, I thought I would simply handle the Current_SizeChanged event with a switch statement for each of the states.
I tried both ways and both seem to work for me (though the VSM was decidedly more work - at least for me).
Can someone tell me why I should use the VSM over code, or what benefits I would receive?

A: It's a good question, and certainly one that entered my head when starting WPF & WinRT development. Having coded C# projects for years, it seemed a strange concept to start building UI logic in the Xaml (which is usually more lines than C#, but also more declarative).
In actual fact (if you don't mind me saying) I think we can abstract your question out to 'Is there any benefit to writing UI code in Xaml over C#/VB.net?'.
Let me give you an example, in work I'm on a project team with several developers, and several graphic designers. The designers are pretty awesome at laying out that Xaml, and creating a consistent feel for the application (something I can't say I would be that good at) - but will have little idea when it comes to writing web-services and Data Access layers - which is our job as developers. And that's how it should be right?
Well whenever you start writing a lot of View/UI related logic in C#.net, this can lead to all sorts of problems. The designers all of a sudden can't focus on the Xaml at hand, and must get up to speed with OO programming. In our project this isn't that much of a concern, as the designers are actually pretty competent developers (must have been all that UI code I forced them to understand last year :)) But what I think it boils down to is a 'Separation of Concerns' at a job description level. If we take the paradigms associated to WPF I think things like Databinding 'guides' developers down a road where they create separated, testable UI and Business layers - the same way that the nature of Xaml allows for a very declarative approach to writing UI where the View Logic is created and maintained in a very readable manner without getting too much into the nature of OO programming.
So, coming back to your question - No, I don't think there any immediate benefits, and if you come from a mainly .Net background to write a lot of these things is Xaml can be little tricky. However, if you are in a team of people - or if you find best-practices a very important factor in development, then writing View related code such as Visual State manager configuration in Xaml is the way to go.
One last point - you'll notice I used the terminology 'View related logic' a lot. This is because it's widly viewed that writing UI related code in code-behind is acceptable (if not best-practice) but sometimes due to the nature of the WPF or WinRT framework you are dragged down this route for some functionality. However, if you are writing business logic in the UI files codebehind this is viewed a particular no-no. This breaks the 'seperation of concerns' and can make testing very difficult. If you are following the MVVM pattern (as many WPF or WinRT projects do) then this is what the ViewModel is responsible for.


text:
Q: Possible structures for a group G where every element has order dividing 63 and in which there are 108 elements of order exactly 63. I am trying prove the problem in the title.
Let $G$ be a finite abelian group in which every element has order dividing 63 and in which there are 108 elements or order exactly 63. I want to determine all the possibilities for the structure of G.
My attempt is the following:
I know that since every element has order dividing 63, then the order of any element will be either 3, 9 or 7. Furthermore, by the fundamental theorem for the finitely generated abelian groups, I know that the group will be a direct product/sum of a certain number of copies of $\mathbb{Z}/3\mathbb{Z}$, $\mathbb{Z}/9\mathbb{Z}$ and $\mathbb{Z}/7\mathbb{Z}$. So my group G will be isomorphic to $(\mathbb{Z}/3\mathbb{Z})^a \oplus (\mathbb{Z}/9\mathbb{Z})^b \oplus (\mathbb{Z}/7\mathbb{Z})^c$ where $a,b,c$ are integers such that $b, c \geq 1$ (since every element has order dividing 63). Now, this is where I am stuck. Since there are 108 elements of order exactly 63, I think I want to count how many elements have order 63 in my direct sum (find an expression for the number of these elements in terms of $a,b,c$) and from there find the adequate values of $a,b,c$. Is this is a good way to approach this problem? How could I count this number of elements of order 63? Thanks!

A: Note that the element of $G = (\mathbb{Z}/3\mathbb{Z})^k \oplus (\mathbb{Z}/9\mathbb{Z})^s \oplus (\mathbb{Z}/7\mathbb{Z})^r$ are of the form $(a_1,\cdots,a_k,b_1,\cdots,b_s,c_1,\cdots,c_r)$, where $a_i,b_i,c_i$ are elements of copy of $\mathbb{Z}/3\mathbb{Z},\mathbb{Z}/9\mathbb{Z},\mathbb{Z}/7\mathbb{Z}$ respectively. Also we have that:
$$o((a_1,\cdots,a_k,b_1,\cdots,b_s,c_1,\cdots,c_r)) = \operatorname{lcm}(o(a_1),\cdots ,o(c_r))$$
From here it's easy to notice that the order would be divisible by $7$ if at least one $c_i$ has order $7$ in its respective copy of $\mathbb{Z}/7\mathbb{Z}$. Thus we have $7^r - 1$ choiches for the last $r$ coordinates s.t. the element will have an order divisible by $7$.
Similar reasoning yields that we have $9^s - 3^s$ choiches for the middle $s$ coordinates. This is true, as $\mathbb{Z}/9\mathbb{Z}$ has exactly $3$ elements of order not $9$.
Finally the choice of the first $k$ coordinates doesn't matter too much, as they alone can't contribute to an element having order divisible by $9$. Thus the number of elements of order $63$ in $G$ is exactly:
$$3^k(9^s-3^s)(7^r-1)$$
Now it's not hard to conclude that $r=1$, as if $r\ge 2$ we obtain a contradiction by:
$$108 = 3^k(9^s-3^s)(7^r-1) \ge 3^k(9-3)(7^2-1) = 288\cdot3^k $$
Similarly $s=1$, as otherwise:
$$108 = 108 = 3^k(9^s-3^s)(7-1) \ge 3^k(9^2-3^2)(7-1) = 432\cdot3^k$$
Finally we are left with:
$$108 = 3^k\cdot 6 \cdot 6 \implies k=1$$
Thus we must have $G= \mathbb{Z}/3\mathbb{Z} \oplus \mathbb{Z}/9\mathbb{Z} \oplus\mathbb{Z}/7\mathbb{Z} $

A: In $\mathbb{Z/7Z}$ there are $1$ element of order $1$ and $6$ elements of order $6$. In $\mathbb{Z/9Z}$ there are $1$ element of order $1$, $2$ elements of order $2$, and $6$ elements of order $9$. A $9$ and a $7$ give you $36$ elements of order $63$, so you need one $3$ to get $108$.

A: Here's another approach: in any finite abelian group $G$, if $g\in G$ has maximal order, then we can write
$$ G = \langle g\rangle\times K $$
for some subgroup $K$.
Applying that to your case, we see we can write
$$ G = C_{63}\times K $$
If there were elements of order $63$ in $K$, we could go again and write
$$ G = C_{63}\times C_{63}\times H $$
but then $G$ would have more than $108$ elements of order $63$. Thus $ G = C_{63}\times K$ and $G$ then has $36*|K|$ elements of order $63$. Thus $K$ has order $3$ and you're done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get matching strings in a variable I am trying to fetch the matching strings from a variable.
For example,
$out = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall\{F1E1501C-B95C-42E0-BFD4-757DF1B961D1}"

I need the value inside "{ }".

A: You can use a RegEx for this:
$out = "Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall{F1E1501C-B95C-42E0-BFD4-757DF1B961D1}"

$out -match "^.*{(?<guid>.*)}$" | Out-Null

You can then access the value like this:
$matches.Guid

-match produces a bool that lets you know if it was successful or not.  Here I discard it by sending it to Out-Null, but you can use it to decide if you should proceeed, by, say, wrapping it in an if:
if ($out -match "^.*{(?<guid>.*)}$")
{
   # Do something
}

Note that you can get a more accurate match for the GUID using the patterns mentioned here:
RegEx for GUID


text:
Q: Change maxlen attribute of collections.deque I've been working on a small project lately where the maxlen attribute of a collections.deque is set in accordance with a user-configurable parameter. State is stored between sessions; any active deque forms part of this state. There is therefore a need to change the maxlen attribute of each restored deque if there are configuration changes between sessions. At the moment, I am doing it like so:
if current_setting != last_setting:
    # Deques are in a dictionary
    for k in dictionary:
        # Other data types and structures exist in this dictionary
        if dictionary[k].__class__() == deque():
            dictionary[k] = deque([*dictionary[k]], maxlen=current_setting)

Creating a new deque and unpacking the old one into it seems inefficient. My question is if there is either;

*

*A way to change the value of the maxlen attribute of a deque after creation or, if this is impossible/ill-advised;

*A more efficient way to do what is achieved in the example above?

A: As CKM's comment tells, changing the maxlen is impossible since it is a read-only attribute.
>>> d = deque("abcdefghij", maxlen=10)
>>> len(d)
10
>>> d
deque(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'], maxlen=10)
>>> d.maxlen = 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: attribute 'maxlen' of 'collections.deque' objects is not writable

In order to change the maxlen, you have to create a new deque object with the correct maxlen like this:
>>> NEW_MAX_LENGTH = 3
>>> d = deque("abcdefghij", maxlen=10)
>>> d2 = deque(d, maxlen=NEW_MAX_LENGTH)
>>> d2
deque(['h', 'i', 'j'], maxlen=3)

See the Python docs for more info.


text:
Q: Dynamic Button Click on Tab Control - Tab Pages C# I have an application that needs to click on button located on tab pages. So for example:
Tabcontrol has Tabpage1, Tabpage2, .... TabpageN
and each tabpage has a buttonX that performs a taskX.
Now supposing, I'm on TabPage1 and I want to Click ButtonX on Tabpage3 without changing tabindex/selectedindex. How can I do that?

A: Generally one would use PerformClick but I've noticed it failing on TabControl. So if not dependent on EventArgs, create a sub method for the click event e.g.
private void button1_Click(object sender, EventArgs e)
{
    Button1PerformClick();
}

private void Button1PerformClick()
{
    MessageBox.Show("Button1");
}

Than calling
private void button2_Click(object sender, EventArgs e)
{
    Button1PerformClick();
}

Doesn't matter in regards to which tab the button is on in this case.


text:
Q: Quarkus Reactive PostgreSQL Vert.x - Cannot resolve method 'thenCompose' in 'Query' I'm having this problem no matter what dependency I import. I followed the guide in https://quarkus.io/guides/reactive-postgres-client. Using another dependency - not "by" Quarkus, for example - doesn't solve it either. It's in this piece of code:
private void initDatabase() {
    client.query("DROP TABLE IF EXISTS fruits")
            .thenCompose(r -> client.query("CREATE TABLE fruits (id SERIAL PRIMARY KEY, name TEXT NOT NULL)"))
            .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Orange')"))
            .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Pear')"))
            .thenCompose(r -> client.query("INSERT INTO fruits (name) VALUES ('Apple')"))
            .toCompletableFuture()
            .join();
}

A: This page is no longer valid, I'm not sure why it wasn't deleted from the website. Here's the updated one: https://quarkus.io/guides/reactive-sql-clients
With Quarkus in most cases you should use io.vertx.mutiny.pgclient.PgPool.
The method implementation is:
private void initdb() {
    client.query("DROP TABLE IF EXISTS fruits").execute()
            .flatMap(r -> client.query("CREATE TABLE fruits (id SERIAL PRIMARY KEY, name TEXT NOT NULL)").execute())
            .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Kiwi')").execute())
            .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Durian')").execute())
            .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Pomelo')").execute())
            .flatMap(r -> client.query("INSERT INTO fruits (name) VALUES ('Lychee')").execute())
            .await().indefinitely();
}


text:
Q: spring-boot rest application on weblogic I have a spring boot rest application working fine on Tomcat.
My goal was to deploy the same on weblogic. I have followed the steps mentioned on spring site here
I don't have a web.xml file in the project.
After deployment I ran into this error.
java.lang.IllegalStateException: No thread-bound request found:
Are you referring to request attributes outside of an actual web request,
or processing a request outside of the originally receiving thread? If you are actually operating with
in a web request and still receive this message, your code is probably running outside
of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener
or RequestContextFilter to expose the current request.
        at org.springframework.web.context.request.RequestContextHolder.currentR
equestAttributes(RequestContextHolder.java:131) ~[spring-web-4.3.13.RELEASE.jar:
4.3.13.RELEASE]

The same requests work fine in tomcat. I am not sure if I need to include a web.xml file with ContextLoaderListener. But I wonder how it's not a problem in tomcat container.


text:
Q: android error while installing .apk on emulator I'm pretty much new to android development.I made a very basic program and when I try to run it on the emulator,the following error is encountered:
[2014-07-13 15:54:26 - AndroidLove] Starting activity com.example.androidlove.MainActivity on device emulator-5554
[2014-07-13 15:54:32 - AndroidLove] Installation failed due to invalid URI!
[2014-07-13 15:54:32 - AndroidLove] Please check logcat output for more details.
[2014-07-13 15:54:32 - AndroidLove] Launch cancelled!
Any help would be appreciated!

A: There can be many reasons failing the apk installation on your emulator.
Have a look here :
Installation failed due to an invalid URI


text:
Q: If $x=\cos t,y=\cos(2t+\pi/3)$ find an analytical relation between $x$ and $y$. I'm having a bit of trouble figuring this out. At the moment this is the near solution I have:
$$y=\frac12(2\cos^2 t-1)-\sqrt{3}\sin t\cos t.$$
I should be just about to solve it but find myself stuck. I appreciate any hint on how to "eliminate" that sine, or any other way in which I could express $x$ as an expression that depends on $y$. Thanks!

A: *

*To find y as a function of x, just replace t with $\arccos x$.

*To find x as a function of y, just take the arccos of the second expression, and try to express t in terms of $\arccos y$.

A: You're almost there. You have correctly used that
$$
\cos\left(2t+\frac{\pi}{3}\right)=\frac{1}{2}\cos2t-\frac{\sqrt{3}}{2}\sin2t
$$
so
$$
2y=2\cos^2t-1-2\sqrt{3}\sin t\cos t=2x^2-1-2x\sqrt{3}\sin t.
$$
Thus
$$
2x\sqrt{3}\sin t=2x^2-1-2y.
$$
Hence
$$
12x^2(1-x^2)=(2x^2-1-2y)^2.
$$


text:
Q: When printing X variable it prints "123" then the actual variable value When you type in 4 it should output only 2 but instead it outputs 12, same goes for 6 it outputs 123 and so on and so forth
int main() {
    int salary, yearsOfService, X; //rounded off for computation of bonuse
    string companyName;

    std::cin >> yearsOfService;

    if (yearsOfService >= 1){ //X is rounded off case number for amount of years
        X = 0;
        X = 1;
        std::cout << X;

        if (yearsOfService>=2){
            X = 0;
            X = 2;
            std::cout << X;
        }
        if (yearsOfService>=5){
            X = 0;
            X = 3;
            std::cout << X;
        }
        if (yearsOfService>=6){
            X = 0;
            X = 4;
            std::cout << X;
        }
        if (yearsOfService>=11){
            X = 0;
            X = 5;
            std::cout << X;
        }

    }
}

A: Your program is doing exactly what you told it to do.  It will run down and execute those statements in sequence.  It sounds like what you're trying to do is this:
X = 0;
if (yearsOfService >= 11)
    X = 5;
else if (yearsOfService >= 6)
    X = 4;
else if (yearsOfService >= 5)
    X = 3;
else if (yearsOfService >= 2)
    X = 2;
else if (yearsOfService >= 1)
    X = 1;

if (X != 0) std::cout << X;

Another way instead of using else is to just add 1 to X any time one of these conditions is satisfied.  Then you can run them in any order.


text:
Q: how to write test functions for decorators? from __future__ import print_function
    def nonnegative(f):
    def wrapper(xs):
        for x in xs:
            if x < 0:
                raise ValueError("{} < 0".format(x))
        return f(xs)
    return wrapper

    @nonnegative
    def inputs(xs):
        for x in xs:
            print(x)

inputs([1, 2, 3, 4])
inputs([-1])}

This is my decorator function. how can i write a test function for it? is there any common way?

A: Sure ... Just make a (really!) simple function and decorate it and see if it has the proper behavior.
import unittest

class TestNonNegative(unittest.TestCase):
    def setUp(self):
        super(TestNonNegative, self).setUp()

        self.fn = nonnegative(lambda x: x)

    def test_raises(self):
        with self.assertRaises(ValueError):
            self.fn([1, 2, 3, -1])

        # doesn't raise with all positive numbers
        expected = [1, 2, 3]
        self.assertEqual(self.fn(expected), expected)

If you really wanted to, you could even use a mock.Mock instance instead of the lambda function and then make sure that it was never called when raising.


text:
Q: Generate 2 columns when using LEFT JOIN on 3 tables I have 3 tables:
Call table:
    +-----------+-------------+
    | CallId    | CallerName  |
    +-----------+-------------+
    | A         | Alice       |
    | B         | Bruno       |
    | C         | Tina        |
    | D         | Marina      |
    | E         | Elena       |
    +-----------+-------------+

AnsweredCall table
   +-----------+-------------+
   | CallId    | PhoneNumber |
   +-----------+-------------+
   | A         | 1234567     |
   | B         | 45678       |
   | C         | 1598        |
   +-----------+-------------+

AllCallsDetail table:
+--------+--------+-------+-------------+
| CallId | Caller | Callee| CallType    |
+--------+--------+-------+-------------+
| A      |   1234 |  1111 |        1    |
| B      |   4567 |  2222 |        2    |
| C      |   8927 |    -1 |        2    |
| D      |   4567 |  2562 |        2    |
| E      |   8927 |    -1 |        1    |
+--------+--------+-------+-------------+

I have to create a view that contains all recordings from Call table joined with AnsweredCall table (where exist values, where not, display null ) and joined with AllCallsDetails i have to display two colums filtered by CallTypeId.
First column  is like :
(SELECT allCalls.Caller Where (allCalls.CallType= 1)) as Caller

Second column is like :
(SELECT allCalls.Callee Where (allCalls.ConferenceType!= 1 and  allCalls.Callee != '-1')) as Callee

Right now i have something like this, but Callee column is always null and i dont understand why, because Caller column contains good values.
 Create VIEW [dbo].[CallView]
           as
        Select      NEWID() As Id
                    ,callTbl.CallId
                    ,callTbl.CallerName
                    ,answeredCallTbl.PhoneNumber
                    ,(SELECT callDetailTbl.Caller Where(callDetailTbl.CallType = 1)) as Caller
                    ,(SELECT callDetailTbl.Callee Where (callDetailTbl.CallType != 1 and  callDetailTbl.Callee != '-1')) as Callee

     FROM [dbo].[Call] as callTbl
     left join [dbo].[AnsweredCall] answeredCallTbl on callTbl.CallId= answeredCallTbl .CallId
     left  join [dbo].[AllCallsDetails] callDetailTbl on callTbl.CallId= callDetailTbl .CallId

Output must should look like:
+----+--------+------------+-------------+--------+-------+
| Id | CallId | CallerName | PhoneNumber | Caller | Calle |
+----+--------+------------+-------------+--------+-------+
|  1 | A      | Alice      | 1234567     | 1234   | null  |
|  2 | B      | bruno      | 45678       | null   | 2222  |
|  3 | C      | tina       | 1598        | null   | null  |
|  4 | D      | Marina     | null        | null   | 2562  |
|  5 | E      | Elena      | null        | 8927   | null  |
+----+--------+------------+-------------+--------+-------+

A: You can probably use a CASE statement for this like
 Create VIEW [dbo].[CallView]
           as
    Select      NEWID() As Id
                ,callTbl.CallId
                ,callTbl.CallerName
                ,answeredCallTbl.PhoneNumber
                ,case when coalesce(callDetailTbl.CallType, 0) = 1 then callDetailTbl.Caller end as Caller
                ,case when (coalesce(callDetailTbl.CallType,0) != 1 and  coalesce(callDetailTbl.Callee, '') != '-1') then callDetailTbl.Callee end as Callee

 FROM [Call] as callTbl
 left join [AnsweredCall] answeredCallTbl on callTbl.CallId= answeredCallTbl .CallId
 left  join [AllCallsDetail] callDetailTbl on callTbl.CallId= callDetailTbl .CallId

See a Demo Fiddle


text:
Q: Will Django model instance always be populated when calling save()? I have a model where I am overriding the save() function to add SearchVector's. I need to preprocess one of the instance's fields so I am overriding the save function:
class Student(models.Model):
  first_name = models.CharField(max_length=255, default="")
  last_name = models.CharField(max_length=255, default="")
  search_vector = SearchVectorField(null=True)

  def save(self, *args, **kwargs):
    sv = SearchVector(Value(self.first_name)) + SearchVector(Value(self.last_name))
    if len(self.last_name) > 3:
      sv += SearchVector(Value(self.last_name[0:3]))
    self.search_vector = sv
    super().save(*args, **kwargs)

Can I expect that all fields (first_name & last_name) of the instance are always populated inside the save() function? I noticed that the instance loading function from_db seems to suggest that model instances can be created with a partial set of fields. Does this mean that first_name could be None on the save() call?


text:
Q: Search strings in Excel Column & Delete the column in PowerShell I am new to this forum so please excuse if this is not the right channel.
I am looking for some help in searching the strings which are in Excel Column Header "$Col4 / $Col6 / $Col7 / $Col19 / $Col22 / $Col27" and if found, then delete the entire column.
The concern is if I am changing the line as per below then it goes into loop but reads only Row 1 of the sheet. But if I keep as per the below code then because it reads all the $col value as Row 1, it gives the result as "Nothing found".
if (($sheet.cells.Item($row,$column).text -eq $Col4) -or ($sheet.cells.Item($row,$column).text -eq $Col6) -or ($sheet.cells.Item($row,$column).text -eq $Col7) -or ($sheet.cells.Item($row,$column).text -eq $Col19) -or ($sheet.cells.Item($row,$column).text -eq $Col22) -or ($sheet.cells.Item($row,$column).text -eq $Col27)) {

$column++

$Col4 = 'Col4'

$Col6 = 'Col6'

$Col7 = 'Col7'

$Col19 = 'Col19'

$Col22 = 'Col22'

$Col27 = 'Col27'

$Results = "C:\Temp\Results.xls"

$excel = New-Object -Com Excel.Application -Property @{Visible = $false}

# open Excel file

$workbook = $excel.Workbooks.Open($Results)

$sheet = $workbook.ActiveSheet

$row = 1

$column = 1

$found = $false

# Search for /TESTOut in A1

$info = $sheet.cells.Item($column, $row).Text

# Write-Host $info

if($info -eq "/Test"){

$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row

}

$WorksheetRange = $sheet.UsedRange

$RowCount = $WorksheetRange.Rows.Count

$ColumnCount = $WorksheetRange.Columns.Count

While ($row -ne $RowCount) {

If ($sheet.cells.Item($row,$column).text -eq $Col4) {

$column++

If ($sheet.cells.Item($row,$column).text -eq $Col6) {

$column++

If ($sheet.cells.Item($row,$column).text -eq $Col7) {

$column++

If ($sheet.cells.Item($row,$column).text -eq $Col19) {

$column++

If ($sheet.cells.Item($row,$column).text -eq $Col22) {

$column++

If ($sheet.cells.Item($row,$column).text -eq $Col27) {

Write-Host -ForegroundColor Green "Found match at Row: " $row # Replace this line to delete the Column

$found =$true

}

}

}

}

}

}

Else {

$row++

$column = 1

}

}

If (!($found)) {

Write-Host -ForegroundColor Red "Nothing found" # This is for test purpose only. Do Nothing.

}

$workbook.Close($true) # Close workbook and save changes

$excel.Quit() # Quit Excel

[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM

A: This could be done with a simple counting loop running backwards:
# columns to delete
$deleteThese = 'Col4', 'Col6', 'Col7', 'Col19', 'Col22', 'Col27'

$file  = 'C:\Temp\Results.xls'
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
# open the Excel file
$workbook = $excel.Workbooks.Open($file)
$sheet    = $workbook.ActiveSheet
# get the number of columns in the sheet
$colMax   = $sheet.UsedRange.Columns.Count

# loop through the columns to test if the column header is found in the $deleteThese array
# do the loop BACKWARDS, otherwise the indices will change on every deletion.
for ($col = $colMax; $col -ge 1; $col--) {
    $header = $sheet.Cells.Item(1, $col).Value2
    if ($deleteThese -contains $header) {
        $null = $sheet.Columns($col).EntireColumn.Delete()
    }
}

# save and exit
$workbook.Close($true)
$excel.Quit()
# clean up the COM objects used
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()


text:
Q: Python, VK API: как проверить на подписку пользователей на сообщество? Как проверить, подписан ли человек на моё сообщество?
Этот код проверяет, подписан ли я на какую-либо группу, а как быть в обратном направлении, т.е. как узнать, подписан ли определённый человек на мою группу?
import vk
def Authorization():  # Авторизация пользователя
    return vk.API(vk.AuthSession(app_id='***',
                                user_login='***',
                                user_password='***',
                                scope='groups'))

def foo(session):
    if session.groups.isMember(group_id = 'Group id'): # Проверяем является ли пользователь участником сообщества
        return 'Вы уже подписаны.'
    session.groups.join(group_id = 'Group id')  # ID Группы. Подписываемся
    return 'Спасибо за подписку {0}'.format(session.users.get()[0]['first_name'])

if __name__ == '__main__':
    print(foo(Authorization()))

A: Спасибо, разобрался, нашёл,  в чём была проблема, я на самом деле не правильно запускал сессию. usr_id -  передаётся при вызове функции
Вот, у меня так, кому-то может пригодится:
def user_aprove(user_id, token):
    if api.groups.isMember(access_token = token, group_id = 'komnata_risovak',user_id = user_id):# Проверяем является ли пользователь участником сообщества
        return 1
    return 0


text:
Q: Latex Missing $ Help How much glucose $(C_6H_{12}O_6)$ per liter should be used for an intravenous solution
to match the $7.65$ atm at $37 °C$ osmotic pressure of blood?

What's wrong with this LaTeX Code? I can't figure it out, it says missing $ inserted.

A: *

*Chemistry: The letters for the atoms are set in math italics, if used in math mode. I would use a dedicated package (e.g., the example uses chemmacros) to get proper typesetting of the chemical formula.

*Numbers and units: The example uses package siunitx for the numbers with units. The package takes care of the symbols (degree celsius), the spacing between the number and unit and prevents line breaks before the unit.
Example file:
\documentclass{article}
\usepackage{chemmacros}
\usepackage{siunitx}
\DeclareSIUnit\atm{atm}
\begin{document}
How much glucose (\ch{C_6H_{12}O_6}) per liter should be used for an
intravenous solution to match the \SI{7.65}{\atm} at \SI{37}{\celsius}
osmotic pressure of
blood?
\end{document}


text:
Q: How to derive a definition of definite integral from another definition Consider the following exercise:

If $f$ is uniformly continuous in $[a,b]$ then show that $$\int_{a}^{b}f(x)dx=\lim_{n\to\infty}\frac{b-a}{n}\sum_{i=0}^{n-1}f\left(a+\frac{i(b-a)}{n}\right).$$

The definition of Riemann integrable I have is:
A function $f$ is Riemann integrable in $[a,b]$ if and only if there is a number $L\in\mathbb{R}$ such that for every $\varepsilon>0$ there is a partition $P_{\varepsilon}$ such that the inequality $$\left|S(,f,P;\xi_0,...,\xi_{n-1})-L\right|<\varepsilon$$ holds for every partition $P=\{a_0,...,a_n\}$ finer than $P_{\varepsilon}$ and every election of points $\xi_i\in\{a_i,...,a_{i+1}\}.$ The number $L$ is defined as $$L=\int_{a}^{b}f(x)dx.$$ And $S(f,P;\xi_0,...,\xi_{n-1})$ denotes the Riemann sum of $f$ with respect to a partition $P$.
Is it necessary to use that definition of integral to prove the exercise? If so, how can I do it? Any help is welcome.

A: Further hint:
With $x_i = a+\frac{i(b-a)}{n}$, we have $x_{i+1}- x_i = \frac{b-a}{n}$ and
$$\left|\int_a^b f(x) \, dx -  \frac{b-a}{n}\sum_{i=0}^{n-1}f\left(a+\frac{i(b-a)}{n}\right)\right|= \left|\sum_{i=0}^{n-1}\int_{x_i}^{x_{i+1}} f(x) \, dx -  \frac{b-a}{n}\sum_{i=0}^{n-1}f\left(x_i\right)\right|\\= \left|\sum_{i=0}^{n-1}\int_{x_i}^{x_{i+1}} [f(x)-f(x_i)] \, dx \right| \leqslant \ldots $$


text:
Q: how to check NSString format from UIPasteBoard I am allowing the user to copy a registration key from my website, the NSStirng is then saved to the clipboard and when the application opens with the registration dialog I check the clipboard right away using this code -
NSString *registrationCode = [UIPasteboard generalPasteboard].string;

Now that I have the value from the pasteboard I want to check its format.. which should be something like AAAA-AAAA-AAAA-AAAA so in essance No numbers, no spaces (including at the front and end), no lower case, no special characters... just uppercase characters. How could I achive this?

A: Try doing this in your code:
NSCharacterSet * everythingThatsAllowedSet = [NSCharacterSet characterSetWithCharactersInString: @"ABCDEFGHIJKLMNOPQRSTUVWXYZ-"];
NSCharacterSet * characterSetFromRegistrationCode = [NSCharacterSet characterSetWithCharactersInString: registrationCode];

if([everythingThatsAllowedSet isSupersetOfSet: characterSetFromRegistrationCode ] == YES)
    NSLog( @"this is a valid registration code");
else
{
    // if there are any characters in the registration code that aren't members of
    // the everythingAllowed set, the "isSupersetOfSet" test will fail
    NSLog( @"this has invalid characters");
}


text:
Q: xhr status 0 ajax Tengo un script donde uso ajax que no entra en success
$.ajax({

    data: parametros,
    url: '../gestionUsuario/insertUsuario.php',
    type: 'post',

    success: function(response) {
        alert("hola success");
        if (response == 1) {
            alert("insertado");
            //$('#success_message').html('
USUARIOS INSERTADO
');
        } else {
            alert("no insertado");
            //$('#success_message').html('
ERROS INSERCCION
');
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert("estatus " + xhr.status);
        alert("estatus " + xhr.responseText);
        alert("error " + thrownError)
    }

La ruta esta bien puesto que el php me inserta en la base de datos pero la respuesta entra en error y el status muestra 0.

A: te recomiendo revisar lo que esta retornando el código de PHP, en el caso del ejemplo he probado creando un archivo php con el contenido 1 y funciona correctamente, también lo probé con 0 y trabaja bien en mi localhost.
te recomiendo usar console.log(response) con el fin de averiguar lo que php esta retornando
var parametros = {
                "id" : 1,
                "nombre" : "Manuel",
        };
$.ajax({

    data: parametros,
    url: 'insertUsuario.php',
    type: 'post',
    beforeSend: function () {
                    console.log('Se inicia la petición');
    },
    success: function(response) {
        console.log(response);
        alert("hola success");
        if (response == 1) {
            alert("insertado");
            //$('#success_message').html('
USUARIOS INSERTADO
');
            }else{
            alert("no insertado");
            //$('#success_message').html('
ERROS INSERCCION
');
        }
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert("estatus " + xhr.status);
        alert("estatus " + xhr.responseText);
        alert("error " + thrownError);
    }
});

la respuesta se debe hacer con print o echo ya que javascript lo que lee es el texto plano generado, en el comentario anterior muestra una forma de averiguar si la consulta se hizo correctamente con affected_rows
if (mysqli_affected_rows($con)>0) { return 1; } else { return 0; }

Sin embargo para una petición ajax es recomendale hacer lo siguiente
if (mysqli_affected_rows($con)>0) { echo 1; } else { echo 0; }


text:
Q: why ListView does not filled while I am using AsyncTask? I am writing an app that uses Google book search API , what the app suppose to do is to display a list of books based on a search query that i provide within the app's code as a String, i use an AsyncTask inner class to handle the background work (making HTTP request , JSON formatting ...etc), I also have book costume adapter and book class to get the data from , my problem is the app dose not display any book in the list view .
here's my code:

My Activity:

public class MainActivity extends AppCompatActivity {

    final static String bookUrl = "https://www.googleapis.com/books/v1/volumes?q=android&maxResults=6";
    private BookAdapter bookAdapter;

    private ArrayList<Book> books;

    private ListView list;

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

         list = (ListView) findViewById(R.id.list);
         new BookAsynck().execute(bookUrl);

    }

    private class BookAsynck extends AsyncTask<String, Void, ArrayList<Book>> {
        @Override
        protected ArrayList<Book> doInBackground(String... strings) {
            books = Utils.fetchBookData(bookUrl);
            return books;
        }

        @Override
        protected void onPostExecute(ArrayList<Book> books) {
            bookAdapter = new BookAdapter(MainActivity.this, books);
            list.setAdapter(bookAdapter);
        }
    }

}

My Util class :

    public class Utils {
    public static final String LOG_TAG = Utils.class.getSimpleName();

    public static ArrayList<Book> fetchBookData(String requestUrl) {

        ArrayList<Book> bookList = new ArrayList<>();

        URL url = CreateURl(requestUrl);
        String json = null;
        try {
            json = makeHttpRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error closing input stream", e);
        }
        bookList = extractBookData(json);
        return bookList;
    }

    public static URL CreateURl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error with creating URL ", e);
        }
        return url;
    }

    //make http  request and return a string containing the response
    public static String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        //if the url is null return empty string
        if (url == null) {
            return jsonResponse;
        }

        HttpURLConnection urlcon = null;
        InputStream inputstream = null;
        try {
            urlcon = (HttpURLConnection) url.openConnection();
            urlcon.setRequestMethod("GET");
            urlcon.setReadTimeout(1000 /*milleseconds*/);
            urlcon.setConnectTimeout(1500 /*milleseconds*/);
            urlcon.connect();
//if the request wass Successul (code 200)
            // get the input stream and decode it

            if (urlcon.getResponseCode() == 200) {
                inputstream = urlcon.getInputStream();
                jsonResponse = readFromStream(inputstream);
            } else {
                Log.e(LOG_TAG, "Error response code " + urlcon.getResponseCode());

            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving the book JSON results", e);
        } finally {
            if (urlcon != null) {
                urlcon.disconnect();
            }
            if (inputstream != null) {
                inputstream.close();
            }
        }

        return jsonResponse;
    }

//decode the inputstream into string that conatin the Jsresponse from the Server

        private static String readFromStream(InputStream inputStream) throws IOException {
            StringBuilder output = new StringBuilder();
            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
                BufferedReader reader = new BufferedReader(inputStreamReader);
                String line = reader.readLine();
                while (line != null) {
                    output.append(line);
                    line = reader.readLine();
                }
            }
            return output.toString();
        }

        public static ArrayList<Book> extractBookData(String json) {
            ArrayList<Book> booklist = new ArrayList<>();

            if (TextUtils.isEmpty(json)) {
                return null;
            }

            try {
                JSONObject base = new JSONObject(json);
                JSONArray itemsArray = base.optJSONArray("items");

                for (int i = 0; i < itemsArray.length(); i++) {
                    JSONObject first = itemsArray.getJSONObject(i);
                    JSONObject volume = new JSONObject("volumeInfo");
                    String title = volume.getString("title");
                    JSONArray authorsArray = volume.getJSONArray("authors");
                    String author = authorsArray.getString(0);

                    Book b = new Book(title, author);
                    booklist.add(b);
                }

            } catch (JSONException e) {
                Log.e(LOG_TAG, "Problem parsing the book JSON results", e);
            }
            return booklist;
        }
    }

My Book Adapter:

    public class BookAdapter extends ArrayAdapter<Book> {
    public BookAdapter(Context c, ArrayList<Book> book) {
        super(c, 0, book);
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View list = convertView;
        if (list == null) {
            list = LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);

        }
        Book b = getItem(position);

        TextView titleTextView = (TextView) list.findViewById(R.id.title);
        titleTextView.setText(b.getName());

        TextView author = (TextView) list.findViewById(R.id.author);
        author.setText(b.getAuthor());

        return list;
    }
}

A: It looks like you missed calling your asynctask inside activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

 list = (ListView) findViewById(R.id.list);
new BookAsynck().execute(bookUrl);
}

A: Welcome to stackoverflow !!
Beginning at Android 9, requests without encryption will not work, that means HttpsURLConnection will work but HttpURLConnection will not.
Then the URL you try to connect must have a https:// access or you should include this in your manifest
android:usesCleartextTraffic="true"

A: Change the below line from onCreate()
ListView list = (ListView) findViewById(R.id.list);

to
list = (ListView) findViewById(R.id.list);


text:
Q: Get array value and put it into a variable (multidimensional array?) When a print_r() an array $stats, I get the following:
Array ( [0] => Array ( [like] => 71 [dislike] => 372 [total] => 443 [like_s] => 78 [dislike_s] => 291 [total_s] => 369 [final] => 11 ))

I want to get the [dislike_s] value and put it into a variable.
I have attempted this:
$statss = $stats['dislike_s'];

But it did not work. I have also tried $statss = $stats['dislike_s'][0]; without result.
What am I doing wrong?

A: You are missing a level of your array
Array ( [0] => Array ( [like] => 71
       //^ this level

Also you are using the wrong variable, as you said your array is stored in $stats so
$total_revision = $stats[0]['dislike_s'];

A: $stats is a two dimensional Array, i.e. it is an array of arrays. You can see this from the output of print_r. You have something that looks like `Array ( [0]=>Array(...)). Therefore, when accessing an element of the inside array, you can think of it like this:
$inner_array=$stats[0];
$total_revisions=$inner_array['dislike_s'];

Php gives you a shorthand for combining these steps(pretty much all languages do) and it looks like $total_revisions=$stats[0]['dislike_s'] but intuitively it's the same thing. You're saying "in the array $stats[0] give back the value of array element 'dislike_s'"


text:
Q: cv::connectedComponentsWithStats in OpenCV 3.2.0 sometimes crashes with gcc 6.2 Using this simple standalone demo:
#include <opencv2/opencv.hpp>

#include <iostream>

int main(int argc, char *argv[]) {
  // unsigned char data[] = {1, 0, 1}; // crashes
  unsigned char data[] = {1, 1, 0}; // does not crash

  cv::Mat1b testImage = cv::Mat1b(3, 1, data);

  cv::Mat labeledImage;
  cv::Mat stats;
  cv::Mat centroids;
  int neighborhood = 8;

  int componentCount = cv::connectedComponentsWithStats(
      testImage, labeledImage, stats, centroids, neighborhood);

  std::cout << "componentCount: " << componentCount << std::endl;

  return EXIT_SUCCESS;
}

With gcc 5.4 it works fine for both 'data' values. With gcc 6.2, it works fine for {1,1,0} but dumps this with data = {1,0,0}:
======= Memory map: ========
00400000-00407000 r-xp 00000000 08:01 15214967                           /home/doria/build/Examples/c++/OpenCV/Bug/Bug
00606000-00607000 rw-p 00006000 08:01 15214967                           /home/doria/build/Examples/c++/OpenCV/Bug/Bug
020b2000-0216c000 rw-p 00000000 00:00 0                                  [heap]
7f2608000000-7f2608021000 rw-p 00000000 00:00 0
7f2608021000-7f260c000000 ---p 00000000 00:00 0
7f260cc1d000-7f260cc24000 r-xp 00000000 08:01 10883576                   /lib/x86_64-linux-gnu/librt-2.23.so
7f260cc24000-7f260ce23000 ---p 00007000 08:01 10883576                   /lib/x86_64-linux-gnu/librt-2.23.so
7f260ce23000-7f260ce24000 r--p 00006000 08:01 10883576                   /lib/x86_64-linux-gnu/librt-2.23.so
7f260ce24000-7f260ce25000 rw-p 00007000 08:01 10883576                   /lib/x86_64-linux-gnu/librt-2.23.so
7f260ce25000-7f260ce28000 r-xp 00000000 08:01 10883446                   /lib/x86_64-linux-gnu/libdl-2.23.so

Any thoughts?

A: I'm responsible for the bug... sigh.
The problem is that the algorithm works in 2x2 blocks on the image. The maximum number of labels is one per block. Unfortunately if the image has an odd number of row and/or columns the estimate of number of blocks is wrong. So to fix this we should be doing:
const size_t Plength = ((img.rows + 1) / 2) * ((img.cols + 1) / 2);

We'll file a pull request to OpenCV for this today. Plus an improved set of tests. By the way we are still waiting for the parallel version (multicore) of the algorithm to be included.
We already filed in November a pull request for the parallel version (multicore) of the algorithm which also fixes the bug.
You can find the fixed version in OpenCV 3.3, since June 2017. Moreover it also includes the parallel version.

A: I can reproduce this bug with Visual Studio 2015 (vc14 x64).
The problems seems in line 352 of connectedcomponents.cpp:
 //A quick and dirty upper bound for the maximimum number of labels.
 const size_t Plength = img.rows*img.cols / 4;
 LabelT *P = (LabelT *)fastMalloc(sizeof(LabelT)* Plength);

With your test image, this PLength evaluates to 0:
 Plength = (3*1)/4 = 0

So *P has zero elements.
However, there is this assignement in a few places in the algorithm:
 P[lunique] = lunique;

and lunique has values >0. So this causes the heap corruption sometimes.
The fix should be to provide a better estimate of the upper bound Plength.


text:
Q: URI extract including trailing square bracket ] Using URI.extract to identify and deal with urls inside text (emails in this example).
A slightly annoying feature is that when extracting via schemes
urls = URI.extract(text, ['http', 'https', 'cid','mailto'])

Some of them come back with a trailing square bracket if they're included in the text with brackets around them.
e.g.
text = "Here's a link [mailto:bob@bob.com]"
urls = URI.extract(text, ['http', 'https', 'cid','mailto'])
=> ["mailto:bob@bob.com]"]

Noting that trailing closing bracket which then breaks any url parser that I use.
Is there a sensible way to stop that?
The documentation for URI.extract is sort of annoyingly short.

A: Maybe I missed something, but very simple text substitution could help? If you are familiar with tr unix tool, there's also String#tr for Ruby:
urls.map { |s| s.tr('[]', '') }
=> ["mailto:bob@bob.com"]


text:
Q: Extract a value from a text file in a specific position I have a file containing tons of information. It looks like this:
===============================================================================

   NSTEP       ENERGY          RMS            GMAX         NAME    NUMBER
     52      -4.8969E+05     5.1393E+00     1.7327E+03     P1         31

 BOND    =    29534.6906  ANGLE   =     2139.5547  DIHED      =     9235.7381
 VDWAALS =    51148.8783  EEL     =  -595288.4773  HBOND      =        0.0000
 1-4 VDW =     2741.3848  1-4 EEL =    26043.4789  RESTRAINT  =       29.3591
 DFTBESCF=   -15274.2075
 EAMBER  =  -489718.9594
 NMR restraints: Bond =    0.000   Angle =     0.000   Torsion =     0.000
===============================================================================

Now, I want to extract (and put in one column only) the value (here shown as -4.8969E+05) from the 'Energy' (or second) column in the line directly under the word ENERGY.
I tried to extract it with grep but have not been able to.

A: You seem to be saying "I want the second field from the line
immediately after the line that contains the word ENERGY
(in which ENERGY is the second field)."
If that's what you want, you can do it with
awk '/ENERGY/ { found_it=1; next;     }
    found_it  { print $2; found_it=0; }'

(Put your filename at the end of that command — right after the }' —
or pipe your data into the above command.)
This simply

*

*Looks for a line that contains the string ENERGY,

*

*sets a flag (found_it) when it does,

*and skips that line.

*When it encounters a line, and the found_it flag is set,
that means that the previous line contained ENERGY, so

*

*print the second word from that line, and

*clear (zero) the found_it flag, so we don't produce output
from any subsequent lines.

If you file has ENERGY on lines 4, 14 and 24,
then the above command will print the second field
from lines 5, 15 and 25.
If that's not what you want, a simpler approach is
awk '/ENERGY/ { found_it=1; next; }
    found_it  { print $2;   exit; }'

which is the same as the first one,
except, after it has printed the second field from line 5,
it just stops looking.
Even if ENERGY appears only once in the file,
this approach is preferable in that
it doesn't require reading the entire file,
but only up to the value you want.
These commands will:

*

*find the string ENERGY even if it is part of a larger word,
such as CENERGY, ENERGY-CONSUMING, ENERGYLEVEL or HIGH-ENERGY.

*find the string ENERGY
even if it is not the second field on its line.

*print the value of the second field,
not the field where it found ENERGY.

*not find Energy or energy.

*fail silently if ENERGY is on the last line.

If those are problems,
edit your question to specify your requirements.


text:
Q: problem with the proof of the fundamental theorem of algebra please see here(p.174-175 Elementary real and complex analysis
By Georgiĭ Evgenʹevich Shilov):
Image snapshot from google books:

Question is, why is $\displaystyle |H(z)| \lt 1/2$ true?

A: It is the definition of continuity in $0$. For any $\epsilon$ you can find $\delta$ such as $z$ lies in the disc centered in $0$ with radius $\delta$ implies $H(z)$ is in the disc centered on $H(0)=0$ with radius $\epsilon=1/2$.

A: It follows from continuity of polynomials: If $H$ is continuus at $z_0$ then for any $\varepsilon>0$ there exists $r>0$ such that if $|z-z_0|<r$ then $|H(z)-H(z_0)|<\varepsilon$.
Plug in $z_0=0$, $\varepsilon=\frac{1}{2}$ and remember that $H(0)=0$.


text:
Q: floating point exception trying to find prime numbers I have a program that generates prime numbers. This code works fine when i want the first 100 and 200 primes, but puts out a Floating point exception whenever I use a value above 300 for total. The problem seems to be in the array, but I don't understand what is happening.
#include<stdio.h>

int main()
{
    int total = 500;
    int primes[total];
    primes[0] = 2;
    int max = 1;
    int current = 3;
    int index = 0;
    printf("%d\n",2);
    while(max != total)
    {
        for(index = 0; index <= max + 1; index++)
        {
            if(index == max + 1){
                primes[index] = current;
                printf("%d\n",current);
                max = max + 1;
                current = current + 1;
                break;
            } else {
                if(current % primes[index] == 0){
                    current = current + 1;
                    break;
                }
            }
        }
    }
}

A: You have to ensure the expression current % primes[index] is never evaluated with a 0 value for primes[index]. A 0 value as the right operand of % operator invokes undefined behavior in C.

A:
your accessing beyond the end of primes[], in the debugger you write primes[index] where index == 500.. primes[500] doesn't exist


text:
Q: Stop int from increasing My game has a score. The score is represented by gameobjects. The score increases by 10 on a collision event. These events can not be stopped. I would like for the score to stop increasing on conditional "GameOver".
I am wondering how to stop the score from increasing since the triggering event can not be stopped. Making score = 0 is not good because I want to have the player's end score displayed. I need to somehow disconnect the score from the instantiations at the time of GameOver. Or I need to make the score integer stay the same at the time of GameOver. This is really a conceptual question and I'm not sure how to tackle this problem. Any ideas?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class ScoreHandler : MonoBehaviour {
public int score = 0;
public List<GameObject> destroyList = new List<GameObject>();
public static GameObject[] Score;

// Use this for initialization
void Start () {
    score -= 80;

}

// Update is called once per frame
void Update () {

}

void OnCollisionEnter (Collision col)
{
    if (col.gameObject.name == "carA") {
        score += 10;

    }
    if(col.gameObject.name == "carB")
    {
        score += 10;

    }
    if(col.gameObject.name == "carC")
    {
        score += 10;

    }
    if(col.gameObject.name == "carD")
    {
        score += 10;

    }
    if(col.gameObject.name == "carE")
    {
        score += 10;

    }
    if(col.gameObject.name == "carF")
    {
        score += 10;

    }
    if(col.gameObject.name == "carG")
    {
        score += 10;

    }
    if(col.gameObject.name == "carH")
    {
        score += 10;

    }

    foreach (var go in destroyList)
    {
        Destroy(go);
    }
    destroyList.Clear();

    string scoreText = score.ToString ();

    Score = new GameObject[scoreText.Length];

    for (int i = 0; i < scoreText.Length; i++) {

        Score[i] = (GameObject)Instantiate (Resources.Load (scoreText
[i].ToString ()));

        Score[i].layer = 8;
        Score[i].transform.localScale = new Vector3 (0.02F, 0.02F,
0.02F);
        Score[i].transform.localPosition = new Vector3 (0.013F + i *
0.01F, 0.12F, 0.0F);
        Score[i].transform.Rotate (0, 180, 0);

        destroyList.Add (Score[i]);

    }
  }

}

*This code box has a scroll bar.

A: If you have GameOver flag, things will get easier.
Suppose you have a flag called when game over occurs:
bool gameOverFlag = false;
.... //something else
void OnGameOver(){
    .... //something else
    gameOverFlag = true;
    .... //something else
}

And, only not to add score (while leaving everything else the same) when game over flag is true on collision event would be quite straight-forward:
if (col.gameObject.name == "carA") {
    score += gameOverFlag ? 0 : 10; //this is where ternary operator will come really handy
    //something else specific for carA, not for score
}

By implementing something like above, only your score won't be changed on collision

A: Why are objects colliding if the game is over?
One easy way to keep the game running in the background but stop the interaction is to disable the collider of the player when game is over.
GetComponent<Collider>().enabled = false;

One other solution would be to check if game is running and only add score then.
void OnCollisionEnter (Collision col)
{
    if(!gameRunning)
        return;

    // score logic
}

However, I would recommend that you separate your code parts to be able to control the different states of your game. If you don't want to use a State Machine you could use Enum States. This will make it easier to manage as your game gets more complex.

A: Just check if score is < 10 and also I suggest moving all your conditions in one block:
void OnCollisionEnter (Collision col)
{
    if ((col.gameObject.name == "carA" || col.gameObject.name == "carB" || col.gameObject.name == "carC"
      || col.gameObject.name == "carD" || col.gameObject.name == "carE"
      || col.gameObject.name == "carF" || col.gameObject.name == "carG"
      || col.gameObject.name == "carH") && score < 10 )
    {
        score += 10;
    }

//Rest of the code
}


text:
Q: Finding $\int_{\gamma}^{} \frac{1}{z^2-1}dz$ along the path $\gamma(t)=1+e^{it},t\in [0,2\pi]$ Here is my attempt (without using residue theorem or Cauchy, just basic stuff):
$$\int_{\gamma}^{} \frac{1}{z^2-1}dz=\frac{1}{2}\Big( \int_{\gamma}^{} \frac{1}{z-1}dz-\int_{\gamma}{}\frac{1}{z+1}dz\Big)=\frac{1}{2}\Big( \int_{\gamma}^{} \frac{1}{z-1}dz+\int_{-\gamma}{}\frac{1}{z+1}dz\Big)=\frac{1}{2}\Big( \int_{0}^{2\pi} \frac{ie^{it}}{1+e^{it}-1}dt+\int_{0}^{2\pi}\frac{-ie^{it}}{-1-e^{it}+1}dt\Big)= \int_{0}^{2\pi} \ idt=2\pi i$$
Is this correct? Any feedback is appreciated. Thank you in advance.


text:
Q: jQuery Mobile ignoring data-role="none" on form elements I'm dynamically injecting pages into my jQuery Mobile app.  Everything is working fine, except form elements.  It seems that data-role="none" is being ignored on form elements that are on the injected pages.

<input data-role='none' type='radio' name='type' id='type' value='none'/>None

<input data-role='none' type='radio' name='type' id='type' value='segments'/>Market Segments

    &nbsp <select data-role='none' id='segments'><option value='all'>All</option></select>

The radio buttons render as regular radio buttons, albeit with some screwy formatting.  The select button should appear as a regular dropdown, but it is being rendered as a jQuery Mobile dropdown instead.
Here's how the pages are being injected:
var t = results.rows.item(i).body;
var n = results.rows.item(i).name;
$("#"+n).remove();
$("body").append(t);
$("#"+n).appendTo($.mobile.pageContainer);
$("#"+n).attr('data-url',$("#"+n).attr("ID")).trigger('create');

Form elements on non-injected pages are working fine... any ideas?

A: By default jQuery Mobile will auto enhance form elements, if you want to tell JQM to ignore them you can add the data-role="none" attribute to the container, however you also need to set $.mobile.ignoreContentEnabled = true. The reason for this is because by default JQM doesn't check for the data-role="none" attribute (so as to not perform a check every time needlessly).
Keep in mind that you need to set the ignoreContentEnabled in the mobileinit event.

A: You should check if you are manually initialising those form controls. Since you are injecting those controls you may also be calling selectmenu('refresh') method. Just remove those calls and everything should work fine.


text:
Q: How to hide the parent table cell/row if child is hidden or having no data I have table (t1) which is binded with some dataset. One of the row of this table is having another table (t2). so t2 is a child of t1. I want to hide row of t1 if there is no data in t2.
I tried setting the visibility expression of t2 as =CountRows() = 0. With this t2 is hidden but there is an empty space created.
I think I have to set the visibility of t1 row which is containing t2. I tried the same expression but it did not work.
Can anybody please tell me how to hide row of t1 if there is no data in t2. Or is there anyway to bind the visibility of t2 with row visibility of t1?
Atul

A: you can set expression in row visibility property of table (t1) like:
IIF(CountRows("Dataset1") > 0,true,false)


text:
Q: What is the meaning of the blue line and the green line in MySQL workbench?
As shown in the figure, the Country table is combined with the City table by the green line, and the City table is combined with the Address table by the blue line. I can't figure out what's the meaning of the two kind of lines.

A: The connections show relationships (foreign keys). That should be clear.
When you hover with the mouse over a table figure, all connections are highlighted which either go out from or come in to that table.
Outgoing connections, that is, foreign keys defined on that table, which reference a different table are shown in green.
Incoming connections, that is, foreign keys defined in another table, which end on the current table are colored blue.
The referenced fields are colored the same way as their associated relationship.
Currently table city is active, so the foreign key from city.country_id to country.country_id is colored green (it's an outgoing connection). Table address has defined a foreign key to city, which is shown in blue. Now hover address and you will see that the connection color to city switches from blue to green.


text:
Q: How to detect the presence of certain device In a C# application, what are some good ways to detect the presence of certain device connected to the computer? Programatically, of course. I need to support Windows XP and 7.
Background
I've been given a huge C# application that uses some connected device. The devices are custom hardware and are not designed to use without the software. When the C# app starts, it searches for such connected devices and communicates with them when appropriate. There can be more than one connected devices. I haven't looked into the source code that searches the devices. The devices are plugged into the PC with either USB or serial cable. They appear as COM port in device manager. Sometimes there can be USB hub or serial to USB converters in between the PC and the device.
When the device is connected with certain USB hub, or certain serial to USB converter is used, sometimes the software cannot detect the device properly. Sometimes it varies from PC to PC. We're not sure if it causes for some driver.
I'm told to look into the device searching algorithm and if possible, come up with better solution and replace current implementation. I haven't done this sort of task before and I need to learn how Windows manage the devices under the hood.
How can I search for specific connected devices in C#? What are some good practice and what I should be aware of or avoid?

A: You can find all devices in registry: HKLM/CurrentControlSet/Enum ( http://msdn.microsoft.com/en-us/library/windows/hardware/ff546173(v=vs.85).aspx )
But there will be problem with serial port. You can't be certain in which device is connected to a serial port. It can be mobile phone, modem, mouse, your device, another custom device, etc. To guarantee that it is your device connected to a given serial port you must try to communicate with it. And if it responds in proper way - then yes, it is your device.
Because of this many programs that works with serial devices asks user to manually select serial port, where device is connected.
UPD:
Another link about enumerating serial ports: http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/afb62e84-53e5-4f17-ba91-8de15c4c2e38/


text:
Q: Argb value from rgb value I have rgb value 0, 69, 255. What would be it's argb value in silverlight. Is there any online converter that we can use.
Thanks in anticipation!

A: ARGB or RGBA works just like RGB except you need an extra value for alpha or transparency. Now, 0 alpha means fully transparent, while 255 alpha is totally opaque. So you probably want use the same RBG values with 255 for the alpha. You may also want to check out the documentation for Color.FromARGB.


text:
Q: Can't link OpenCL on Windows with GHC I'm trying to get the OpenCLRaw bindings to a point where I can use them on windows.  I've forked the the OpenCLRaw repo on github so I can make modifications as needed.  My branch is here:
https://github.com/dagit/OpenCLRaw
I've been mostly working out of my "FunPtr" branch.
The issue I'm having is this:  I installed AMD's OpenCL SDK, converted their Visual Studio specific .lib file to a file that gcc can handle (.a file), but ghc can't seem to link with it.  I get undefined symbols for everything I use in the OpenCL API.
I was able to build a "trivial" C program and link it using the .a file that I generated and gcc from mingw (not from the Haskell install).  I'm using the latest windows release of the Haskell platform.
These are the steps I used for generating the .a file:
http://forums.amd.com/forum/messageview.cfm?catid=390&threadid=138890
I used the commands in the example script (e.g., gendef and dlltool).  I've tried to use 32bit everything as much as possible, as I know that GHC will want everything to be 32bit, so I don't think it's a 32bit vs. 64bit issue.
Does anyone know if there is something different about invoking gcc under ghc instead of the gcc that I get from mingw?
I've also played with the ghc command line (I used cabal-dev --verbose=3 to inspect the command line) and I'm still unable to massage it into a working state.
Any help would be appreciated!

A: OpenCL uses the stdcall convention, but OpenCLRaw is using ccall.  This creates several issues.  The main one being that the linker wants the function name symbols to end in @NN where NN depends on the function.
As it turns out, the correct way to generate libOpenCL.a is as follows (from a mingw shell):
cp /c/Windows/System32/OpenCL.dll .
gendef OpenCL.dll
dlltool -l libOpenCL.a -d OpenCL.def -k -A

This will generate libOpenCL.a that ghc can correctly use for linking, but only if OpenCLRaw is modified to use stdcall instead of ccall.
Now that I understand the problem I can fix the OpenCLRaw bindings to do the right thing on Windows.
When I used pexports instead of gendef, I was able to remove the @NN from the symbol names, but then the resulting program started to segfault.  This is because the symbol was found but the calling convention was incorrect, probably leading to corrupted stacks.
The main lesson for me is that your FFI binding must match your C library's calling convention.


text:
Q: Using AJAX to confirm visitor activity? I'd like to enable my visitors to see how many people are currently connected to the same page as them (it's an interactive javascript page). So if there were 2 users, it would show to both users:
Users connected: 2
Since all users are constantly sending ajax requests to the server (every 1s), I thought there must be a good way to take advantage of that.
I'm guessing I should write some sort of a script that logs these ajax requests and writes to the database the number of different ajax requests it is currently getting.
But I'm not exactly sure how to implement this...

A: Insert session id into db when user visits your site, make a php file which counts number of rows, then ping that file using setInterval() function..


text:
Q: crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field - models.ForeignKey I'm trying to create a frontend data entry page for an existing model. However, when clicking the link, I get an error:
crispy_forms.exceptions.CrispyError: |as_crispy_field got passed an invalid or inexistent field

Just to be clear, adding the data from Django Admin works with no issues at all.
Having looked through a number of answered questions here, one did highlight what I believe could be problem, but it was out of context and did not provide much of an explanation.
I am trying to create a frontend entry form for users that corresponds with a foreign key.
models.py
class NewHandoff(models.Model):
    handoff_pk = models.AutoField(primary_key=True)
    handoff_date = models.DateField(auto_now_add=True,verbose_name="Handoff Date")
    shift1_pri = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Primary")
    shift1_sec = models.ForeignKey(Engineer,on_delete=models.CASCADE,verbose_name="Shift 1 Secondary")

    def __str__(self):
        return f"{self.handoff_date}"

    class Meta:
        verbose_name_plural = 'Handoffs'

# New Handoff Form
class NewHandoffForm(forms.ModelForm):
    class Meta:
        model = NewHandoff
        fields = ['shift1_pri','shift1_sec']

views.py
from django.shortcuts import redirect, render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http.response import HttpResponse
from django.contrib import messages
from .models import AttentionForm,  NewHandoffForm

# Handoff View Page
class NewHandoffView(LoginRequiredMixin,View):
    def get(self, request):
        greeting = {}
        greeting['heading'] = "New Handoff"
        greeting['pageview'] = "Handoff"
        return render (request,'handoff/handoff-new.html')

    def post(self, request):
        if request.method == "POST":
            if "add-new-handoff-button" in request.POST:
                create_new_handoff_form = NewHandoffForm(request.POST)
                create_new_handoff_form.save()
                return redirect("/handoff/handoff-create")

handoff-new.html
{% extends 'partials/base.html' %}
{% load static %}
{% load humanize %}
{% load crispy_forms_tags %}

{% block extra_css %}
    <link href="{% static 'libs/bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}" rel="stylesheet">
{% endblock %}

{% block contents %}

                    <form method="POST">
                        {% csrf_token %}

                                    {{ form.shift1_pri|as_crispy_field }}

                            <button type="submit" class="btn btn-primary waves-effect waves-light" name="add-new-handoff-button">Create New Handoff</button>

                    </form>

{% endblock %}

{% block extra_javascript %}
{% endblock %}

Someone mentioned in another post that forms should correlate with the declared form name {{ form.shift1_mod|as_crispy_field }} so it should actually be {{ create_new_handoff_form.shift1_mod|as_crispy_field }} but I have tried changing this and still get the same problem, plus, another model form works fine with just form despite the name of the form being attention_form.
Does anyone have any idea or can point me in the right direction? :)

A: You are not passing the form through the context in the template. As you are inheriting View, Add the following line in the get() and afterwards in the post() method appropriately:
form = NewHandoffForm()

# and then change return
return render(request,'handoff/handoff-new.html', {'form': form })

Also, you have a space after render in the get function. I hope this is a typo here, but not in your code.


text:
Q: XSLT Creating namespace dynamically My source XML is:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:DriverResponse xmlns:ns2="com/rsa/eosago/schema-1.1" xmlns:ns3="com/rsa/dkbm/schema-1.5">
  <IDCheckDriver>84714718</IDCheckDriver>
  <ErrorList>
    <ErrorInfo>
      2
      <Message>Принят в обработку</Message>
    </ErrorInfo>
  </ErrorList>
</ns2:DriverResponse>

Wanted output:
<?xml version="1.0" encoding="UTF-8"?>
<rsa:DriverStatusRequest xmlns:rsa="com/rsa/eosago/schema-1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <InsurerID>18800000</InsurerID>
  <IDCheckDriver>84714718</IDCheckDriver>
</rsa:DriverStatusRequest>

I expect this output using this XSL wich is called from Apache Camel:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  xmlns:ext="http://exslt.org/common" exclude-result-prefixes="ext">
<xsl:param name="RSA-InsurerID"/>
<xsl:param name="EOSAGO-schema-version"/>

<xsl:param name="schema" select="concat('com/rsa/eosago/schema-', $EOSAGO-schema-version)"/>
<xsl:variable name="schemaUrlDummy">
    <xsl:element name="ns2:dummy" namespace="{$schema}"/>
</xsl:variable>
<xsl:variable name="NS" select="ext:node-set($schemaUrlDummy)/*/namespace::ns2"/>

<xsl:template match="/">
    <xsl:element name="rsa:DriverStatusRequest" namespace="com/rsa/eosago/schema-{$EOSAGO-schema-version}">

        <InsurerID>
            <xsl:value-of select="$RSA-InsurerID"/>
        </InsurerID>

        <xsl:element name="IDCheckDriver">
            <xsl:copy-of select="namespace::*[not(name()='ns2')]"/>
            <xsl:copy-of select="$NS"/>
            <xsl:value-of select="ns2:DriverResponse/IDCheckDriver"/>
        </xsl:element>

    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Camel settings:
<setHeader headerName="RSA-InsurerID">
    <constant>18800000</constant>
</setHeader>

<setHeader headerName="EOSAGO-schema-version">
    <constant>1.2</constant>
</setHeader>

<to uri="xslt:com/rsa/eosago/xsl/DriverResponse2DriverStatusRequest.xsl"/>

The problem is that i get this error stacktrace

Failed to resolve endpoint: xslt://com/rsa/eosago/xsl/DriverResponse2DriverStatusRequest.xsl due to: Namespace prefix 'ns2' is undeclared.
Failed to resolve endpoint: xslt://com/rsa/eosago/xsl/DriverResponse2DriverStatusRequest.xsl due to: Namespace prefix 'ns2' is undeclared.
javax.xml.transform.TransformerConfigurationException: Namespace prefix 'ns2' is undeclared.

Why compiler throws exception on namespace that was created dinamically?

A: This is very confusing. Why can't you do simply:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="RSA-InsurerID"/>
<xsl:param name="EOSAGO-schema-version"/>

<xsl:template match="/*">
    <xsl:element name="rsa:DriverStatusRequest" namespace="com/rsa/eosago/schema-{$EOSAGO-schema-version}">
        <InsurerID>
            <xsl:value-of select="$RSA-InsurerID"/>
        </InsurerID>
        <IDCheckDriver>
            <xsl:value-of select="IDCheckDriver"/>
        </IDCheckDriver>
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Working demo: http://xsltransform.net/pPzifqv


text:
Q: How to read row one at a time in Datagrid Wpf c# How can i read each row in Datagrid one at a time.
For example my datagrid has 5 data on it. And each data corresponds to a method /  function in my C# solution.
I want to read it as data 1 then perform the corresponding function under that data.
then read data 2 then perform the corresponding function under that data 2. and so on..
Can anyone give me some idea how?

A: I assume you are not following MVVM, Get the Items From Your DataGrid like this,
    var tmplist = (ObservableCollection<YourDataGridObject>)DataGrid.ItemsSource;
    foreach (YourDataGridObjectitm in tmplist)
    {
    ///Access elements
    }


text:
Q: Visual Studio Code debugger reports "npm ERR! code ELIFECYCLE node.js" after script is completed This is my very simple Node.js program configuration for VSCode:
main.js
const msg = "Hello World!";
console.log(msg);

package.json
{
  ...
  "scripts": {
    "start": "node --inspect-brk=9229 main.js"
  },
  ...
}

launch.json
{
    "type": "node",
    "request": "launch",
    "name": "Debug",
    "runtimeExecutable": "npm",
    "runtimeArgs": [
        "run-script",
        "start"
    ],
    "console": "integratedTerminal",
    "port": 9229
}

Every time I run the 'main.js' script via 'Debug' launcher configuration at the very end when the script is already completed I'm getting this particular error in the TERMINAL window:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! debug1@1.0.0 start: `node --inspect-brk=9229 main.js`
npm ERR! Exit status 1

Except for these messages, everything works fine: the script runs, breakpoints are triggered.
When I run it without VSCode debugger or with Chrome debugger these error messages don't appear.
What could be wrong with VSCode debugger or with my simple JS-script, configuration or what else it could be?


text:
Q: Permission denied on Chromebook even with sudo When I compile my C++ code on my Chromebook's shell, I get the error bash: ./a.out: Permission denied. This happens even when I run with sudo: sudo: unable to execute ./a.out: Permission denied. Why does this happen?

A: The problem ended up being that the filesystem was mounted with the noexec flag, probably for security reasons. To get around this,

*

*Run sudo mount -o remount,rw -o exec PATH/TO/YOUR/FILE, where PATH/TO/YOUR/FILE is the directory where you're trying to execute the file.

*If you get an error like mount: /home/chronos/user/Downloads not mounted or bad option, remove the last directory from the command (in this case /Downloads) and try again. Keep removing until it works.

*If you get an error like When remounting eCryptfs, you need to pass the mount utility the -i parameter to avoid calling the mount helper, run sudo mount -o remount,rw -io exec PATH/TO/YOUR/.

You should now be able to run the file.


text:
Q: Comparing Saved TXT and EditText text I Want to Make A System that compares password (4 letter numeric).
Input Code (I Already Have fis)
fis = openFileInput(FILE_NAME);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String text;

        while((text = br.readLine()) != null)
        {
            sb.append(text).append("\n");
        }

        String finalinput = sb.toString();

        String finalpassinput = password.getText().toString();

        Toast.makeText(this, "finalinput:"+finalinput+"finalpassinput:"+finalpassinput,Toast.LENGTH_LONG).show();

        if(finalinput.equals(finalpassinput))
        {
            Toast.makeText(this,"Login!", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(MainActivity.this, HomeActivity.class));
        }
        else
        {
            Toast.makeText(this,"Incorrect Password",Toast.LENGTH_SHORT).show();
        }

And This Source Code will keep say that the two passwords are different.
How I Wrote My File :
fos = openFileOutput(FILE_NAME_PW, MODE_PRIVATE);
        fos.write(encodedpw.getBytes());
        Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILE_NAME_PW, Toast.LENGTH_LONG).show();

I am curious if encodepw.getBytes() will change anything to the string (Including null characters, etc.) and if Java won't think them the same.
Thank you.

A: I found myself the answer to it. The finalinput variable had some null charachter before it, so you can get pure string using this function.
public static String FileStringParse(String FileString)
{
    FileString = FileString.replaceAll("\\D+","");
    return FileString;
}


text:
Q: How can i upload files (text) in gmail for iphone Hi everyone i have been working on iPhone 4s
I have downloaded file (.doc) using ifileexplorer and i can see that file on my iPhone .I need to send that document to my friend ,so that i compose gmail tap on attach a file i can see only photos  ,i'm not getting document file .
How can i upload  document to gmail ,do i need to install anything more .i have been searching this for a long time but i didn't found best way to upload file .i have tried installing various apps like files, ifileexplorer to save but cannot upload from this
please help me out from this

A: I think this code help's you...
NSData *attachment = [NSData dataWithContentsOfURL:fileURL options:(NSDataReadingMapped|NSDataReadingUncached) error:nil];

        if (attachment != nil) // Ensure that we have valid document file attachment data
        {
            MFMailComposeViewController *mailComposer = [MFMailComposeViewController new];

            [mailComposer addAttachmentData:attachment mimeType:@"application/pdf" fileName:fileName];
        }


text:
Q: about "didReceiveRemoteNotification" delegate function For system upper than iOS 10 version, within UNUserNotificationCenterDelegate, there are two methods to clarify whether the APNS message method was called from user clicked or system received the message:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
While for system under iOS 10 version, there was an issue for the application delegate method - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo,  there are 3 ways to call this method:
1:Click a notification message when App was running in background, will call this method.
2:Click App icon wether App was running in background or was killed, before App really launched(about 1~3 seconds), during these seconds if received an APNS message, this method will be called too.
3: App was running, pull down the notification bar to make application become inactive, at this state if received an APNS message, this method will be called too.
Now here is the question, how to judge these 3 kind of clicks? Generally if user did't click message to enter app(2 and 3's click), app shouldn't execute this message(like open a new page base on the message info). But how to know it is from 2 and 3?
From below answers, found that kind-2 has been resolved with the applicationState, while kind-3 still has left no answer, anyone knows how to fix it?

A: You can check that using UIApplication state as the following:

///- if app is running in foreground
     if (application.applicationState == UIApplicationStateActive) {

         [self pushNotificationReceivedWhileActiveWithInfo:userInfo];

///- if app was running in background
     } else if (application.applicationState == UIApplicationStateBackground) {
        if (self.pushReceivedWhileClosed != YES) {
         [self pushNotificationReceivedWhileInBackgroundWithInfo:userInfo];
       }
     }

Also you'll need to handle the notification when the app was fully closed by getting it from didFinishLaunchingWithOptions when opened from a notification by saving the notification data and execute it when the user reaches the home screen let's say:
     ///- when receiving push notification while [app closed]
     if (launchOptions != nil) {
         NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
         if (dictionary != nil) {
             NSLog(@"[AppDelegate]##########################AppDelegate######################### Received notification while app CLOSED");

             ///- save the dictionary data and execute it when the app loads for example.
             self.pushReceivedWhileClosed = YES;
         }
     }

A: Check the app state in the application didReceiveRemoteNotification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateInactive || application.applicationState == UIApplicationStateBackground  )
    {
         //app was on background
    }
}

A:     - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

         NSMutableDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

               if (userInfo != nil)
                {
                    comingFromNotification = YES;
                }else{
                    comingFromNotification = NO;
                }

}


text:
Q: mov instruction fetches data from memory to memory in x86 assembly I've disassembled a x86 elf binary that was making use of the C scanf function.
Here is the disassembled chunk of code related to scanf :
0x0804857a      89442404       mov dword [esp + 0x4], eax
0x0804857e      c70424b28604.  mov dword [esp], 0x80486b2
0x08048585      e8eafdffff     call sym.imp.scanf

Checking with gdb, the memory at the address 0x80486b2 contains the data 0x7325 ("%s" string in ASCII code).
So what this code apparently does is pushing scanf parameters in reverse order on the stack so as to call scanf with these two arguments.
This would have been typically coded in C as scanf ("%s", &somevar);
What I would have expected here given the assembly code is that the 32-bit representation of the constant 0x80486b2 gets loaded into the address pointed to by the stack pointer ...
But rather, the mov instruction has loaded the 32-bit representation of whatever was at the address 0x80486b2 into the address pointed to by the stack pointer ... Is that right ?
So what we basically get is that mov has just moved around data from a memory location to another memory location, which according to this x86 assembly introduction (among a plethora of others sources) is illicit (emphasis is mine):

In cases where memory transfers are desired, the source memory
  contents must first be loaded into a register, then can be stored to
  the destination memory address.

No register has been made use of here as intermediary.
How is that possible ?

A:
If I understand well, the mov instruction here loaded the 32-bit representation of whatever was at the address 0x80486b2 into the address pointed to by the stack pointer ... Is that right ?

No. The instruction
mov dword [esp], 0x80486b2

copies the immediate value 0x80486B2 to the address pointed to by the register ESP. This place is the first parameter passed to the scanf function.

So what we basically get is that mov has just moved around data from a memory location to another memory location, [...]

No. The instruction moves an immediate 32-bit value to a memory location. The instruction's signature of the MOV in this case is:
MOV r/m32, imm32        Move imm32 to r/m32.

The value 0x80486b2 is written to the DWORD memory address pointed to by the register ESP.
The instruction mov dword [esp + 0x4], eax does pass the second parameter from EAX to scanf.

A: The instruction mov dword [esp], 0x80486b2 moves the 32-bit immediate value 0x80486b2 into the 32-bit memory location pointed to by ESP.  If it moved the 32-bit value at stored the address 0x80486b2 into the destination, then it would be written as mov dword [esp], dword [0x80486b2]. However, this is not an allowed combination of operands for the MOV instruction.
Note that your disassembly is using NASM syntax.


text:
Q: installing libva and intel-vaapi-driver I downloaded libva 2.1 and intel-vaapi-driver 2.1
I compiled and "make install" and the libs were installed in /usr/local/lib and /usr/local/lib/dri.
But when I run "vainfo", it shows the old version and not the new 2.1 version. What did I do wrong?

A: I had to use ./configure --prefix=/usr --libdir=/usr/lib/x86_64-linux-gnu

A: While user372194 answer fixed their problem, for others Intel have a detailed installation instructions for both the libva and the libva-utils for Ubuntu 16.4, https://software.intel.com/content/www/us/en/develop/articles/build-and-debug-open-source-media-stack.html.
Step 7 from the link for simplicity.
cd $WORKING_DIR
git clone https://github.com/intel/libva.git
git clone https://github.com/intel/libva-utils.git
cd $WORKING_DIR/libva
git checkout <libva commit id>
./autogen.sh --prefix=/usr --libdir=/usr/lib/x86_64-linux-gnu
make -j4
sudo make install
cd $WORKING_DIR/libva-utils
git checkout <libva-utils commit id>
./autogen.sh --prefix=/usr --libdir=/usr/lib/x86_64-linux-gnu
make -j4
sudo make install


text:
Q: Htaccess redirection duplication and HTML linking problem I'm digging all resources but cannot find the solution.
My website has multiple languages. It is basically adding ?lang=cn etc. and I'm turning it to a fake folder via htaccess with following code.
RewriteRule ^cn/(.*) $1\?lang=cn [L,N]
So,
example.com/index?lang=cn
goes to
example.com/cn/index
and everything is okay.
BUT, my footer links are;
/foo/bar
/foo/bar2
It works on English perfectly, because my English folder is the main folder, there is no /en.
When I go to Chinese and it turns to /cn, link is duplicating.
Here is what happens, when I triple click on /foo/bar
cn/foo/foo/foo/bar
I've tried to get rid of it by making the links like
../foo/bar
but this time, language folders not working.
How can I get rid of this duplication?
Thanks

EDIT:
Main Link
example.com

Language folder
cn

Inner Link 1
/foo/bar

When you click cn and change your language it becomes,
example.com/cn

After that, click inner link 1
example.com/cn/foo/bar

Then, click inner link 1 again and it duplicates and become,
example.com/cn/foo/foo/bar


text:
Q: replace php mysql to mysqli in a large codebase? We know that the other drivers are depreciated and from php7 its recommended to use mysqli methods. The problem is i came across codebase from a long time ago from one of my employer and he wants that updated.
Now there are around 3K files and the previous developer did a great job at putting in 3-5 mysql_query calls in almost every file. How would you recommend updating all of them at once, maybe some kind of method overide trick if someone has had the same issue in future.
Currently i am working with 2 vim macros that find mysql_ keyword and replace with mysqli_ and the other one which adds $con as first parameter to the method mysqli_connect.
Even with this automation, i still need to open all files individually. Any better hack is appreciated that would prevent me from opening all the files manually and making changes.

A: Here is a short way to update all the functions in codebase.
Replacing mysql_ with mysqli_
So the macro vim macro i used for this is
:%s/mysql_/mysqli_/g

This seems to be working fine with almost all functions
Changing methods that need additional params
mysqli_query needed another parameter $con so i created a macro like
:%s/mysqli_query(/mysqli_query(\$con/g

This adds the $con variable.
Save macros to file
Now the above macros can be stored in a file using
"ap

where a is the macro name, similary repeat for b and save them as a.vim and b.vim
Run on all files
Now the simple trick is running macro on all files using bash script. I simply created a loop for that
for i in *.php;
  do
    vim -s ./macro/a.vim $i;
    echo $i;
  done

This would run a.vim macro on all files. Similarly repeat the step for b.vim.
Store and close the files
By default the vim will open the file after running macro, we need to save that file by default. Add the following at the end of macro script
:wq!

This will save and exit the php file after making changes making the entire process faster and autonomous

Note the above method works but you might need some changes depending on your codebase and how to methods are called.

A: As a workaround, I created a small PHP include file, that recreates the old mysql_* functions with mysqli_*()-functions: fix_mysql.inc.php


text:
Q: Execute operation from fragment after onRestoreInstanceState I have a custom view that performs some network operations. From that operation result the view builds UI.
The view contains a list of cards that are fetched via internet. This view is used in multiple places. Lets say one of them is my fragment.
Here's what I do inside of fragment:
class MyFragment extends Fragment  {
    // same as findViewById
    @BindView(R.id.card_list) CardHelper cardHelper;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // init my element with some data before it initializes
        cardHelper.init(data);
    }
}

Here's how my custom view looks like:
public class CardHelper extends ListView {

   // some info that is built from internet data
   private List<HashMap<String, String>> cardElements = new ArrayList<>();

    public void init(Data data) {
        // does async network and then build a view based on results
        // Network operations could depend on data param
    }
}

OK, now when user switches from my app to another one, my Fragment could be destroyed. And I wanna saved the state of my custom view. Thus my view doesn't need to get information from internet again. So I append my CardHelper with the following data (based on this answer):
public class CardHelper extends ListView {
   // some info that is built from internet data
   private List<HashMap<String, String>> cardElements = new ArrayList<>();

    public void init(Data data) {
        // does async network and then build a view based on results
    }

    @Override
    public Parcelable onSaveInstanceState() {
        Parcelable superState = super.onSaveInstanceState();
        SavedState ss = new SavedState(superState);
        ss.cardElements = this.cardElements;
        return ss;
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        if(state instanceof SavedState) {
            SavedState ss = (SavedState)state;
            super.onRestoreInstanceState(ss.getSuperState());
            this.cardElements = ss.cardElements;
        } else {
            super.onRestoreInstanceState(state);
        }
    }

    private static class SavedState extends BaseSavedState {
        private List<HashMap<String, String>> cardElements = new ArrayList<>();

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.cardElements = new ArrayList<>();
            in.readList(this.cardElements, null);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeList(this.cardElements);
        }

        public static final Parcelable.Creator<SavedState> CREATOR =
                new Parcelable.Creator<SavedState>() {
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }
}

For the sake of argument, I wanna save the view's data from this view itself. So fragments/activities or w/e use it wouldn't need to know anything how it works inside. And if I use it from multiple places I wouldn't need to duplicate code that stores\restores this view.
Ok, to the problem now:
When CardHelper is created the very first time I perform init to initialize the view manually with some data. When my fragment gets destroyed and app goes to background and then gets restored, methods are executed in the following priority:

*

*SavedState: private SavedState(Parcel in) {

*SavedState: public void writeToParcel(Parcel out, int flags) {

*CardHelper: public void init(Data data) {

*CardHelper: public void onRestoreInstanceState(Parcelable state) {

As you see onRestoreInstanceState executed only after onActivityCreated. But I need to know if I should perform network operation in init method before that. So I want to onRestoreInstanceState be executed first and only then init. But there're no method in fragments LifeCycle that could be done after this.
How to I reformat my code that I can call some operation within my fragment after onRestoreInstanceState on CardHelper gets called? One more thing that onRestoreInstanceState wouldn't be called for the first time when CardHelper is created. But I need to initialize my CardHelper in this case as well.

A: The easy fix should be posting the init() step after cardHelper has been laid out, therefore onRestoreInstanceState has already been called. To do that you just have to perform init() in post(...):
cardHelper.post(new Runnable() {
                   public void run() {
                       cardHelper.init();
                   }
               });

Haven't tested it, I assume it will work.


text:
Q: Deeper sleep when closing lid of MacBook Pro? I have a mid-2015 MacBook Pro (Monterey 12.5.1), and the battery is quite badly degraded, despite being replaced once. I can only just get 30-40 minutes of use from a fully charged battery. This isn't so much a problem, as I rarely use the device without a power source, however I'm finding when I shut the lid of the device at night with a 100% charge, by the following day when I return to the device, the battery will have drained to < 10% and the device powers off, as can be seen in the image below.

My battery settings are shown below.

If I shut the device down at night, when I power it back up the following day, the battery has lost no more than a couple of percentage points of charge, so my question is, is it possible to have the Mac go in to a deeper sleep when the lid is shut?

A: I've never been able to get hibernate to work in a way that was helpful, so if you can't keep it alive by turning off Power Nap (which your screen shot shows is already off), you'll have to shut it down, plug it in or replace the battery.

*

*https://support.apple.com/lv-lv/guide/mac-help/mh40773/mac


text:
Q: Comparing Dynamic dates How to compare the two dates from div element using jQuery?
If the div is like:

The from and to dates are dynamic. After comparing it should display greater date based on time.
Please help - I searched but every where dates were first initialized and then compared.

A: Why don't you just use new Date(attributeValue) and compare like integers. Check this link http://jsfiddle.net/b0ye90ps/
var elements = document.querySelectorAll('.date-time');

for(var i = 0; i < elements.length; i++) {
    var from = elements[i].getAttribute('data-from');
    var to = elements[i].getAttribute('data-to');
    var bigger = to;
    if(new Date(from) > new Date(to)) {
       bigger = from;
    }
    elements[i].innerHTML = bigger + ' --> Compared ' + from + ' vs ' + to + ';
';
}

Hope this is what you are looking for.


text:
Q: Google spreadsheet: How to add notification rule (in script) Is it possible to create script for the next task:

*

*select range in spreadsheet

*click special item in menu (no prob with that part)

*as a result: this range automatically added as new notification rule (see in menu Tools)

I've checked spreadsheet classes (Range, Sheet, Spreadsheet, SpreadsheetApp), and search it in inet - no results so far.
Thanks!

A: I don't think it is possible now, because, as you wrote, there is no GAS functionality to manage the notification rules. Also I have not found any feature request on the issue tracker asking this functionality. Please submit a new feature request to the issue tracker to help Google to understand which features are required for the users.


text:
Q: Fopen didnt see /dev/usb/lp0 I've got a problem with open /dev/usb/lp0 . In terminal I see that file, but in PHP I dont. If i try open that file in PHP, I got error : open(/dev/usb/lp0): failed to open stream: No such file or directory so I try sudo chmod 777 /dev/usb but nothing change. I try to scan /dev/ folder in PHP Picture of all folder, what i see in PHP. And nothing change, again.. Do you have any ideas?
Thanks, for help.


text: Q: How to change border thickness in Qtablewidget via Pyqt I want to change specifically second and third column line's thickness in my Qtablewidget. I searched all the Internet but couldn't find a way to do it via Pyqt5. It is possible to do it with C++. If you know, I would be appreciated