text:
Q: Try/Catch not working in PowerShell I have the function get_user that searches for the username typed:
function get_user
{
    $url2 = "myurl/userName:" + $userName

    $contentType2 = "application/json"
    $basicAuth2 = post_token
    $headers2 = @{
              Authorization = $basicAuth2
             }
    $body2 = @{
              grant_type = 'client_credentials'
             }
    $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2 -Headers $headers2 -Body $body2

    return $getUser.userName
}

And then I have my try/catch statement in the main method which is not working:
#MAIN

try {

$userName = Read-Host -Prompt "Input the user's username"
$getUser = get_user

    if ($userName -eq $getUser)
        {
            $courseId = Read-Host -Prompt "Input the course's ID"
            $availability = Read-Host -Prompt "Available? (Yes/No)"
            $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"

            $confirmationEnrollment = putStudentCourse
            " "
            "####################################################"
            "Success!"
            "####################################################"
        }
    else
        {
            $firstName = Read-Host -Prompt "First Name"
            $lastName = Read-Host -Prompt "Last Name"
            $netId = $userName
            $email = $userName + "@school.edu"
            $password = Read-Host -Prompt "Password"
            $uin = Read-Host -Prompt "ID Number"
            $isAvailable = Read-Host -Prompt "Available? (Yes/No)"

            $confirmationUserCreate = user_create
            " "
            "####################################################"
            "User created!"
            "####################################################"
            " "
            $courseId = Read-Host -Prompt "Input the course's ID"

            $confirmEnroll = putStudentCourse
            " "
            "####################################################"
            "User enrolled!"
            "####################################################"
        }
    }
catch [System.Net.HttpWebRequest]
    {
        "####################################################"
        "User not found. We'll create it now!"
        "####################################################"
        " "
    }

Right now it is throwing error after you type a username that doesn't exist:
Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At E:\Blackboard_REST_API_Project\PowerShell\Post_Student_Course.ps1:42 char:13
+     $getUser = Invoke-RestMethod -Method Get -Uri $url2 -ContentType $contentType2  ...
+    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

I am trying to hide the red error and output what I have in the catch statement but it is skipping the catch and jumping straight to the else when it can't find a username. Any ideas?

A: You're checking for the wrong exception-type in your catch-statement. A 404 error is thrown as a WebException:
$Error[0]
Invoke-RestMethod : The remote server returned an error: (404) Not Found.
At line:2 char:5
+     Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage"
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

$Error[0].Exception

The remote server returned an error: (404) Not Found.

$Error[0].Exception.GetType().FullName

System.Net.WebException

Try:
try {
    Invoke-RestMethod -Uri "http://www.vg.no/nonexistingpage"
}
catch [System.Net.WebException]
{
    "Exception caught!"
}

As for the script, I would probably do something like this to make create the user if it doesn't (404-error):
#MAIN

$userName = Read-Host -Prompt "Input the user's username"

try {
    $getUser = get_user
} catch [System.Net.WebException] {
    #User doesn't exist, create new
    $firstName = Read-Host -Prompt "First Name"
    $lastName = Read-Host -Prompt "Last Name"
    $netId = $userName
    $email = $userName + "@school.edu"
    $password = Read-Host -Prompt "Password"
    $uin = Read-Host -Prompt "ID Number"
    #Is it required to create user? If not, remove as it's specified later
    $isAvailable = Read-Host -Prompt "Available? (Yes/No)"

    $confirmationUserCreate = user_create
    " "
    "####################################################"
    "User created!"
    "####################################################"

    #Verify user was created
    $getUser = get_user
}

#Not sure if test is still needed..
if($userName -eq $getUser) {
    $courseId = Read-Host -Prompt "Input the course's ID"
    $availability = Read-Host -Prompt "Available? (Yes/No)"
    $courseRoleId = Read-Host -Prompt "Course Role? (Student/Instructor)"

    $confirmationEnrollment = putStudentCourse
    " "
    "####################################################"
    "Success!"
    "####################################################"
}

Tip: You should use parameters in your functions and not rely on variables that might exist.

A: Regarding the Try Catch the most likely cause is that an error other than the one listed explicitly after the Catch is occurring. The way to test this is to remove the named exception type and just catch all errors. I am not recommending doing this in production code, but for testing it will at least reveal if your general idea is correct. Then you can clarify what specific errors to catch.
There seems to be some confusion about the desired actions. Based on comments below the question and based on your code comments you seem to be saying that if the request throws an error then the user must not exist and should be created. If this is correct be careful as that assumption won't always be true.
Once the error is thrown you will in fact skip all of the code in your If Else structure. Essentially I think you want to take the logic in your ELSE statement and move this into the Catch block. If it is the case that you want to try to create the user either if get_user throws an error or if it doesn't throw an error but the If condition fails then you will want the same logic in the else AND in the catch. Of course it would be better to create a function to call from either rather than duplicating code.
Essentially:
Try{
    #try to invoke the request

    #if the request did not fail then compare the user entered text to the text returned from the request
    #if these match then user already exists
    #else the user does not exist so create it here
}
catch{
  #if the request failed assume that the user does not exist and create it here

}


text:
Q: Is "class" is predefined class in Java? Can we say that java.lang.Class is predefined class in Java?
I am really confused on this.. I am new to Java so I am not sure. So please let me know the correct answer.

A: Class is a class where as class is a keyword.

*

*Type java.lang.Class

Instances of the class Class represent classes and interfaces in a
  running Java application.

*Keywordclass (JLS Chapter 8 ff.)

Class declarations define new reference types and describe how they are implemented
  [...]
  A class declaration specifies a new named reference type.

A: Class java.lang.Class. Class objects contain runtime representations of classes. Every object in the system is an instance of some Class, and for each Class there is one of these descriptor objects.
A Class descriptor is not modifiable at runtime
Declaration
public final class Class<T> extends Object
implements Serializable, GenericDeclaration, Type, AnnotatedElement

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS App Won't start on Testflight Ad Hoc Distribution I'm developing an application that works perfectly well on my phone when I run it through Xcode. But when I distribute a beta through TestFlight, none of the users can run it - NOTE: They can install the app on their phones without any problem. The application just closes before it launches and there are no crash logs on TestFlight.
I can connect any of my testers' phones to my computer and run the app on them (using Xcode) just fine. I thought maybe this is a problem with provisioning profiles, but on my phone, I can delete the relevant profile from Settings app then install the app from the TestFlight link, and it still runs fine.
From things I've read on Stack Overflow, this must be because of some difference in "Release" and "debug" settings of the app, but I'm totally lost as to how to debug it. I can't run the app in release mode while it's connected to Xcode, and I can't debug when it's not connected to Xcode.
Any suggestions?
Update - Resolved
I did end up "solving" this problem. SO user Cliff Ribaudo had the same problem (apparently he was the only other person) and he posted about it here and finally found the solution here. The solution turned out to be setting two linker flags: STRIP LINKED PRODUCT = NO & STRIP STYLE = DEBUGGING SYMBOLS. I have no idea why this fixed it, and I don't know why it was broken in the first place. But we haven't had this crash since I made these changes.

A: Thanks, Kerni I was able to debug the issue by tracking down the crash report via
iPhone Configuration Utility
. I Selected the Devices I was debugging and opened the Console Tab on the iPhone Configuration Utility hitting clear and check it out. I Saved the log after getting the app to crash again and found that I had been using In-App Audio when I didn't add it to the App ID when I was creating my provisioning profile. This was the only issue. After I went threw all of the steps again the IPA Uploaded just fine. The app installed like one would imagine!
To Put it short :

*

*Debugged with iPhone Configuration Utility (issue was In-App Audio wasn't selected on the App ID Generation)

*Generated a New App ID and Provisioning Profile

*Created and uploaded a new IPA.

<<<< Console Debugging here >>>>:
http://help.testflightapp.com/customer/portal/articles/1305502-my-apps-are-failing-to-install-what-do-i-do-

A: I had exactly same problem and I figured it out. Please see my answer here.
testflight application closes on start


text:
Q: Changing class combinations based on multiple conditions I have few style classes defined in my style sheet as like the following:
.left-align{
  /* some styles here */
}
.right-align{
  /* some styles here */
}
.validate-error{
  /* some styles here */
}

Based on the type of data in the class I need to align the content left or right, and also I wanted to call a method which will validate my data in the control, if validation fails need to append the validate-error class as well to the ng-class. I gone through different SO threads and other articles and QA sites that titled as multiple conditions in ng-class but nothing found working in my scenario, I have tried the following based on the references:
ng-class="{!vm.validate()?'validate-error': vm.isNumericField?'right-align':'left-align'}"

But this will not align the content to the right even isNumericField is true when validate() returns false.
In short, I need to add left-align or right-align depends on the isNumericField property and also validate-error if validate() returns false.
 "isNumericField?{'left-align':'right-align'} + 'validate-error':validate()"

Please anyone let me know if there any way to achieve this:

A: You can specify "map" of class names to boolean values:
ng-class="{'validate-error': !vm.validate(), 'right-align': vm.isNumericField, 'left-align': !vm.isNumericField}"


text:
Q: Data attached to POST request is gone during redirection to GET with CURL I wrote followed command to send POST with JSON data to server. The server must redirect my request and send GET with the same data:
curl  -L -i -XPOST \
     -d 'id=105' \
     -d 'json={"orderBy":0,"maxResults":50}'  http://mysite.com/ctlClient/

I get response:
HTTP/1.1 302 Found
Date: Thu, 04 Jul 2013 13:12:08 GMT
Server: Apache
X-Powered-By: PHP/5.3.19
Set-Cookie: PHPSESSID=1hn0g8d7gtfl4nghjvab63btmk2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
location: http://mysite.com/fwf/online/
Content-Length: 0
Connection: close
Content-Type: text/html

HTTP/1.1 200 OK
Date: Thu, 04 Jul 2013 13:12:08 GMT
Server: Apache
X-Powered-By: PHP/5.3.19
Set-Cookie: PHPSESSID=16akc7kdcoet71ipjflk9o9cnm5; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 1
Connection: close
Content-Type: text/html

From access-log I see:
 "POST /ctlClient/ HTTP/1.1" 302 - "-" "Apache-HttpClient/4.1 (java 1.5)"
 "GET /fwf/online/ HTTP/1.1" 200 1 "-" "Apache-HttpClient/4.1 (java 1.5)"

So far so good,
The problem is that GET doesn't  receives my data added to post. Sounds like during redirect my data dismissed somehow. From Android client it works, therefore its not Server side problem.
What I need to do to pass POST data to GET request?
Thank you very much,
[EDIT]
@nif offerd to upgrade CURL, i did ,  to 7.28.0.
Still get the same problem
[INFO]
1st time i go to http://mysite.com/ctlClient/index.php where:
 case 105: // id=105
        session_unset();
        session_start();
        foreach($_POST as $key => $value){$_SESSION[$key] = $value;}
        ctlGotoSameDomain("/fwf/online/"); // <- aka redirect
        return true;

after redirect i go to /fwf/online/index.php and there my request is empty:
public function __construct() {
        $this->json = isset($_SESSION['json']) ? $_SESSION['json'] : null;
        msqLogFile("fwf/post", Array('post' => 'Request: '.$this->json));

    }

http://mysite.com/ctlClient/index.php get 2 parameters properly: id and json

A: From curl's manpage:

When  curl  follows a redirect and the request is not a plain GET (for example POST or PUT), it will do the following request with a GET if the HTTP response was 301, 302, or 303. If the response code was any other 3xx code, curl will re-send the following request using the same unmodified method.

Edit
I did some research and found out, that it might be a problem with your curl version. Newer version will honour the -XPOST option and will POST to the redirected location as well. But older versions had an own option for this, i.e. --post301 and --post302. According to their manpage:

--post301
Tells curl to respect RFC 2616/10.3.2 and not convert POST requests into GET
requests when following a 301 redirection. The non-RFC behaviour is ubiquitous
in web browsers, so curl does the conversion by default to maintain
consistency. However, a server may require a POST to remain a POST after such
a redirection. This option is meaningful only when using -L, --location
(Added in 7.17.1)
--post302
Tells curl to respect RFC 2616/10.3.2 and not convert POST requests into GET
requests when following a 302 redirection. The non-RFC behaviour is ubiquitous
in web browsers, so curl does the conversion by default to maintain
consistency. However, a server may require a POST to remain a POST after such
a redirection. This option is meaningful only when using -L, --location
(Added in 7.19.1)

References:

*

*Following redirects with curl

*HTTP RFC

A: I need to add -b to my script to enable the cookies. CURL by default doesn't use them and this issue caused to session ID change. Therefore no data transferred.
curl -b -L -i -X POST \
 -d 'id=105' \
 -d 'json={"orderBy":0,"maxResults":50}'  http://mysite.com/ctlClient/

Now its working


text:
Q: Linking of Lists columns in SharePoint 2013 I am using SharePoint 2013.
Scenario:
There is a List named TestList. This list contains 4 columns AppName, AppID, Domain and Owner.
Here Owner is Person field type and rest are single line of text.
Now, there are 4 different Lists. TestList1,TestList2,TestList3 and TestList4.
These lists are provided with List Level Permissions with usergroup1, usergroup2, usergroup3 and usergroup4 respectively.
In each of the above lists there are 8 columns. And the first columns in each lists are looked up from TestList and the next four are entered manually.
Now, depending on the Owner column in TestList the AppName in all these different lists should only auto populate their AppNames.

A: Select AppName as a dependent column when creating a lookup column.


text:
Q: Не могу установить discord-components ERROR: Could not find a version that satisfies the requirement discord-components (from versions: none)
ERROR: No matching distribution found for discord-components
from discord_components import DiscordComponents, Button, ButtonStyle

A: тоже столкнулся с такой проблемой при развёртывании своего бота, который раньше работал стабильно. Единственное решение, которое я нашел, — это вручную установить сам код библиотеки. Установите библиотеку с github https://github.com/kiki7000/discord.py-components/tree/master/discord_components в папку ваших библиотек, пример Ubuntu /usr/lib/python3.10/, на Windows же эта папка скорее всего находится здесь C:\Users\ИМЯ ПОЛЬЗОВАТЕЛЯ\AppData\Local\Programs\Python\Python310\Lib


text:
Q: Simple way to prevent data.table auto-index from being created without using options(datatable.auto.index = FALSE) I have some code like
library(data.table)  # v 1.12.3

foo <- data.table(x = sample(letters, 10^6, replace = T), y = 1)
foo[x == "a", y := 0]
indices(foo)  # x

As you can see, an index is being created automatically on the column x. In this case, I don't want the index to be created. I know I can prevent it with something like
options(datatable.auto.index = FALSE)
foo[x == "a", y := 0]
options(datatable.auto.index = TRUE)

but this seems like poor design because

*

*It's messy code

*If foo[x == "a", y := 0] has an error, auto-indexes will not get turned back on

Is there a better option here, perhaps something like foo[x == "a", y := 0, autoindex = FALSE]?
Also, I guess I could allow the index to be created and then just delete it with setindex(foo, NULL) but I'm concerned this has an added performance cost. Plus it seems messier than it should be.

A: For cases like your example, I think it's better to let data.table do its thing:
library(data.table)  # v 1.12.3 IN DEVELOPMENT built 2019-07-29 22:08:45 UTC
foo <- data.table(x = sample(letters, 10^8, replace = T), y = 1)

# allow optimization (forder, store order as index, bmerge value)
foo1 = copy(foo)
system.time({
  foo1[x == "a", y := 0]
})
stopifnot(length(indices(foo1)) > 0)
#    user  system elapsed
#    1.43    0.39    0.56

# disable optimization, hacky
foo2 = copy(foo)
system.time({
  foo2[(x == "a"), y := 0]
})
stopifnot(length(indices(foo2)) == 0)
#    user  system elapsed
#    0.47    0.01    0.49

# disable optimization, properly
foo2 = copy(foo)
system.time({
  options(datatable.auto.index = FALSE)
  foo[x == "a", y := 0]
  options(datatable.auto.index = TRUE)
})
stopifnot(length(indices(foo2)) == 0)
#    user  system elapsed
#    0.48    0.00    0.49

# disable optimization, from @Oliver in comments
foo2 = copy(foo)
system.time({
  foo2[which(x == "a"), y := 0]
})
stopifnot(length(indices(foo2)) == 0)
#    user  system elapsed
#    0.54    0.03    0.50

Misc comments:

*

*The parentheses (x == "a") prevent the data.table parser from recognizing that optimized subsetting is appropriate. For details on the optimizations used, turn on the verbose=TRUE argument.

*I regard the additional cost above as small, and the benefits in subsequent queries as large:
system.time({
  foo1[x == "b", y := 0]
})
#    user  system elapsed
#    0.17    0.12    0.25

*Maybe for other auto-indexed queries, the time difference would be larger than in this case.

*Besides time to compute, indices presumably take up some space (storing a permutation of the table's row numbers?), but I doubt that would be worth fiddling with in most cases.

A: datatable.auto.index option was my idea just because there was no official way to disable automatic creation of index. It was useful specially when benchmarking. I still think it is better to use option than adding new argument to [.data.table.
It is not clear why exactly you don't want to use auto index. If you are worried about potential overhead then simple check could examine if it is really a problem.
My suggestion then, is to disable auto.index for good just after loading data.table. Then for each data.table you want to use any index call setindex.


text:
Q: Creating Tabs Dynamically in code - Android Studio 3.5 I am having the hardest time understanding the Studio 3.5 Tabbed Activity template. So to follow along, simply open a new project with Studio 3.5 and select Tabbed Activity as your starting template.
I need an activity, in this simple example, that adds a new TAB and passes info to the PlaceholderFragment class object, and sets the Tab title. Each tab will use the same fragment.xml layout. And will populate the contents based on data passed from the main activity. It won't start with any Tabs initially. For this example, let's assume that each time you press the Floating Button in the template that it adds a new TAB.
Can someone show me how this should be wired up? I simply can't figure it out by looking at the template which hard codes the number of Tabs and the Tab titles. I seem to have a complete mental block on this design pattern.

A: Ok - figured it out, so going to answer my specific question so others can learn.
This page helped me figure it out. It is written in Kotlin, and I am using Java; but no problem translating.
https://www.codexpedia.com/android/android-tablayout-with-many-tabs-kotlin/

*

*Do not modify either XML file that the template creates.

*No modification to PageViewModel.java (I still don't know how to use that and probably not needed in this exercise.

*Do not modify the PlaceholderFragment.java

*My modifications to MainActivity.java and SectionsPagerAdapter.java are below and self-explanatory.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final Context mContext;
ArrayList<String> tabNames = new ArrayList<>();
ArrayList<Fragment> fragments = new ArrayList<>();

public SectionsPagerAdapter(Context context, FragmentManager fm) {
    super(fm);
    mContext = context;
}

public void add(Fragment fragment, String title) {
    tabNames.add(title);
    fragments.add(fragment);
}

@Override
public Fragment getItem(int position) {
    return fragments.get(position);
}

@Nullable
@Override
public CharSequence getPageTitle(int position) {
    return tabNames.get(position);
}

@Override
public int getCount() {
    return fragments.size();
}

}
And for MainActivity.java, just use this code in the FloatingActionButton,onClickListener to add a new Tab.
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int curCount = sectionsPagerAdapter.getCount();
            sectionsPagerAdapter.add(PlaceholderFragment.newInstance(curCount),
                    "TAB " + String.valueOf(curCount));
            sectionsPagerAdapter.notifyDataSetChanged();
        }
    });

That is all it takes.


text:
Q: How to stop a long running spark streaming step in AWS EMR I use AWS EMR for our spark streaming. I add a step in EMR that reads data from Kinesis stream. What I need is an approach to stop this step and add a new one.
Right now I spawn a thread from the Spark driver and listen to an SQS queue for a message and upon receiving a message, I call sparkContext.stop(). I use Chef for our deployment automation. So when there is a new artifact, a message is put into SQS, EMR reads it and stops the step. Chef then adds a new step with EMR API.
My question is, is this the right way to stop a long running streaming job in EMR? How will this be handled had spark been deployed on a standalone cluster instead of EMR?

A: EMR STEP API at this moment, does not support STOPPING. When you submit a step , EMR usually runs a hadoop jar command with he arguments you provided. If the step type is spark, it will run spark-submit command. When this command returns 0 exit code , a STEP is marked as FINISHED and when it returns any other exit code , it will be marked as FAILED. The state can also depend on the current YARN applications running. At present, You can test and observe that EMR will not mark a STEP FINISHED if there's any ongoing YARN apps(not particularly spawned by STEP) running during that time.
So, using your main class / JAR on spark-submit, by writing a custom code,  you can reach the desired state of the STEP by pushing the desired exit code.
You can find more about the command that EMR translates your STEP to, by looking at the controller.log of the STEP.


text:
Q: how to handle months value in dateadd I know what the problem is but can anyone please suggest as how to resolve this query.
The problem is when i calculate for months in dateadd i am getting value more than 98540 :(
declare @Basepool int =10000000
declare @transactioncount bigint =1
declare @Monthnum int=1
declare @ContractId int=1

select CASE @Basepool
            WHEN 0 THEN 'N/A'
            WHEN -1 THEN 'N/A'
            ELSE CASE
                    WHEN SUM(SUM(@TransactionCount)) OVER (Partition by @ContractId) > @Basepool THEN 'IN-OVERAGE'
                    --WHEN SUM(SUM(B.TransactionCount)) OVER (Partition by @ContractId) + (SUM(SUM(B.TransactionCount))  OVER (Partition by @ContractId)/MonthNum) > U.BasePool THEN DATEADD(MM, 1, GETDATE())
                    ELSE  CONVERT(VARCHAR(20),DATEADD(MM,CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))
                                /(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT), GETDATE()),101)

                    --(basepool - sumcontract) / (sumcontract/monthNum ) is the expected months to reach overage
                END

            END AS  ExpectedDate

A: Your @Basepool variable has very long value which is overflow by INT.
Just try below corrected code.
declare @Basepool INT =10000
declare @transactioncount bigint =1
declare @Monthnum int=1
declare @ContractId int=1

select CASE @Basepool
            WHEN 0 THEN 'N/A'
            WHEN -1 THEN 'N/A'
            ELSE CASE
                    WHEN SUM(SUM(@TransactionCount)) OVER (Partition by @ContractId) > @Basepool THEN 'IN-OVERAGE'
                    ELSE  CONVERT(VARCHAR(20),DATEADD(MM,CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))
                                /(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT), GETDATE()),101)
                END

       END AS  ExpectedDate

A: First of all, the maximum months I can add to getdate() is
select dateadd(mm, 95840, getdate())

What you need is a way to handle the exception case where number of months to be added is greater than the limit.
Try this:
select DATEADD(MM
    , case when CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))/(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT)
        > datediff(mm, getdate(), '9999-12-31')
        then datediff(mm, getdate(), '9999-12-31')
        else CAST(ROUND((@Basepool - SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId))/(SUM(SUM(@TransactionCount))  OVER (Partition by @ContractId)/@Monthnum),0) as INT)
        end
    , GETDATE())

You will need to handle '9999-12-XX' after getting the value back from the query.


text:
Q: .htaccess rewriterule is redirecting me to another site - why I am trying to do some work in serve_each_drive.php under the url drive_for_london/?pid=12
this is my .htaccess:
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^drive_for_(.*)/$ http://web228.sydney.webhoster.ag/soputnik/serve_each_drive.php [L]

I want to keep the url drive_for_london/?pid=12 and do the work in background. but the rule above is redirecting me to serve_each_drive.php. the url is becoming:
http://web228.sydney.webhoster.ag/soputnik/serve_each_drive.php

why? please help

A: Yes that is correct mod_rewrite behavior that target URL will externally redirect (hence change in your browser also) if you have full URL in the target. Since your target URL starts with http:// therefore this redirection is happening.
To prevent this behavior you need to:

*

*Make sure you're using URL without domain (internal to web server)

*Make sure to not to use R flag (you are already doing it)

So change your code with this:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} ^pid=.+ [NC]
RewriteRule ^drive_for_(.*?)/$ /soputnik/serve_each_drive.php [L,NC]

Also keep in mind above code assumes the URL on your page is: http://web228.sydney.webhoster.ag/drive_for_london/?pid=12 and that will be internally forwarded to: http://web228.sydney.webhoster.ag/soputnik/serve_each_drive.php?pid=12


text:
Q: Cannot wrap video.js component in react-loadable Here is the sandbox link: https://codesandbox.io/s/playvideo-e3dbw
I'm using video.js to display video in my react project, and it's imported in my <VideoPlayer/> component.
Now I want to use react-loadable to wrap <VideoPlayer/> cause video.js is too large.
But when I'm accessing the actural video player in my running project, the project was crashed and I got some error messages in my browser's console:
react-dom.development.js:57 Uncaught Invariant Violation: Element type is
invalid: expected a string (for built-in components) or a class/function (for
composite components) but got: object.

Check the render method of `LoadableComponent`.

Warning: Can't perform a React state update on an unmounted component. This is
a no-op, but it indicates a memory leak in your application. To fix, cancel
all subscriptions and asynchronous tasks in the componentWillUnmount method.

Here are some pieces of my source codes. The problem occurs after I wrapped <VideoPlayer/> component using react-loadable like so:
const LoadableVideoPlayer = Loadable({
  loader: () => import('./VideoPlayer'),
  render(loaded, props) {
    let Component = loaded.default;
    return <Component {...props}/>;
  },
  loading:
Loading...

});

I want to render either pdf player or video player in a page according to current state. Here is the usage of <LoadableVideoPlayer/> component:
if (this.state.currentPlayer==='Video' && videoSrc) {
      return <LoadableVideoPlayer key={videoSrc} videoSrc={videoSrc}/>
    } else if (this.state.currentPlayer==='PDF' && pdfSrc) {
      return <PDFPlayer key={pdfSrc} pdfSrc={pdfSrc}/>
    }
}

This is my <VideoPlayer/> component:
import React from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

class VideoPlayer extends React.Component {
  componentDidMount() {
    const src = this.props.videoSrc;

    const videoPlayerOptions = {
      controls: true,
      sources:[
        {
          src:src,
          type:'video/mp4'
        }
      ]
    };

    this.player = videojs(this.videoNode, videoPlayerOptions, () => {
      console.log("Ready to play")
    })
  }

  componentWillUnmount() {
    // if (this.player) {
    //   this.player.dispose()
    // }
  }

  render() {
    return(

        <video ref={node => this.videoNode = node} className="video-js" />

    )
  }
}

export default VideoPlayer

Please notice that in componentWillUnmount() method I comment out those lines of code, since if not, I will get another error message even if I do not use react-loadable.
I think the problem might be here, but I searched a lot and didn't find any solutions.
For more details, here are where I import Loadable and use it.
import React from 'react';
import Loadable from 'react-loadable';
import PDFPlayer from './PDFPlayer';

const LoadableVideoPlayer = Loadable({
  loader: () => import('./VideoPlayer'),
  render(loaded, props) {
    let Component = loaded.default;
    return <Component {...props}/>;
  },
  loading:
Loading...

});

class ResourcePlayer extends React.Component {
  state = {currentPlayer:'PDF'};

  onPlayerChange = selectedPlayer => {
    this.setState({currentPlayer:selectedPlayer})
  };

  renderPlayer = () => {
    const {videoSrc, pdfSrc} = this.props;

    if (this.state.currentPlayer==='Video' && videoSrc) {
      return <LoadableVideoPlayerkey={videoSrc} videoSrc={videoSrc}/>
    } else if (this.state.currentPlayer==='PDF' && pdfSrc) {
      return <PDFPlayer key={pdfSrc} pdfSrc={pdfSrc}/>
    } else {
      return (

          {/*Some placeholder here, not important for this problem*/}

      )
    }
  };

  render () {
    // suppose here are some logic to switch the state between 'PDF' and 'Video'
    return (
      {this.renderPlayer()}
    )
  }
}

A: I think I have found the reason. Instead of using
Loading...
 in side that LoadableVideoPlayer component, I should use a react component for the loading property.
const LoadableComponent = () => {
   return
Loading...

};

const LoadableVideoPlayer = Loadable({
  loader: () => import('./VideoPlayer'),
  render(loaded, props) {
    let Component = loaded.default;
    return <Component {...props}/>;
  },
  loading: LoadableComponent
});

Also, I missed some error messages and sorry for that. Here is the error messages that indicates this problem:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got:
. Did you accidentally export a JSX literal instead of a component?
    in LoadableComponent (created by ResourcePlayer)
    in div (created by ResourcePlayer)
    in ResourcePlayer


text:
Q: Python 2.7 Qt Matplotlib : subplot ID reference from event My goal is to identify which subplot has been clicked on by the user. More precisely in the matplotlib class, I can identify the subplot using event.inaxes. Great. But I cannot get that event in the Qt widget class.
I am definitely missing something ...
Here is the code with my latest "awkward" attempt. Any suggestion on how to procceed ?
I am no Python expert. Python 2.7 has to be used (no choice)
from __future__ import print_function
from __future__ import division

import sys

from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from matplotlib.figure import Figure
from matplotlib.backend_bases import key_press_handler
from matplotlib.backend_bases import Event
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)

#Connect InventoryChartsWidget to ChartFigure: QT
class TheConnector(QtCore.QObject):

   selecteddataregion=pyqtSignal(name='selecteddataregion')

   def emitsignal(self,xmin,xmax,ymin,ymax):
       self.selecteddataregion.emit()

#Chart including events: MATPLOTLIB
class ChartFigure(Figure):

def onclick(self,event):
    #MAIN ISSUE
    #HOW TO RETURN THE subplot axes to class InventoryChartsWidget?

    if event.button==1 :
       self.ConnSbPlt.emitsignal(1.0,1.0,2.0,2.0)
       print('OK: Axes is ... ', event.inaxes)

def __init__(self,Conn):
    #Init the Matplotlib
    Figure.__init__(self) #initialize the orginal class, see also super()
    super(ChartFigure, self).__init__()
    self.canvas=FigureCanvas(self)
    self.ConnSbPlt=Conn

#Chart including events: QT
class InventoryChartsWidget(QtGui.QDialog):

def __init__(self, parent=None,xlimlow=0,xlimhigh=100,ylimlow=0,ylimhigh=100, G_array=[], N_array=[], ddom_array=[], hdom_array=[], speciesDict={}):

    QMainWindow.__init__(self, parent)

    #Fake stupid data
    self.mG_array  = [2] * 10
    self.mHdom_array = [0.5] * 10

    #jte to make sur I have it
    self.xdata_start=-1.0

    #fake plot to get a member of type subplot: UGLY!
    #Attempt to create a member object "axes"
    self.tabFake = QtGui.QWidget()
    self.tabFake = self.create_tab(self.tabFake)
    self.tabFake.plots = []
    self.subPlotFake = self.tabFake.fig.add_subplot(111)

    print("here is OK; it exists ...", self.subPlotFake)

    self.create_main_frame()

    self.setModal(False)
    self.setVisible(True)
    self.show()

def create_main_frame(self):
    #Associate a Qwidget with the InventoryChartsWidget widget

    print("OK here too; it exists ... ",self.subPlotFake)

    self.main_frame = QtGui.QWidget()
    LesTabs = QtGui.QTabWidget()
    self.tabG   = QtGui.QWidget()

    #Fill the tab with Matplotlib object and draw the charts
    self.tabG=self.create_tab(self.tabG)
    self.on_draw_G(self.tabG)
    self.tabG.fig.subplots_adjust(left=0.02,bottom=0.05,right=1,top=0.95,wspace=0.2,hspace=0.2)

    LesTabs.addTab(self.tabG,"Chart")

    grid = QGridLayout()
    grid.addWidget(LesTabs, 0, 0)
    self.main_frame.setLayout(grid)
    self.setLayout(grid)
    self.layout().addWidget(self.main_frame)

def UpdatePlot_DataSelection(self):
    #SLOT
    print("Get connected here process the data in the subplot XX...")

def on_draw_G(self,tab):
    #Juts one subplot for test purpose
    tab.fig.clear()
    tab.plots = []
    subPlot = tab.fig.add_subplot(111)
    subPlot.hold(False)
    tab.plots.append(subPlot)
    self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
    subPlot = tab.fig.add_subplot(122)
    subPlot.hold(False)
    tab.plots.append(subPlot)
    self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
    tab.canvas.draw()

def create_tab(self,tab):
    #Create the tab widget, associated with Matplotlib plot

    print("OK member exists ... ", self.xdata_start)
    print("OK member exists ",self.tabFake)

    #ISSUE HERE: don't understand
    #print("NOT OK !!! member does not exist Why ? ",self.subPlotFake)

    Conn=TheConnector()
    #MATPLOTLIB
    tab.fig = ChartFigure(Conn)
    tab.canvas = FigureCanvas(tab.fig)
    tab.canvas.setParent(tab)
    tab.canvas.setFocusPolicy(Qt.StrongFocus)
    tab.canvas.setFocus()

    #connect signal to slot
    Conn.selecteddataregion.connect(self.UpdatePlot_DataSelection)

    tab.mpl_toolbar = NavigationToolbar(tab.canvas, tab)

    vbox = QVBoxLayout()
    vbox.addWidget(tab.canvas)
    vbox.addWidget(tab.mpl_toolbar)
    tab.setLayout(vbox)

    tab.canvas.mpl_connect('button_press_event', tab.fig.onclick)

    return tab

def on_key_press(self, event):
    #Keyboard input: standard mpl key press
    key_press_handler(event, self.canvas, self.mpl_toolbar)

def PlotData_G(self, plot, G_array, hdom_array):
    # Plot G
    plot.hold(False)
    plot.scatter(x=hdom_array, y=G_array, marker='+',linewidths=1.5)
    plot.set_autoscaley_on(True)
    plot.tick_params(labelsize=8)

def main():
app = QApplication(sys.argv)
form = InventoryChartsWidget(xlimlow=0,xlimhigh=60,ylimlow=0,ylimhigh=80)
form.show()
app.exec_()

if __name__ == "__main__":
main()

There are 3 classes:
TheConnector is a Signal/Slot QT class
ChartFigure is matplotlib class (including the desired mouse Event)
InventoryChartsWidget is the main widget (Qt; here I need the ID of the subplot)
Any help would be greatly appreciated. Thank you.

A: Here is a working solution. The true limit was my thinking in python (to be more specific the lack of properly declared variables ... can't get use to it)
from __future__ import print_function
from __future__ import division

import sys

from PyQt4 import QtGui
from PyQt4 import QtCore
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from matplotlib.figure import Figure
from matplotlib.backend_bases import key_press_handler
from matplotlib.backend_bases import Event
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)

#Connect InventoryChartsWidget to ChartFigure: QT
class TheConnector(QtCore.QObject):

   selecteddataregionARG=pyqtSignal(object,name='selecteddataregionIN')

   def emitsignalEvent(self,TheEvent):
       self.selecteddataregionARG.emit(TheEvent)

#Chart including events: MATPLOTLIB
class ChartFigure(Figure):

def onclick(self,event):
    #MAIN ISSUE
    #HOW TO RETURN THE subplot axes to class InventoryChartsWidget class?

    if event.button==1 :
       print('Event: Axes is ... ', event.inaxes)
       self.ConnSbPlt.emitsignalEvent(event.inaxes)

def __init__(self,Conn):
    #Init the Matplotlib
    Figure.__init__(self) #initialize the orginal class, see also super()
    super(ChartFigure, self).__init__()
    self.canvas=FigureCanvas(self)
    self.ConnSbPlt=Conn

#Chart including events: QT
class InventoryChartsWidget(QtGui.QDialog):

def __init__(self, parent=None,xlimlow=0,xlimhigh=100,ylimlow=0,ylimhigh=100, G_array=[], N_array=[], ddom_array=[], hdom_array=[], speciesDict={}):

    QMainWindow.__init__(self, parent)

    #Fake stupid data
    self.mG_array  = [2] * 10
    self.mHdom_array = [0.5] * 10

    #jte to make sur I have it
    self.xdata_start=-1.0

    self.create_main_frame()

    self.setModal(False)
    self.setVisible(True)
    self.show()

def create_main_frame(self):
    #Associate a Qwidget with the InventoryChartsWidget widget

    self.main_frame = QtGui.QWidget()
    LesTabs = QtGui.QTabWidget()
    self.tabG   = QtGui.QWidget()

    #Fill the tab with Matplotlib object and draw the charts
    self.tabG=self.create_tab(self.tabG)
    self.on_draw_G(self.tabG)
    self.tabG.fig.subplots_adjust(left=0.02,bottom=0.05,right=1,top=0.95,wspace=0.2,hspace=0.2)

    LesTabs.addTab(self.tabG,"Chart")

    grid = QGridLayout()
    grid.addWidget(LesTabs, 0, 0)
    self.main_frame.setLayout(grid)
    self.setLayout(grid)
    self.layout().addWidget(self.main_frame)

def UpdatePlot_DataSelection_withArg(self,TheEvent):
    #SLOT
    print("WITH ARG : Get connected here process the data in the subplot XX...",TheEvent)

def on_draw_G(self,tab):
    #Juts one subplot for test purpose
    tab.fig.clear()
    tab.plots = []
    subPlot = tab.fig.add_subplot(111)
    subPlot.hold(False)
    tab.plots.append(subPlot)
    self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
    subPlot = tab.fig.add_subplot(122)
    subPlot.hold(False)
    tab.plots.append(subPlot)
    self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
    tab.canvas.draw()

def create_tab(self,tab):
    #Create the tab widget, associated with Matplotlib plot

    Conn=TheConnector()
    #MATPLOTLIB
    tab.fig = ChartFigure(Conn)
    tab.canvas = FigureCanvas(tab.fig)
    tab.canvas.setParent(tab)
    tab.canvas.setFocusPolicy(Qt.StrongFocus)
    tab.canvas.setFocus()

    #connect signal to slot
    Conn.selecteddataregionARG.connect(lambda who="Three": self.UpdatePlot_DataSelection_withArg(who))

    tab.mpl_toolbar = NavigationToolbar(tab.canvas, tab)

    vbox = QVBoxLayout()
    vbox.addWidget(tab.canvas)
    vbox.addWidget(tab.mpl_toolbar)
    tab.setLayout(vbox)

    tab.canvas.mpl_connect('button_press_event', tab.fig.onclick)

    return tab

def on_key_press(self, event):
    #Keyboard input: standard mpl key press
    key_press_handler(event, self.canvas, self.mpl_toolbar)

def PlotData_G(self, plot, G_array, hdom_array):
    # Plot G
    plot.hold(False)
    plot.scatter(x=hdom_array, y=G_array, marker='+',linewidths=1.5)
    plot.set_autoscaley_on(True)

def main():
app = QApplication(sys.argv)
form = InventoryChartsWidget(xlimlow=0,xlimhigh=60,ylimlow=0,ylimhigh=80)
form.show()
app.exec_()

if __name__ == "__main__":
main()

Maybe it can help someone ...
We can of course argue if the 3 classes make sense but this is another topic.

A: Here is how you could transfer the event to the main class:
from __future__ import print_function
from __future__ import division

import sys

from PyQt4 import QtGui
from PyQt4 import QtCore

from matplotlib.figure import Figure
from matplotlib.backend_bases import key_press_handler
from matplotlib.backends.backend_qt4agg import (
FigureCanvasQTAgg as FigureCanvas,
NavigationToolbar2QT as NavigationToolbar)

#Connect InventoryChartsWidget to ChartFigure: QT
class TheConnector(QtCore.QObject):

    selecteddataregion=QtCore.pyqtSignal(object, name='selecteddataregion')

    def emitsignal(self,xmin,xmax,ymin,ymax, event):
        self.selecteddataregion.emit((xmin,xmax,ymin,ymax, event))

#Chart including events: MATPLOTLIB
class ChartFigure(Figure):

    def onclick(self,event):
        #MAIN ISSUE
        #HOW TO RETURN THE subplot axes to class InventoryChartsWidget?

        if event.button==1 :
            print('OK: Axes is ... ', event.inaxes)
            self.ConnSbPlt.emitsignal(1.0,1.0,2.0,2.0, event)

    def __init__(self,Conn):
        #Init the Matplotlib
        Figure.__init__(self) #initialize the orginal class, see also super()
        super(ChartFigure, self).__init__()
        self.canvas=FigureCanvas(self)
        self.ConnSbPlt=Conn

#Chart including events: QT
class InventoryChartsWidget(QtGui.QDialog):

    def __init__(self, parent=None,xlimlow=0,xlimhigh=100,ylimlow=0,ylimhigh=100, G_array=[], N_array=[], ddom_array=[], hdom_array=[], speciesDict={}):

        QtGui.QMainWindow.__init__(self, parent)

        #Fake stupid data
        self.mG_array  = [2] * 10
        self.mHdom_array = [0.5] * 10

        #jte to make sur I have it
        self.xdata_start=-1.0

        #fake plot to get a member of type subplot: UGLY!
        #Attempt to create a member object "axes"
        self.tabFake = QtGui.QWidget()
        self.tabFake = self.create_tab(self.tabFake)
        self.tabFake.plots = []
        self.subPlotFake = self.tabFake.fig.add_subplot(111)

        print("here is OK; it exists ...", self.subPlotFake)

        self.create_main_frame()

        self.setModal(False)
        self.setVisible(True)
        self.show()

    def create_main_frame(self):
        #Associate a Qwidget with the InventoryChartsWidget widget

        print("OK here too; it exists ... ",self.subPlotFake)

        self.main_frame = QtGui.QWidget()
        LesTabs = QtGui.QTabWidget()
        self.tabG   = QtGui.QWidget()

        #Fill the tab with Matplotlib object and draw the charts
        self.tabG=self.create_tab(self.tabG)
        self.on_draw_G(self.tabG)
        self.tabG.fig.subplots_adjust(left=0.02,bottom=0.05,right=1,top=0.95,wspace=0.2,hspace=0.2)

        LesTabs.addTab(self.tabG,"Chart")

        grid = QtGui.QGridLayout()
        grid.addWidget(LesTabs, 0, 0)
        self.main_frame.setLayout(grid)
        self.setLayout(grid)
        self.layout().addWidget(self.main_frame)

    def UpdatePlot_DataSelection(self, transfer_object):
        #SLOT
        xmin,xmax,ymin,ymax, event = transfer_object
        print ("Axes are now in the InventoryChartsWidget: ", event.inaxes)

    def on_draw_G(self,tab):
        #Juts one subplot for test purpose
        tab.fig.clear()
        tab.plots = []
        subPlot = tab.fig.add_subplot(111)
        #subPlot.hold(False)
        tab.plots.append(subPlot)
        self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
        subPlot = tab.fig.add_subplot(122)
        #subPlot.hold(False)
        tab.plots.append(subPlot)
        self.PlotData_G(subPlot,self.mG_array,self.mHdom_array)
        tab.canvas.draw()

    def create_tab(self,tab):
        #Create the tab widget, associated with Matplotlib plot

        print("OK member exists ... ", self.xdata_start)
        print("OK member exists ",self.tabFake)

        #ISSUE HERE: don't understand
        #print("NOT OK !!! member does not exist Why ? ",self.subPlotFake)
        # reason: self.subPlotFake does not yet exist

        Conn=TheConnector()
        #MATPLOTLIB
        tab.fig = ChartFigure(Conn)
        tab.canvas = FigureCanvas(tab.fig)
        tab.canvas.setParent(tab)
        tab.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        tab.canvas.setFocus()

        #connect signal to slot
        Conn.selecteddataregion.connect(self.UpdatePlot_DataSelection)

        tab.mpl_toolbar = NavigationToolbar(tab.canvas, tab)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(tab.canvas)
        vbox.addWidget(tab.mpl_toolbar)
        tab.setLayout(vbox)

        tab.canvas.mpl_connect('button_press_event', tab.fig.onclick)

        return tab

    def on_key_press(self, event):
        #Keyboard input: standard mpl key press
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    def PlotData_G(self, plot, G_array, hdom_array):
        # Plot G
        #plot.hold(False) #axes.hold is deprecated.
        plot.scatter(x=hdom_array, y=G_array, marker='+',linewidths=1.5)
        plot.set_autoscaley_on(True)
        plot.tick_params(labelsize=8)

def main():
    app = QtGui.QApplication(sys.argv)
    form = InventoryChartsWidget(xlimlow=0,xlimhigh=60,ylimlow=0,ylimhigh=80)
    form.show()
    app.exec_()

if __name__ == "__main__":
    main()


text:
Q: Is the analyzer really trustworthy concerning the detection of memory leaks? In my app delegate I have the following code snippet:
...

@synthesize model = _model;

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

    // Allocate the model
    self.model = [[Model alloc] init];

    ...
}

- (void)dealloc
{
    [_model release];
    [super dealloc];
}

...

The XCode Analyzer reports a potential memory leak on the line after the allocation of the model (it did go away when I added an autorelease statement, so I guess it just got mixed up with the line numbers). Is this truly a memory leak or is the analyzer confused? After all a release is done in the dealloc method. So is there a potential of a memory leak here and in which situations?
If that's so I guess the solution would be to add autorelase to the allocation.

A: It's a memory leak if the property is defined as retain because it has a retain count of 2 - once for alloc and once on assignment to the property - but you only release it once.  Xcode does get confused about line numbers though.

A: Yes, it is trustworthy!
If you click on the blue arrow icon on the line where the analyzer shows a leak:

it will give you more information about the leak, showing exactly where it originated, and in this case the reason why it appears on the next line:

A: The static analyser is very trust worthy. after all ARC is completely based on it. It has to be good in order for iOS5 programming to work.


text:
Q: Batch extracting multiple .aac tracks from an .mp4 using ffmpeg? How do I create a ffmpeg .bat file that will let me drop in .mp4 file(s) and extract multiple .aac tracks without any converting or transcoding taking place ? I do know that there will always be 3 .aac tracks.
I have tried using:
ffmpeg -i INPUT.mp4 -c copy -map 0:a:0 Output.aac

But that extracts only the first audio stream.
Ideally i would like to be able:
-videoname.mp4
-drop videoname.mp4 onto bat
-outputs videonameaudio1.aac, videonameaudio2.aac, videonameaudio3.aac
thanks in advance :)

A: The command will be
ffmpeg -i videoname.mp4 -c copy -map 0:a:0 videonameaudio1.aac -c copy -map 0:a:1 videonameaudio2.aac -c copy -map 0:a:2 videonameaudio3.aac


text:
Q: Send mail to different customer on their birthday I have found that there is related topic.However, there are some difference because the people is asking for ubuntu server but i am using the Apache (xampp****) the latest version, so are there any method to let the system automatically send mail by checking the date ?
Can it applies to some schedule sending as well? thanks
I have the script for sending it , the only thing i need is how to schedule  send.
Edit:
Make it simpler , assuming only windows is the only platform. Can i do some php script and create the cron job in os , so that my client can schedule their mail in my system instead of doing it in the os?
3 rd party cron job is good suggestion but there is limitation (what if their service break down etc...) and i want everything is based on own system

A: *

*If your xampp is on Windows, you can use windows-schedulers to call a particular script (PHP script in your case, preferably by an URL), which checks the birthdays of all the users and sends them mail accordingly.

*If your xampp is on Linux/Unix/etc, you can use cron-jobs, and rest is same!

*There is also a third way, a third-party scheduler or say online-cron, which will remotely call yours script (php-page).
Example:
If you are doing the cron-settings of OS yourself, you can still let the configure as to whom to email in your system, rather than OS.
After all, a cron so is to do something repeatedly, in your case, its just calling your scripts, by an URL.
Now regarding the time settings, you can make the CRON call your script every hour, and your php script will check the appropriate time, and fire the mails!

A: schedule a script in crontab or scheduler which will check the birthday of your customer
and send them an email
this script will run everyday at particular time of the day

A: use server cron job to run a script that will send out email. ur script should compare current's date and customer's birthday date.

A: You could use a cron-job. With PHP that get all the people that you want to send an email and gets template and send it just substitute the name and other stuff

A: You may use Wishing Application. Getting started provides good details on how to kick started. At minimal you need only two things the excel file having wish details (Birthday and on work anniversary), and a configuration file (application.properties) to provide the mapping details and other configurations. There are various options to run this application, locally (background, foreground, docker, windows-scheduler etc) on cloud
Disclaimer : I am the owner of application.


text:
Q: How to properly bake a ultra high vacuum chamber? I need to get rid of water excess in my vacuum chamber, and for that there is the procedure of baking. In order to do that there are several things that one needs to consider, the power, heat load, type of heat tape to use etc. Since I've never done this before, I hope that some of you could share their advice on that subject.

A: The usual procedure involves

*

*Careful preparation for ultra high vacuum

*

*Do you reach a good high vacuum?

*Can all the equipment withstand high temperatures over a long period of time? If not you might to cool those parts while heating the rest of the chamber.

*Try to remove all materials that might have a high outgassing rate, otherwise ultra high vacuum is never achievable.

*Check for residual gas volumes, e.g. from screw threads.

*Prepare and bake

*

*Wrap heat tape around metallic parts of vessel, try to get good contact and not much overlap. The tape should not reach very high temperatures when used alone.

*Pump, heat and monitor gas pressure. It should rise a bit, exact numbers depend on the circumstances. Do a smell test, if it smells like burnt plastic you forgot something. Heat for at least 24 hours, even at elevated temperatures this might take a long time. The longest time a colleague used was 2 weeks.

If heating is not going to work alternatively use a sorption pump with either liquid nitrogen or liquid helium.


text:
Q: How do I remove diskdigger completely from my computer? I don't want to have any trace of diskdigger on my computer. How do I get rid of it?

A: Enter the following commands to completely delete DiskDigger and everything asociated from it's install, based on, and as per Running DiskDigger in Linux. The 1st part completely removes (purges) the packages for Windows Forms 4.0 for Mono you needed to run it.
sudo apt-get purge libmono-system-windows-forms4* libmono-system-design*
sudo apt autoremove
rm diskdigger.zip
rm DiskDigger.exe


text:
Q: How to resolve the transitive dependencies of different versions? Suppose my application depends on two libraries one of which is Spark.
Spark has the transitive dependency of com.fasterxml.jackson(specific version and not configurable).
Another depending library also has the same transitive dependency, but a newer version(will not work with the version Spark requires).
So basically both versions are required when testing(unit tests) the app.
What would be a recommended way(workaround) to co-exist both versions? if any

A: You can try shading the problematic dependency with jarjar-abrams. Shading is a process where the bytecode of the library is rewritten to move its classes to a different package, and all references to these classes are rewritten as well to match.
https://eed3si9n.com/jarjar-abrams
Unfortunately it often doesn't work when reflection is involved – I don't know if Jackson uses reflection in a way that's incompatible with this process, but it's worth a shot.


text:
Q: Uncaught Error: Incomplete or corrupt PNG file I am trying to add a couple of images to a pdf. I am using the jspdf plugin for this. My code is as following:
document.getElementById("help").addEventListener("click",function(){
    var base1="";
    var base2="";
    var base3="";
    var doc = new jsPDF();
    var img=new Image();
    var img1=new Image();
    var img2=new Image();
    img.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0);
        base1 = canvas.toDataURL();
    }
    img.src='/Screenshot (1).png';
    img1.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img1, 0, 0);
        base2 = canvas.toDataURL();
    }
    img1.src='/Screenshot (2).png';
    img2.onload = function() {
        var canvas = document.createElement("canvas");
        ctx = canvas.getContext('2d');
        ctx.drawImage(img2, 0, 0);
        base3 = canvas.toDataURL();
    }
    img2.src='/Screenshot (3).png';

    doc.addImage(base1,'PNG',20,36,100,120);

    doc.addImage(base2,'PNG',20,158,100,120);

    doc.addImage(base3,'PNG',20,281,100,120);
    doc.save("example.pdf");
})

But when I execute the code, I get the following error in addImage():

Uncaught Error: Incomplete or corrupt PNG file

How do I fix this?
EDIT: After implementing @AKX's solution, the code works in the local machine. But when tested live, it throws this error:

Uncaught (in promise) Event {isTrusted: true, type: 'error', target:
null, currentTarget: null, eventPhase: 0, …}

A: You're not waiting for all the images to load. You can refactor things to use a promisified function to load an image and turn it into a data URI (though according to the docs for jspdf, a HTMLImageElement would also do, so you could skip the canvas bit), and then turn your handler into an async function to make it easy to just await for all the loads.
function loadImageAsDataURL(url) {
  return new Promise((resolve, reject) => {
    var img = new Image();
    img.onload = function () {
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      resolve(canvas.toDataURL());
    }
    img.onerror = reject;
    img.src = url;
  });
}

document.getElementById('help').addEventListener('click', async function () {
  // Load all images first...
  var base1 = await loadImageAsDataURL("/Screenshot (1).png");
  var base2 = await loadImageAsDataURL("/Screenshot (2).png");
  var base3 = await loadImageAsDataURL("/Screenshot (3).png");
  // ... and then generate the PDF.
  var doc = new jsPDF();
  doc.addImage(base1, 'PNG', 20, 36, 100, 120);
  doc.addImage(base2, 'PNG', 20, 158, 100, 120);
  doc.addImage(base3, 'PNG', 20, 281, 100, 120);
  doc.save('example.pdf');
})


text:
Q: Get text from closest DIV contains string I'm trying to get the full text of a dynamic id div that contains a string.
For example:

COD: 123 Status: OK

Approved

That way works. But only what is inside the p
var codigoExame     =   $( "p:contains('OK')").html()
-- returns COD: 123 Status: OK

If I use the same way, it returns all content from the parent divs
I need all the content inside the closest div and I tried doing it in the following ways:
var a = $(this).closest("div").is(":contains('OK')").text()

var b = $(this).parents("div").parents().eq(1).is(":contains('OK')").text()

var c = $(this).closest('div').attr('id').is(":contains('OK')")

Did not work.
Any ideas on how I can get this content?
Thank you very much in advance


text:
Q: Extract text from PDF in code I'm making an app for my school which people can check with if they've got a schedule change. All schedule changes are listed here: http://www.augustinianum.eu/roosterwijzigingen/14062012.pdf. I want to search that page for a keyword (the user's group, which is entered in an EditText). I've found out how to make the app check if the edittext matches a certain string, so now I only need to download all of the text on that page to a string. But the problem is that it's not a simple webpage, but a PDFpage. I've heard that you need a special pdf library or something to extract the text from the PDF and then put that text into a string and then search the string for keywords using contains().
However I've got some questions about that:

*

*This PDF is made with a PDF-creator, it's not a scanned page or so. You can actually for example select the text or search it for keywords using CTRL+F. So I wonder if it is actually required to extract the PDF and stuff or is there maybe an easier way.

*I want the app to check for changes every, let's say hour. So it also has to download the PDF and extract the text every hour (about 8 pages), would that consume very much juice?

*I've heard that there are many many libraries which do what I want. So which should I use? (If possible, I'd like one which is free :))

*Could anyone explain to me how to use it in my code? (I'm not really experienced, so plz keep it a little easy :))
THANK YOU ALL SO MUCH!!!

A: Unfortunately, I did not working with java and you have to implement it in java code by yourself. Now I'll tell you, how finally I did it:
1) I took the file by your link. PHP is doing it by @fopen("http://...").
2) I opened it as a binary (it is important) and extracted two parts:
2.1) Data 3 0 obj part, which represents creation and modification dates. I did it by regex. It was simple and I mention it above.
2.1) Data stream from 5 0 obj, which represents the deflated data. IMPORTANT! Microsoft Excel inserts two bytes 0D 0A as a line break. Do not forget it, when you filtering the content by regexp. This bytes in the start and in the end have not to be included in extracted string.
3) I inflate a coded stuff by function $uncompressed = @gzuncompress($compressed) and put it in external file. You can see results there
4) Funniest part. The raw data inside the file in textual format. It looks like [(V)-4(RI)16(J)] TJ, and means VRIJ. You can read about texts in PDF in the PDF Reference v1.7, part 5.
5) I believe, the regular expressions can help you extract or/and transform the data.
IMPORTANT: I said "data stream from 5 0 obj", but number of the object "is subject of change". You must control the reference to the object from dictionary->pages->page->content chain. Description of the "bread crumbs" you can find in the manual I mentioned above.
Unfortunately, Excel do not embed any table structure in the PDF, but you can find the coordinates of the text portions and interprete it. Anyway it is a mess.
Do you think, dear Merlin, it is hard? No, dear, it is not. It is not hard, because there is no unicode symbols. The unicode in the PDF is THE REAL SUCK!
Good luck!

A: This PDF was made by Microsoft Excel and have the date stamps:
3 0 obj
<</Author(Janszen, Jan)
/CreationDate(D:20120613153635+02'00')
/ModDate(D:20120613153635+02'00')
/Producer(˛ˇMicrosoftÆ ExcelÆ 2010)
/Creator(˛ˇMicrosoftÆ ExcelÆ 2010)>>
endobj

You can use almost any programming language for taking the file by URL and extraction "ModDate" content. New ModDate means information update. For extracting this information you need not any libraries - this is the text in the file, lines 9, 10 and 11.
Ask Jan Janszen to add you in distribution list. The data in the file is encoded. You have to use a lot of programming techniques to reach source and restore information.


text:
Q: Specific examples of Agile documentation? In an answer to the question Documents for a project?, Chris Ballance replied that "User Stories" and a "burndown chart" are the two most useful types of project documentation for a developer.
My question is, do you know of any good example[s], which I can see (for example on the internet, or in a book), of these kinds of documentation?
If possible I'd be happy to see many examples, including:

*

*Small/short/simple examples

*Big/long/complicated examples

*Famous examples

*High-quality examples

I don't find this an easy topic to Google for: I find lots written about it, but fewer demonstrations showing it.

A: A very good place to start as far as books are concerned is User Stories Applied and Agile Estimation and Planning both by Mike Cohn. This have excellent examples and good starting points for anyone first coming to agile methodologies.
As far as website resources they are few and far between. Probably a good place to actually start would be searching for those keywords on Google Images as many people take photos of their burndown charts and User Stories. This helped me a lot when starting. Here are some samples: Burndown Chart, and User Stories
Please note however while a burndown chart is a simple report that you run on your current story points left in an iteration, User stories are more complex than that and do require a bit of reading to wrap your head around. Start with User Stories Applied book for that.
Hope that helps!

A: I think for both of these questions, you can do a lot worse than scan over Alistair Cockburn's web site. In particular, he has a great article about burndown charts and some different ways to generate them:
http://alistair.cockburn.us/Earned-value+and+burn+charts
(thoug I echo the earlier poster's recommendation of Mike Cohn's work).
One of the tricks is deciding what kind of documentation is good for YOUR project. Do you have many developers, spread over time and space? You will need bigger, heavier, more detailed stories. Do you have one or two devs working in the same place? You can get away with lighter ones. Has the team worked in the system (if it's legacy) for a long time? Light stories will probably do. Is the team new to the system, or are its business requirements complex? This pushes you in the more-detail direction.
If you're on a "small" project by any of the dozen definitions of small, you may be fine with very light stories. Here's an example, again from Cockburn's site:
http://alistair.cockburn.us/Examples+of+ultra-light+use+cases

A: A few months ago, we started writing the user documentation at the same time as we are developing features. A technical writer is assigned to each Scrum teams.
Having to write the user documentation while developing helps validating the design. The technical writer also participate in the design of the application.
This is in addition of release burndown and sprint burndown.
Additional documentation is created by the team when they feel it is useful to communicate with the product owner. This became less important as we are learning to write better user stories.

A: Consider reading Ambler's "Agile Modeling". He makes a very strong case as to why just creating tons of full UMLs is a fairly bad idea, and gives some good examples.


text:
Q: NSDate is converting really strangely I have a time: 7:46 am
I want to convert this to NSDate.  I do this:
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"h:mm a"];
NSDate *sr = [f dateFromString:@"7:46 am"];

I NSLog sr and I get 1969-12-31 22:46:00 +0000
Those times are not the same.  Why is this so messed up?

A:
No. Its not strange. NSDateConverter & NSDate are just doing their intended job here.

You are trying to convert "7:46 am" into a date. It contains only the time. No date is specified in the string. NSDate will default to "1970-01-01"(Unix epoch) if no date is specified. So after you convert the string you will get the date "1970-01-01 7:46 am". When you trying to display this in NSLog, if will display the date after adjusting the timeZone offset value. I guess you live in Japan or Korea. Probably the offset of your region is +09:00. So it diaplays the date subtracting the offset. So you are seeing "1969-12-31 22:46:00 +0000" in the log.
You can use the following method to set that time to a particular date, may be today.
NSString *timeStr = @"7:46 am";
NSDateFormatter *f = [NSDateFormatter new];
[f setDateFormat:@"yyyy-MM-dd"];
NSString *dateStr = [f stringFromDate:[NSDate date]]; // dateStr = 2011-06-10
dateStr = [dateStr stringByAppendingFormat:@" %@", timeStr]; // dateStr = 2011-06-10 7:46 am
[f setDateFormat:@"yyyy-MM-dd h:mm a"];
NSDate *sr = [f dateFromString:dateStr];

A: You aren't providing the day or the timezone... assuming you want to express "today at 7:42am", you can use this code:
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setHour:7];
[comps setMinute:42];
NSDate *myDate = [calendar dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];

The NSLog of myDate should give you the expected output now (assuming you wanted today@7:46am).

A: Since you are only specifying the time that you want the NSDate to refer to, and not the date, the formatter is using the default date (which seems to be very close to the UNIX epoch). Like Julio said, you should specify the current date as well, if you want the NSDate to refer to the time on that specific date.


text:
Q: Getting Can't create handler inside thread that has not called Looper.prepare() i've created a service in android in which at every 3 seconds it will send the GPS cordinates to a remote mysql database.
but i did the 3 seconds loop using ScheduledExecutorService but when i click the start button to start the service i'm getting  java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
 @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            Toast.makeText(this, "Application Started!!!...", Toast.LENGTH_LONG).show();
            ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(5);

            // This schedule a runnable task every 2 minutes
            scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
              public void run() {
                updateLatLong();
              }
            }, 0, 3, TimeUnit.SECONDS);
            return START_STICKY;
        }

A: As far as I remember, this error relates the the way you are trying to access a Handler from the wrong thread.
Remember your Service.onStartCommand() method is running on the main thread.
Your ScheduledExecutorService is not running on the main thread.
Depending on what the updateLatLong() method is doing, you need to run part of that on the main thread - I'm guessing there might be some UI changes you make, or perhaps making a callback to the Service or Activity from that method.
So put that callback or UI code in a runOnUiThread() block... that will ensure that you are on the UI thread when you start, and on the UI thread when complete.

There are alternatives, such as using ASyncTask or an IntentService but the above is the essence of the problem.


text:
Q: Zip and calculate I am looking for a solution without the use of recursion. I have 3 datas such as:
names = ["Alice", "Bob", "Charlie", "David"]

-- their grades:
grades :: [[Int]]
grades = [[3, 2], [4, 6], [2, 3], [1, 4]]

-- And the weights for a total note
weights :: [Float]
weights = [0.75, 0.25]

This should be understood as follows:
Alice's grades:   3 and 2 -- The grade 3 weighted with 75% and the grade 2 with 25%
Bob's grades:     4 and 6 -- The grade 4 weighted with 75% and the grade 6 with 25%
Charlie's grades: 2 and 3 -- The grade 2 weighted with 75% and the grade 3 with 25%
David's grades:   1 and 4 -- The grade 1 weighted with 75% and the grade 4 with 25%

I wrote a function which calculates the averageGrade for one student:
averageGrade :: [Float] -> [Int] -> Float

I have to accomplish a function according to this type:
allStudents :: [String] -> [[Int]] -> [Float] -> [(String, Float)]

This function should give tuples of each person with their average grade such as:
[("Alice", 2.75), ("Bob", 4.5), etc....]

The calculation is made by averageGrade (weights) ([Specific Grades]), e.g.
averageGrade (weights) ([3,2])

if I want to calculate it for Alice.
How can I iterate over a list without going through it via head and tail (because recursion is not allowed)?

A: So you want
allStudents  :: [String] -> [[Int]] -> [Float]            -> [(String, Float)]

which is not all that different from
allStudents2 :: [String] -> [Float] -> [[Int]]            -> [(String, Float)]

and you have
averageGrade ::             [Float] ->  [Int]  ->  Float

such that
averageGrade (weights ::    [Float]) :: [Int]  ->  Float

and since
map (foo ::                               a    ->   b      )
                           ::          [  a  ] -> [ b   ]

we have
map (averageGrade weights) ::          [[Int]] -> [Float]

and
map (averageGrade weights) (grades :: [[Int]]) :: [Float]

and the one last missing piece to the puzzle is
_ ::            [ c    ]  ->                      [ b   ] -> [( c    , b    )]

such that
_ (names ::     [String]) ::                      [ b   ] -> [(String, b    )]

A: If you are prohibited to use recursion, that means that you should use some standard functions like foldl, foldr, map, zip and so on.
As you have averageGrade function to process grades of a student, then you can process a list of such with map like this:
map (averageGrade weights) grades

It will apply averageGrade weights function on each element of list one by one, and return you a list of results, namely, the list of average grades for every student.
So now, when you processed the data of all students, all you need is just pair each student name with appropriate average grade. You can use zip function for that:
allStudents :: [String] -> [[Int]] -> [Float] -> [(String, Float)]
allStudents names grades weights = zip names $ map (averageGrade weights) grades

You can test it here: https://repl.it/@Yuri12358/so-zip


text:
Q: Extending binary operation used by homotopy classes There is this operation you learn in algebraic topology when working with homotopy groups and loops i.e. paths on a topological space $X$,  $p:[0,1]\rightarrow X$ with $p(0) = p(1)$. Basically it is an operation $*$ between two loops $p,q:[0,1]\rightarrow X$ defined by
$$
p*q(t):= \left\{
\begin{array}{ll}
p(2t)  & t\in[0,\frac{1}{2}]\\
q(2t-1) & t\in(\frac{1}{2}, 1]\\
\end{array}
\right.
$$
It so happened that I work a lot now with paths on a specific topological space (mostly with real manifolds). And I tend to work a lot with this operation not on loops but on paths in general (i.e. $p(0)$ is not necessarily the same as $p(1)$ but...). I redefined this operation on generic paths in such a way that you get the same equality as above if $p(1) = q(0)$ and otherwise we define $p*q = p$ (so in general this is nothing but a concatenation of paths if this can be done otherwise we leave it to be the first path). With this it is easy to see that the set of paths on $X$ and the operation makes a noncommutative semigroup and I am not sure if there is anything more algebraic about it.
I am not an algebraic topologist so obviously I am just going by intuition here and not any past experience. So my question is: is this something of any relevance to people in algebraic topology (or any other field)?

A: Check out my answer to https://math.stackexchange.com/questions/706093/ which explains something about Moore paths; concatenation of these gives a category, i.e. is strictly associative with strict identities. The general setting for homotopy classes rel end points of paths is that of groupoids.


text:
Q: How to enable IDN/IRI Support for URI-Class by code? I'm trying to enable the IDN/IRI support for the URI class, because I need the "Uri.IsWellFormedUriString" method on german umlaut-domains (e.g. www.bücher.de).
I found similar question at https://stackoverflow.com/a/6107682/413531 (taken from http://msdn.microsoft.com/en-us/library/system.uri.aspx at "International Resource Identifier Support") but the solution is not working for me. My current app.config file looks something like this:
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>
    </configSections>
    <userSettings>

    </userSettings>
    <applicationSettings>

    </applicationSettings>
</configuration>

when I just add
  <uri>
  <idn enabled="All" />
  <iriParsing enabled="true" />
  </uri>

as an other child of  at the end, an exception is thrown: ConfigurationErrorsException - {"Das Konfigurationssystem konnte nicht initialisiert werden."}
So I read further in http://msdn.microsoft.com/en-us/library/system.uri.aspx an came across

IRI and IDN processing in the Uri class can also be controlled using
  the System.Configuration.IriParsingElement,
  System.Configuration.IdnElement, and System.Configuration.UriSection
  configuration setting classes. The
  System.Configuration.IriParsingElement setting enables or disables IRI
  processing in the Uri class. The System.Configuration.IdnElement
  setting enables or disables IDN processing in the Uri class. The
  System.Configuration.IriParsingElement setting also indirectly
  controls IDN. IRI processing must be enabled for IDN processing to be
  possible. If IRI processing is disabled, then IDN processing will be
  set to the default setting where the .NET Framework 2.0 behavior is
  used for compatibility and IDN names are not used.

Unfortunatly I was not able to find an example for the usage of System.Configuration.IriParsingElement, System.Configuration.IdnElement, and System.Configuration.UriSection. I've no clue how these are used...
So basically, my problem comes down to: I want to enable IDN/IRI support in the URI class, but I can't figure out how to do this. The config-solution is not working for me, so I would like to try it by code, but can't figure out how. Btw. I would also like to know why the config thing isn't working ;)

A: This is my solution, tested worked.
Basically, you need to change the value of the static non-public fields of System.Uri:

*

*s_IdnScope

*s_IriParsing
public static bool ToggleIDNIRISupport(bool enable)
{
    //Important: Try IsWellFormedUriString() once to initialize static fields: s_IdnScope, s_IriParsing
    Uri.IsWellFormedUriString("http://example.com/query=ü", UriKind.Absolute);

    //Get the assembly that contains the class
    Assembly assembly = Assembly.GetAssembly(typeof(Uri));
    if (assembly != null)
    {
        //Use the assembly in order to get the type of the class
        Type uriType = assembly.GetType("System.Uri");
        if (uriType != null)
        {
            object idnScope = uriType.InvokeMember("s_IdnScope", BindingFlags.Static | BindingFlags.GetField | BindingFlags.NonPublic, null, null, new object[] { });
            if (idnScope != null)
            {
                if (enable)
                {
                    uriType.InvokeMember("s_IdnScope", BindingFlags.Static | BindingFlags.SetField | BindingFlags.NonPublic, null, null, new object[] { UriIdnScope.All });
                }
                else
                {
                    uriType.InvokeMember("s_IdnScope", BindingFlags.Static | BindingFlags.SetField | BindingFlags.NonPublic, null, null, new object[] { UriIdnScope.None });
                }
            }

            object iriParsing = uriType.InvokeMember("s_IriParsing", BindingFlags.Static | BindingFlags.GetField | BindingFlags.NonPublic, null, null, new object[] { });
            if (iriParsing != null)
            {
                uriType.InvokeMember("s_IriParsing", BindingFlags.Static | BindingFlags.SetField | BindingFlags.NonPublic, null, null, new object[] { enable });
            }
        }
    }

    return true;
}

A: I found a solution - at least for the app.config part. According to http://social.msdn.microsoft.com/Forums/nl-NL/netfxnetcom/thread/56a73dbb-c0d4-4cad-876d-83ad74064393 one has to add an additional line in the app.config if a .Net version lower 4.0 is used:
<configSections>

</configSections>

After adding this line, I could also add
<uri>
    <idn enabled="All" />
    <iriParsing enabled="true" />
</uri>

without getting an error. My complete app.config now looks like this:
<configuration>
    <configSections>
        <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

        </sectionGroup>

    </configSections>

    <uri>
        <idn enabled="All" />
        <iriParsing enabled="true" />
    </uri>

    <userSettings>

    </userSettings>
    <applicationSettings>

    </applicationSettings>
</configuration>


text:
Q: Using an adjacency matrix vs adjacency list when sorting I want to implement a topological sort based on the DFS method:
import java.util.*;

public class TopologicalSort {

  static void dfs(List<Integer>[] graph, boolean[] used, List<Integer> res, int u) {
    used[u] = true;
    for (int v : graph[u])
      if (!used[v])
        dfs(graph, used, res, v);
    res.add(u);
  }

  public static List<Integer> topologicalSort(List<Integer>[] graph) {
    int n = graph.length;
    boolean[] used = new boolean[n];
    List<Integer> res = new ArrayList<>();
    for (int i = 0; i < n; i++)
      if (!used[i])
        dfs(graph, used, res, i);
    Collections.reverse(res);
    return res;
  }

  // Usage example
  public static void main(String[] args) {
    int n = 3;
    List<Integer>[] g = new List[n];
    for (int i = 0; i < n; i++) {
      g[i] = new ArrayList<>();
    }
    g[2].add(0);
    g[2].add(1);
    g[0].add(1);

    List<Integer> res = topologicalSort(g);
    System.out.println(res);
  }
}

However im unsure how the implementation differs when using as adjacency matrix rather than a list. Which I have stored as:
private Edge[][] adjMatrix;       // Adjacency matrix

how would I use an adjacency matrix in place of the adjacency list as in lines 16, 29.
Thank You

A: That list does not need to be changed in my opinion, you need to record the post order of the visited vertices anyway.
The adjacency matrix is going to affect how you iterate through neighbour vertices of u, specifically this line for (int v : graph[u]) needs to be changed to something like:
for (int v = 0; v < adjMatrix[u].length; v++) {
    if (adjMatrix[u][v] != null && !used(v))
    // If there exists an edge between (u, v), and haven't visited v yet.
    {
         dfs(adjMatrix, used, res, v); // visit v
    }
}


text:
Q: Install flash for Chrome on linux without root? I'm on a workstation here and the admins haven't enabled Flash for Chrome, but it does work under Firefox. Is there some way I could config Chrome to point at the nswrapper_32_64.libflashplayer.so that Firefox is using or copy it to my home directory somewhere and have it working?
Running Chrome 13 on RHEL6.

A: Chrome includes Flash player. You may just need to enable it.
Chromium does not include Flash player. If it does not recognize the same plugins Firefox does (and it should), you can try putting all relevant files into ~/.mozilla/plugins, one of the directories searched by chromium.


text:
Q: Commutation relations for a CFT Exercise
To calculate the commutator $[L_m ; \phi_n]$ where:
$$T(z) = \sum \frac{L_m}{z^{m+2}} \hspace{5mm} and \hspace{5mm} \phi(w) = \sum \phi_n \frac{1}{w^{n+h}} \tag{1}$$
using contour integrals and where the OPE for a primary field of weight $h$ with the energy-momentum tensor is
$$T(z)\phi(w) \sim \frac{h\phi w }{(z-w)^2} + \frac{\partial \phi(w)}{z-w}+ ... \tag{2}$$
My take on it
My first instinct was to commutate $L_m$ and $\phi_n$, meaning $[L_m ; \phi_n]= L_m\phi_n-\phi_nL_m$
We write the following modes where the contour circles the origin  $$L_n = \frac{1}{2\pi i } \oint dz \hspace{1mm}z^{n+1}T(z) \tag{3}$$
and
$$\phi_n = \frac{1}{2\pi i }\oint \phi(w) w^{n+h-1} \tag{4}$$
Problem
But when comparing this to my lecturer's notes he gets:
$$[L_m ; \phi_n] = \frac{1}{2\pi i }\oint \phi(w) w^{n+h-1} \frac{1}{2\pi i }\oint_w \phi(w) w^{n+h-1} \tag{5}$$
later the OPE is substituted in :
$$[L_m ; \phi_n] = \frac{1}{2\pi i }\oint dw\frac{1}{2\pi i }\oint dz \left(\frac{h\phi w}{(z-w)^2} +\frac{\partial \phi }{(z-w)}\right) z^{m+1}w^{n+h-1}$$
The regular terms do not contribute to the integral. Integrating by parts in z in the first term, we get:
$$[L_m ; \phi_n] = \frac{1}{2\pi i }\oint dw\frac{1}{2\pi i }\oint dz \left(\frac{h\phi w}{(z-w)}(m+1)z^m +\frac{\partial \phi }{(z-w)}\right)$$
This doesn't make sense to me as it looks like a multiplication  of the two terms, $L_n$ and $\phi_n$ instead of a commutation relation. Why is is this correct?
I understand that adding a second term would probably just cancel out with the first one, but shouldn't there be a second one, as it is a commutation?
Why is the first term the only one integrated by parts in z, why is the latter term not takeninto consideration?


text:
Q: VB.NET Date Comparison Not Returning Correct Results? I am pulling a date value from my database:
        Dim qfresho = From p In dbConfig.Configs _
                     Where p.Description = "FROD" _
                    Select p.dateValue
        Dim qfreshc = From p In dbConfig.Configs _
                      Where p.Description = "FRCD" _
                      Select p.dateValue

Then comparing these date values to the current date:
        If qfresho.First.Value >= Date.Now And qfreshc.First.Value <= Date.Now Then
        lblFreshman.Text = "Freshmen are currently eligible to register for a room."
    Else
        Dim frdays As TimeSpan
        frdays = (qfresho.First.Value).Subtract(Now)
        lblFreshman.Text = "Registration will open for freshmen in " & frdays.Days & " days."
    End If

But for some reason its always returning the Else condition - even though the values in the database should make the query true. Any ideas? I'm guessing for some reason its not pulling the results as a date?

A: Do the dates have time components that could be throwing off the compares?

A: Date.Now returns a DateTime, so does your database have dates and times or just dates?  If you just want the date, you can use Date.Today.

A: Why not just add two debugs before the comparison???
    Debug.WriteLine(qfresho.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))
    Debug.WriteLine(qfreshc.First.Value.ToString("MM/dd/yyyy hh:mm:ss.ffff"))

That should help.


text:
Q: Tkinter button state overwrites I am trying to make tic tac toe using tkinter, I am storing player and computer inputs in lists and use them to check if the input place is already taken or not. However, it is not working and after the second turn, disabled-buttons turn to normal, although they are already marked. So can someone please point out which part of code return the button to normal state.
from tkinter import *
import random
root = Tk()
root.title("Tic Tac Toe")
root.geometry("400x400")
global playerletter
global computerletter
playerletter = "X"
computerletter = "O"
x = 50
y = 50
playerList = []
computerList = []

def turn(button, box1, box2, box3, box4, box5, box6, box7, box8, box9):
    global count
    count = 0
    playerList.insert(count, button)
    if (button == 1):
        box1 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box1.grid(row=1, column=0)
    if (button == 2):
        box2 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box2.grid(row=1, column=1)
    if (button == 3):
        box3 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box3.grid(row=1, column=2)
    if (button == 4):
        box4 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box4.grid(row=2, column=0)
    if (button == 5):
        box5 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box5.grid(row=2, column=1)
    if (button == 6):
        box6 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box6.grid(row=2, column=2)
    if (button == 7):
        box7 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box7.grid(row=3, column=0)
    if (button == 8):
        box8 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box8.grid(row=3, column=1)
    if (button == 9):
        box9 = Button(root, text=playerletter, state=DISABLED, padx=x, pady=y)
        box9.grid(row=3, column=2)

    computer_input = random.randint(1, 9)

    computerList.insert(count, Button)

    for butts in playerList:
        if (computer_input == butts):
            while (computer_input==butts):
                computer_input = random.randint(1, 9)
                computerList.pop(count)
                computerList.insert(count, Button)

    for cuts in computerList:
        if (computer_input == cuts):
            while (computer_input==cuts):
                computer_input = random.randint(1, 9)
                computerList.pop(count)
                computerList.insert(count, Button)

    count += 1

    if (computer_input == 1 and box1['state'] != "DISABLED"):
        box1 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box1.grid(row=1, column=0)

    if (computer_input == 2 and box2['state'] != "DISABLED"):
        box2 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box2.grid(row=1, column=1)

    if (computer_input == 3 and box3['state'] != "DISABLED" ):
        box3 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box3.grid(row=1, column=2)

    if (computer_input == 4 and box4['state'] != "DISABLED" ):
        box4 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box4.grid(row=2, column=0)

    if (computer_input == 5 and box5['state'] != "DISABLED"):
        box5 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box5.grid(row=2, column=1)

    if (computer_input == 6 and box6['state'] != "DISABLED"):
        box6 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box6.grid(row=2, column=2)

    if (computer_input == 7 and box7['state'] != "DISABLED" ):
        box7 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box7.grid(row=3, column=0)

    if (computer_input == 8 and box8['state'] != "DISABLED" ):
        box8 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box8.grid(row=3, column=1)

    if (computer_input == 9 and box9['state'] != "DISABLED"):
        box9 = Button(root, text=computerletter, state=DISABLED, padx=x, pady=y)
        box9.grid(row=3, column=2)

    print("PLAYER CHOSE: ", button)
    print("COMPUTER CHOSE: ", computer_input)

    print("BOX 1 IS ", box1['state'])
box1 = Button(root, text="", padx=x, pady=y, command= lambda: turn(1, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box1.grid(row=1, column=0)
box2 = Button(root, text="", padx=x, pady=y, command=lambda: turn(2, box1, box2, box3, box4, box5,
box6,
box7, box8, box9))
box2.grid(row=1, column=1)
box3 = Button(root, text="", padx=x, pady=y, command=lambda: turn(3, box1, box2, box3, box4, box5,
box6,
box7, box8, box9))
box3.grid(row=1, column=2)
box4 = Button(root, text="", padx=x, pady=y, command=lambda: turn(4, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box4.grid(row=2, column=0)
box5 = Button(root, text="", padx=x, pady=y, command=lambda: turn(5, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box5.grid(row=2, column=1)
box6 = Button(root, text="", padx=x, pady=y, command=lambda: turn(6, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box6.grid(row=2, column=2)
box7 = Button(root, text="", padx=x, pady=y, command=lambda: turn(7, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box7.grid(row=3, column=0)
box8 = Button(root, text="", padx=x, pady=y, command=lambda: turn(8, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box8.grid(row=3, column=1)
box9 = Button(root, text="", padx=x, pady=y, command=lambda: turn(9, box1, box2, box3, box4, box5,
box6, box7, box8, box9))
box9.grid(row=3, column=2)
mainloop()

A: This code is a little complex. this is the cause of your issue:
    computer_input = random.randint(1, 9)

    computerList.insert(count, computer_input)

    for butts in playerList:
        if (computer_input == butts):
            while (computer_input==butts):
                computer_input = random.randint(1, 9)
                computerList.pop(count)
                computerList.insert(count, Button)

    for cuts in computerList:
        if (computer_input == cuts):
            while (computer_input==cuts):
                computer_input = random.randint(1, 9)
                computerList.pop(count)
                computerList.insert(count, Button)

    count += 1

I know what you want, but the direct way is to use set.
Simplify this logic, this will generate a number that didn't belong to player and computer previous selection:
    if len(computerList) != 4: # computer could only take less than four steps
        computer_input = random.choice(list(set(range(1, 10))-set(playerList)-set(computerList))) # use set to calculate the result

        computerList.append(computer_input)


text:
Q: Query into list activity with rawquery using multiple tables? Basicly I have two tables in my database brought together with a rawQuery and a ListActivity that is supposed to pull info from both tables and show it inside of the ListActivity. I don't get a force close or anything the problem is the information does not show up.
MY RAWQUERY
public Cursor fetchName() {
    return ourdb.rawQuery("SELECT wwJobTable._id, wwJobTable.JobName, wwLatLonTable.JobLatitude FROM wwJobTable, wwLatLonTable WHERE wwLatLonTable.JobLatitude=wwJobTable.JobCode", null);
}

HOW I AM VIEWING THE TABLE INFORMATION
private void fillData() {
     // Get all of the rows from the database and create the item list

    mTimeNotesCursor = mDbHelper.fetchName();
    mTimeNotesCursor.moveToFirst();
    startManagingCursor(mTimeNotesCursor);

    // Create an array to specify the fields we want to display in the list (only TITLE)
    String[] from = new String[]{WWDatabase.KEY_JOBNAME,
            WWDatabase.KEY_LATITUDE};

    // and an array of the fields we want to bind those fields to (in this case just text1)
    int[] to = new int[]{R.id.textView1, R.id.textView2};

    // Now create a simple cursor adapter and set it to display
    SimpleCursorAdapter notes =
        new SimpleCursorAdapter(this, R.layout.time_text_row, mTimeNotesCursor, from, to);

    setListAdapter(notes);
}

What could I possibly be doing wrong?