text:
Q: check if value exists in multidimensional array and find index I have an multidimensional array like this:
$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"],
  "downloads2" => ["downloadnaam" => "eyetyy"],
];

I need to check if the value eyetyy exists in this array under the key downloadnaam
Then I need to find the index of this value and remove it from the array.
The expected result:
$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"]
];

I tried this:
$index = array_search($download->name, array_column($downloadArray, 'downloadnaam'));
if ($index !== null)
{
   unset($downloadArray[$index]);
   die("found index: " . $index);
}

$download->name contains 'eyetyy'
$downloadArray is my array
But it always dies and doesn't show any index on screen.
Can anyone help me?

A: Try in this way:
$downloadArray = [
    "downloads1" => ["downloadnaam" => "fdgssgsfg"],
    "downloads2" => ["downloadnaam" => "eyetyy"],
];

$filter = "eyetyy";

// Search for index
$index = array_search($filter, array_column($downloadArray, "downloadnaam"));

if ($index !== false) {
    // Delete
    array_splice($downloadArray, $index, 1);
}

print_r($downloadArray);
die();

Output:
Array
(
    [downloads1]    Array
        (
            [downloadnaam]    fdgssgsfg
        )

)

A: I got it working using this code
$downloadArray = array_filter($downloadArray, function ($item) use ($download) {
    return $item['downloadnaam'] != $download->name;
});

This way I don't need to find the index first.
Credits to @Cositanto

A: you can try this :
$downloadArray = [
  "downloads1" => ["downloadnaam" => "fdgssgsfg"],
  "downloads2" => ["downloadnaam" => "eyetyy"],
];

foreach ($downloadArray as $subKey => $subArray) {
            if (\in_array($subArray['downloadnaam'], ['eyetyy'], true)) {
              unset($downloadArray[$subKey]);
            }
        }

var_dump($downloadArray);

Regards,


text:
Q: Binary addition which disapproves carrying I'm currently working with binary addition which returns False if there is carrying. My current code is :
def binaryadd(one, other):
    str_1, str_2 = str(one), str(other)
    for a,b in zip(str_1[::-1], str_2[::-1]):
        if a == b == '1':
            return False
    return int(bin(rev_bin(one) + rev_bin(other))[2:])

so 10111 + 1000 would return 11111, 10110 + 1011 would return False. I think there would be more efficient codes ;such as to check overflows in addition, but I'm wondering which code could do it. Is there any better way to do it?

A: There is carry from the moment there is a "column" for which both operands have a 1, since in that case we generate a carry. A carry can also propagate, but only if there was already a carry generated.
We can check this with a bitwise and (&). In case there is no carry, we can just is a bitwise or (|):
def binaryadd(one, other):
    if one & other:
        return False
    return one | other
or in a one-liner:
def binaryadd(one, other):
    return not bool(one & other) and one | other

redpajama_set_name: RedPajamaStackExchange


text:
Q: R - lm p-Value loop I have a small problem with my R code. I think it is pretty easy to solve but I have just very little experience with R.
I have a linear Model and after using the drop1 functions I have p-values (see code below). I have done this for my first term A1.
So I want to do the same for A2 A3 and so on and would like to store all p-values in one file. I need to extract sie p-values and use some kind of loop. What kind of function do I need? How do I extract the p-values?
mod1<-lm(A1~B+C, data=ipo)
drop1(mod1, test="F")

dput(head(ipo, 20))
structure(list(C = c(461.875, 441.85, 2133.025, 2213.704167,
1533.120833, 1423.529167, 1011.6875, 985.1, 221.2708333, 200.1291667,
336.875, 310.6875, 228.7583333, 220.4875, 452.7416667, 435.5416667,
242.0041667, 232.4833333, 411.4458333, 412.5875), A1 = c(32925L,
30797L, 162617L, 159828L, 110595L, 112922L, 78285L, 73708L, 14542L,
14271L, 24484L, 23792L, 18269L, 15513L, 34383L, 32109L, 16531L,
17279L, 30179L, 29919L), A2 = c(32925L, 30797L, 162617L, 159828L,
110595L, 112922L, 78285L, 73708L, 14542L, 14271L, 24484L, 23792L,
18269L, 15513L, 34383L, 32109L, 16531L, 17279L, 30179L, 29919L
), B = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("A", "B", "C",
"D", "E", "F", "G", "H"), class = "factor")), .Names = c("C",
"A1", "A2", "B"), row.names = c(NA, 20L), class = "data.frame")

A: You can try a tidyverse
library(tidyverse)
df %>%
  as_tibble() %>%
  gather(type, EP, -B, -C) %>%
  nest(-type) %>%
  mutate(lm=map(data, ~lm(EP ~ B + C,data = .x))) %>%
  mutate(drop=map(lm, ~drop1(.,test = "F") %>% broom::tidy(.))) %>%
  unnest(drop, .drop = T) %>%
  filter(!is.na(df))
# A tibble: 4 x 8
  type  term     df        sumsq          rss   AIC statistic  p.value
  <chr> <chr> <dbl>        <dbl>        <dbl> <dbl>     <dbl>    <dbl>
1 A1    B         2      836829.   124151602.  317.    0.0543 9.47e- 1
2 A1    C         1 18532654282. 18655969056.  419. 2405.     7.18e-19
3 A2    B         2      836829.   124151602.  317.    0.0543 9.47e- 1
4 A2    C         1 18532654282. 18655969056.  419. 2405.     7.18e-19

A: This solution uses package reshape2, function melt to reshape the data from wide to long format. The rest is base R only.
long <- reshape2::melt(ipo, id.vars = c("B", "C"))

sp <- split(long, long$variable)
res <- lapply(sp, function(DF){
  fit <- lm(value ~ B + C, data = DF)
  d <- drop1(fit)[-1, ]
  attr(d, "heading") <- NULL
  d
})

do.call(rbind, res)
#     Df  Sum of Sq        RSS    AIC
#A1.B  2 8.3683e+05 1.2415e+08 316.83
#A1.C  1 1.8533e+10 1.8656e+10 419.07
#A2.B  2 8.3683e+05 1.2415e+08 316.83
#A2.C  1 1.8533e+10 1.8656e+10 419.07

A: Here is a base R solution that just extracts the p-values. This should get you started--let me know if you are unable to change the output how you would like it. Good luck!!
# Get DV names
dvs <- names(ipo)[2:3]

# Create formula objects
formula_text <- paste0(dvs, " ~ B + C")
formulas <- lapply(formula_text, formula)

# Run models with drop1
models <- lapply(formulas, function(x){
  drop1(lm(x, data = ipo), test = "F")
})

# Extract p-values
model_pvals <- lapply(models, function(x) x[["Pr(>F)"]])

# Name and turn list into dataframe
names(model_pvals) <- formula_text

do.call(rbind, model_pvals)
           [,1]      [,2]         [,3]
A1 ~ B + C   NA 0.9473321 7.177227e-19
A2 ~ B + C   NA 0.9473321 7.177227e-19


text:
Q: Why enable the interrupt so early on threadx scheduler on M4 port? On threadx M4 port of pendsv interrupt implementation, which do the actual context switch of the multithread support of threadx, it shows all the  during the procedure, the interrupt all opened without disabled like other rtos, like ucos, rtthread, etc, so is this cause somethings that unpredictable at running time ?
like below code, the "cpsie i" was executed before the next ready to run thread restored
the line 202 eanbled the interrupt, but the actual context swithc has not finished yet, this is not like ucos does on m4 port, why is this safe? thank you!
**202     CPSIE   i**                                       @ Enable interrupts
203 @
204 @    /* Increment the thread run count.  */
205 @
206 __tx_ts_restore:
207     LDR     r7, [r1, #4]                            @ Pickup the current thread run count
208     LDR     r4, =_tx_timer_time_slice               @ Build address of time-slice variable
209     LDR     r5, [r1, #24]                           @ Pickup thread's current time-slice
210     ADD     r7, r7, #1                              @ Increment the thread run count
211     STR     r7, [r1, #4]                            @ Store the new run count
212 @
213 @    /* Setup global time-slice with thread's current time-slice.  */
214 @
215     STR     r5, [r4]                                @ Setup global time-slice
216
217 #ifdef TX_ENABLE_EXECUTION_CHANGE_NOTIFY
218 @
219 @    /* Call the thread entry function to indicate the thread is executing.  */
220 @
221     PUSH    {r0, r1}                                @ Save r0/r1
222     BL      _tx_execution_thread_enter              @ Call the thread execution enter function
223     POP     {r0, r1}                                @ Recover r3
224 #endif
225 @
226 @    /* Restore the thread context and PSP.  */
227 @
228     LDR     r12, [r1, #8]                           @ Pickup thread's stack pointer
229     LDMIA   r12!, {LR}                              @ Pickup LR
230 #ifdef TX_ENABLE_FPU_SUPPORT
231     TST     LR, #0x10                               @ Determine if the VFP extended frame is present
232     BNE     _skip_vfp_restore                       @ If not, skip VFP restore
233     VLDMIA  r12!, {s16-s31}                         @ Yes, restore additional VFP registers
234 _skip_vfp_restore:
235 #endif
236     LDMIA   r12!, {r4-r11}                          @ Recover thread's registers
237     MSR     PSP, r12                                @ Setup the thread's stack pointer
238 @
239 @    /* Return to thread.  */
240 @
241     BX      lr                                      @ Return to thread!

A: ThreadX is designed to run as fast as possible and minimize critical sections. Enabling  interrupt before restoring context is safe.
More details:
The scheduler is running in the PendSV interrupt, only an interrupt with higher priority than the PendSV can preempt the scheduler. The PendSV cannot preempt itself. ThreadX does not call the scheduler directly(except the first time). So, there is no re-entrancy for the scheduler. The context restoring process can be interrupted by a higher priority interrupt, the hardware will take care of interrupt nesting and saving/restoring caller saved registers etc. When the high priority interrupt is returned, the context restoring process continues as if nothing happened. If a high priority interrupt makes another higher priority thread ready, ThreadX will record the new thread as next thread to execute, but it will not call the scheduler directly. Instead, it sets the PendSV interrupt to pending state. Another context switch happens after the current context restoring process is finished.
As other interrupts do not affect the process of restoring context, it is safe to enable interrupt during context restore process.
By enabling interrupt earlier, other interrupts can be served with less delay. It is better to have less time in interrupt disabled state.

A: The short answer is that it's safe because beyond that point the system can handle an interrupt without leaving its critical data structures in an inconsistent state.
More specifically, after that point ThreadX's internal data structures are in a consistent state such that an ISR can invoke permitted ThreadX services safely - whereas before that point they are not, and so ISRs must be prevented from running.
Note that the M4's exception system - especially the SVCall, PendSV and interrupt exceptions and their relative priorities - facilitates implementation of a preemptive multitasking system without requiring explicit disabling and enabling of interrupts at all.


text:
Q: My PadRight() isn't working - Visual Basic I am trying to retrieve my record from the database Microsoft SQL and write it into a .txt file. My code were working properly but PadRight() are not.
My question is : Why does my PadRight() isn't working?
*Even if I put the PadRight() in other column name it is still not working.
Output : If i put row("ProcessDate".PadRight(9)) it should only show the 6character value not the whole value.
For example: if the value of a ProcessDate from the database Microsoft SQL is
11/8/2016 31342
The OUTPUT SHOULD BE : 11/8/2016
My Code:
 For Each row As DataRow In table.Rows
    swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
        row("ProcessDate".PadRight(6)),
        row("SubscriberAccountNumber"),
        row("PayorName"),
        row("ParNumber"),
        row("MemberType"),
        row("ApplicablePeriodStart"),
        row("ApplicablePeriodEnd"),
        row("TransactionAmount"),
        row("PaymentType"),
        row("CheckNo")))
    count += 1
Next

A: The PadRight method work aligning and adding spaces (by default) to the string.
If the total width is less then the string length it will return a reference to the original string.
So, it will not short your string.
I sugest you take a look at Substring method.
As mentioned by ChrisF in the comments, the Substring solution will solve the problem partially only.
If, for sure, the row("ProcessDate") will always give you a valid date, you can just change your format string for "{0:dd/MM/yyyy}{1}{2}{3}{4}{5}{6}{7}{8}{9}".
If it can be a Nothing, there are many solutions you can use to solve this problem, I will post one.
For Each row As DataRow In table.Rows
    Dim dt As DateTime
    Dim finalValue As String = If(DateTime.TryParse(row("ProcessDate"), dt), dt.ToString("dd/MM/yyyy"), "Default value")

    swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}",
        finalValue,
        row("SubscriberAccountNumber"),
        row("PayorName"),
        row("ParNumber"),
        row("MemberType"),
        row("ApplicablePeriodStart"),
        row("ApplicablePeriodEnd"),
        row("TransactionAmount"),
        row("PaymentType"),
        row("CheckNo")))
    count += 1
Next

*

*This solution will take care if the database returns a Nothing in the date row.

*Also remember to change "dd/MM/yyyy" for the format string that fits your needs.

*And the "Default value" for a default value :), String.Empty maybe.

A: For Each row As DataRow In table.Rows
            Dim dt As DateTime
            Dim finalValue As String = If(DateTime.TryParse(row("ProcessDate"), dt), dt.ToString("dd/MM/yyyy"), "Default value")
            Dim SubscriberNumber As String = row("SubscriberAccountNumber")
            Dim PayorName As String = row("PayorName")
            Dim ParNumber As String = row("ParNumber")
            Dim MemberType As String = row("MemberType")
            Dim Start As String = row("ApplicablePeriodStart")
            Dim Ends As String = row("ApplicablePeriodEnd")
            Dim Amount As String = Convert.ToDouble(row("TransactionAmount"))
            Dim PaymentType As String = row("PaymentType")
            Dim CheckNo As String = row("CheckNo")
            swMonetary.WriteLine(String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", finalValue.PadRight(15), SubscriberNumber.PadRight(20), PayorName.PadRight(30), ParNumber.PadRight(20), MemberType.PadRight(20), Start.PadRight(6), Ends.PadRight(6), Amount.PadRight(15), PaymentType.PadRight(10), CheckNo.PadRight(25)))
            count += 1
        Next

I found another solution. =)


text:
Q: Remove 27 characters from the front of the variable used for random I have the following code:

            <?php
            $sql = "SELECT DISTINCT url,display FROM `image_url` ORDER BY RAND() LIMIT 100";
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
                echo '
';
                foreach ($result as $value) {
                    if($value['display'] != 0){
                        echo'
'.$value['url'].'
';
                    }
                }
                echo '
';
            }
            ?>

I am trying to remove the first 27 characters from the value that is used for #search (link) but can't seem to figure it out.  Anyone?

A: Rather than trying to split the href eg: ...url.split('?url=')[1]...or use slice as described in comments - why don't you simply have the desired url listed as a data attribute. Then on clicking the link - get the data-url value and you will have the sdesired content with no messy manipulations.
Note I have just dodgied up some links with data-urls and its not in PHP - but it should give you the idea.

$('#links-list li').click(function(e){
  e.preventDefault();
  var url = $(this).find('a').attr('data-url');
  console.log(url); //gives the value of the data-url attribute - eg: "test1"
})

Test 1

Test 2

Test 3


text:
Q: Listing multiple compound words How do I list multiple things that are compound words?
In my own language I'm used to writing these lists like this:
"I kicked foot-, basket-, and volleyball"
The sentence is supposed to mean that I kicked all types of balls (football, basketball and volleyball). However, it does not seem correct to me. Should I write them as whole words, with or without hyphen, or how?

A: Basketball, football and volleyball fall under the category of closed compound words. These are combinations of two words that are not separated by a space or a hyphen. For more information on the types of compound words, check this out.
So your sentence should essentially be

I kicked a football, a basketball and a volleyball.

Suspended hyphenation(the case in a phrase like pre- and post-war implying pre-war and post-war) comes into picture only while dealing with hyphenated words. This article will guide you through it.
Hope that helped!

A: It only makes sense when the word has significance in isolation. Foot, volley, basket may not connect to your audience well. Either find a word that can group them. ( don't know if it exists in this case) For example - board games.


text:
Q: Does the Watson iOS SDK allow for access to the customization STT model The WatsonSpeech STT api (recognizeMicrophone method) takes an JSON object with key "customization_id" which allows the STT to use custom terms the user might say.
I don't see this ability in the Watson iOS SDK, I mean there is no customization_id parameter in the API.  Is there some other way to use the customized STT with the Watson iOS SDK?
Thanks.

A: We added support for using a custom Speech to Text model with this commit last week. We'll be publishing a release soon to make those changes more easily accessible through Carthage.


text:
Q: array_push won't give an array, prints out integer value I'm doing a very simple php program with array_push, but it isn't working according to the documentation. Every time i try to print the value of the final array, it gives me an integer. Could someone please help me with this?
Here's my code:
<?php
    $preArray = array('1','2','3','4','5','6','7','8');
    $val = 10;
    $array = array_push($preArray, $val);

    print_r($array);
?>

This is what it outputs:
9

Thanks in advance for the help.

A: array_push() returns the new number of elements in the array. So if you're not interested in the number of elements in the array then just use:
array_push($preArray, $val);

The variable $preArray will contain the value pushed into it.
print_r($preArray);


text:
Q: Trying to concatenate across records I'm having a bit of a problem that I just can't seem to get my head round.  I've got a table that I'm trying to extract some data from.  Below is an example of the data.
Id  DevId     Route
1   1         1
2   1         2
3   1         3
4   1         4
5   2         1
6   2         2

What I want the result to look like would be:
DevId     Route
1         1234
2         12

Don't know if I've been looking at it for too long or something, but I just can't work out how to do it.
Any help or suggestions would be greatly appreciated.
Thanks
Alex

A: Create table ##tmp (id int, name int)
insert into ##tmp values(1,1)
insert into ##tmp values(1,2)
insert into ##tmp values(1,3)
insert into ##tmp values(2,1)
insert into ##tmp values(2,2)
Select   id, (Select cast (name as varchar(4))
            from    ##tmp t2
            where   t1.id = t2.id
            for xml path('')
            )
from ##tmp t1
group by id
drop table  ##tmp


text:
Q: No results when searching with special characters in custom metadata property We have an issue with SharePoint 2010 Search. Currently, we have a property in Active Directory, for each user, that specify their initials. We have a scheduled task that runs every hour to sync these Active Directory properties with our custom user profile property for "Initials". We have created a metadata property in SharePoint Search called "Initials" that maps to "People:Initials(Text)".
Now, we're able to search for initials and get results for the user who have that initial. It works perfectly, except that it doesn't like special characters. In other words, if your initials start with Æ, Ø or Å, either no results get shown or results for "O" is shown when searched for "Ø", and "A" is shown when searched for "Å".
Have anyone ever seen an issue like this and/or know how I can solve this issue?
If you need any more details to answer this question, leave a comment.


text:
Q: Evaluate if result of DOMXpath->query returns match How can I evaluate if DOMTXpath->query actually returns data. Right now I am doing ($xml is a DOMXpath object):
foreach($xml->query($xpath) as $node)
{
  echo $node->textContent;
}

But if I my $xpath doesn't result in a node it just doesn't output any data. I tried something like:
if ($xml->query($xpath))
{
echo "found";
}else{
echo "not found";
}

but that doesn't seem to work. How can I test if my query is actually returning a matching node (actually an attribute in this case)?

A: Check the length parameter on the return of the query() function. xpath->query() returns a DOMNodeList.
$nodeList = $xpath->query();
if ($nodeList->length > 0) {
    echo 'Yay!';
} else {
    echo 'No!';
}


text:
Q: Translating an EER diagram supertype into a database schema How would you go about turning a supertype with two subtypes into a database schema? If I have the supertype person with two subtypes, student and staff, how would this translate into a database schema? (They would all have an ID, name, and email address).

A: I would make a table called person because if you would make a table called stundent and staff what would you do if a student is a staff at the same time?
then your database would become redundant. so just make a table called person and then just assign the students to the classes and the staff to there department.


text:
Q: Load a WPF application Assembly from another WPF app, get error: Cannot create more than one System.Windows.Application instance in the same AppDomain The Scenario:
LUNCHER.exe:   a WPF Application >> Build 32bit, .Net 4.5.1, location= D:\
LOADED.exe:    another WPF Application >> Build 32bit, .Net 4.5.1, location= D:\
I'm owner of both assembly (both application and thair sources)
Now, i want load the LOADED.exe [and its resources such as images dlls and...) as a Byte array to the memory and execute it, then remove LOADED.exe and its resources from hard disk.
In the first step i'm trying to just load the LOADED.exe file to memory and execute it (so i used a simple EXE without any resource in this step).
A)
Ok, i found this way for WinForm programes here:
var filePath = @"D:\LOADED.EXE";

if (File.Exists(filePath))
{
    try
    {

        // prepare to load the application into memory (using Assembly.Load)

        // read the bytes from the application exe file
        var fs = new FileStream(filePath, FileMode.Open);
        var br = new BinaryReader(fs);
        byte[] bin = br.ReadBytes(Convert.ToInt32(fs.Length));
        fs.Close();
        br.Close();

        // load the bytes into Assembly
        var asm = Assembly.Load(bin);
        // search for the Entry Point
        var method = asm.EntryPoint;
        if (method != null)
        {
            // create an istance of the Startup form Main method
            object o = asm.CreateInstance(method.Name);

            // invoke the application starting point
            Application.Current.ShutdownMode = System.Windows.ShutdownMode.OnExplicitShutdown;
            method.Invoke(o, null);
        }
        else
        {
            //show message: Impossible to launch the application
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message + "\n\r\n\r" + ex.InnerException + "\n\r\n\r" + "\n\r\n\r" + ex.Source);
        // exception throws .. something to do?
    }
}

I tried it inside LUNCHER.exe under a button then RUN... The result of handled exception:

Cannot create more than one System.Windows.Application instance in the same AppDomain.

OK!

B)
Then, i searched for a solution and some body has been said you must execute it in a new [different] AppDomain.
For example here is an answer: Dynamically Loaded Assembly - Settings & Communication
I tried it by the following codes under another button in the LUNCHER.exe:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
    try
    {
        var filePath = string.Format("{0}{1}", Utility.ExePath, PART_PATH);
        AppDomain newappdomain = getAppDomainForAssembly(filePath, "LOADED.exe.domain");
        object loadedexe_object = getInstanceFromAppDomain(ref newappdomain, filePath);

        //If you know the method name to call...
        executeMethod(loadedexe_object.GetType(), "methodname", ref loadedexe_object, null);

        //or get entry point...
        executeMethod(loadedexe_object.GetType(),
            _asm_resolve(filePath).EntryPoint.Name, ref loadedexe_object, null);
    }
    catch (Exception ex)
    {
        var type = "";

        if (ex is ArgumentNullException)
        {
            type = "ArgumentNullException";
        }
        else if (ex is NotSupportedException)
        {
            type = "NotSupportedException";
        }
        else if (ex is AppDomainUnloadedException)
        {
            type = "AppDomainUnloadedException";
        }
        else if (ex is TypeLoadException)
        {
            type = "TypeLoadException";
        }
        else if (ex is MissingMethodException)
        {
            type = "MissingMethodException";
        }
        else if (ex is MethodAccessException)
        {
            type = "MethodAccessException";
        }
        else if (ex is BadImageFormatException)
        {
            type = "BadImageFormatException";
        }
        else if (ex is FileLoadException)
        {
            type = "FileLoadException";
        }

        MessageBox.Show(type + "\n\r\n\r" + ex.Message + "\n\r\n\r" + ex.InnerException + "\n\r\n\r" + ex.Source);
    }
}

private AppDomain getAppDomainForAssembly(string assemblypath, string appdomainname)
{
    //this._assembly_file = AssemblyFile;

    string _assembly_file_name = System.IO.Path.GetFileName(assemblypath);
    string _rootpath = System.IO.Path.GetDirectoryName(assemblypath);

    //this._assembly_class_name = AssemblyClassNameToInstance;
    AppDomainSetup _app_domain_info = new AppDomainSetup();
    _app_domain_info.ApplicationBase = _rootpath;
    _app_domain_info.PrivateBinPath = _rootpath;
    _app_domain_info.PrivateBinPathProbe = _rootpath;
    _app_domain_info.ConfigurationFile = _rootpath + @"LOADED.exe.config";  //Here put the path to the correct .assembly .config file

    AppDomain _app_domain = AppDomain.CreateDomain(appdomainname, null, _app_domain_info);

    return _app_domain;
}

protected System.Reflection.Assembly _asm_resolve(string assemblyFile)
{
    return System.Reflection.Assembly.LoadFrom(assemblyFile);
}

private object getInstanceFromAppDomain(ref AppDomain appDomain,
    string assemblyPath, string className = null)
{
    if (string.IsNullOrEmpty(className))
    {
        System.Reflection.Assembly assembly = _asm_resolve(assemblyPath);
        System.Reflection.MethodInfo method = assembly.EntryPoint;

        // Now my ERROR is in this line>>
        return appDomain.CreateInstanceFromAndUnwrap(assemblyPath, method.Name);
    }
    else
    {
        return appDomain.CreateInstanceFromAndUnwrap(assemblyPath, className);
    }
}

Now my error is in this line:

OK!

C)
I searched again and found this one (Dynamically loaded Assembly not loading in new AppDomain):
// Provides a means of invoking an assembly in an isolated appdomain
public static class IsolatedInvoker
{
    // main Invoke method
    public static void Invoke(string assemblyFile, string typeName, string methodName, object[] parameters)
    {
        // resolve path
        assemblyFile = Path.Combine(Environment.CurrentDirectory, assemblyFile);
        Debug.Assert(assemblyFile != null);

        // get base path
        var appBasePath = Path.GetDirectoryName(assemblyFile);
        Debug.Assert(appBasePath != null);

        // change current directory
        var oldDirectory = Environment.CurrentDirectory;
        Environment.CurrentDirectory = appBasePath;
        try
        {
            // create new app domain
            var domain = AppDomain.CreateDomain(Guid.NewGuid().ToString(), null, appBasePath, null, false);
            try
            {
                // create instance
                var invoker = (InvokerHelper) domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location, typeof(InvokerHelper).FullName);

                // invoke method
                var result = invoker.InvokeHelper(assemblyFile, typeName, methodName, parameters);

                // process result
                Debug.WriteLine(result);
            }
            finally
            {
                // unload app domain
                AppDomain.Unload(domain);
            }
        }
        finally
        {
            // revert current directory
            Environment.CurrentDirectory = oldDirectory;
        }
    }

    // This helper class is instantiated in an isolated app domain
    private class InvokerHelper : MarshalByRefObject
    {
        // This helper function is executed in an isolated app domain
        public object InvokeHelper(string assemblyFile, string typeName, string methodName, object[] parameters)
        {
            // create an instance of the target object
            var handle = Activator.CreateInstanceFrom(assemblyFile, typeName);

            // get the instance of the target object
            var instance = handle.Unwrap();

            // get the type of the target object
            var type = instance.GetType();

            // invoke the method
            var result = type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, instance, parameters);

            // success
            return result;
        }
    }
}

Then i called it by the following codes under another button in the LUNCHER.exe:
private void Button_Click_2(object sender, RoutedEventArgs e)
{
    var filePath = string.Format("{0}{1}", Utility.ExePath, PART_PATH);
    IsolatedInvoker.Invoke(filePath, "Main", "Main", new object[] {});
}

But i get same error like previous way **B**:

An unhandled exception of type 'System.TypeLoadException' occurred in
  Luncher.exe
Additional information: Could not load type 'Main' from assembly
  Loaded, Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'.

D)
Also i tested this way under another button in the LUNCHER.EXE:
private void Button_Click_3(object sender, RoutedEventArgs e)
{
    var filePath = @"D:\LOADED.exe";
    var dll = File.ReadAllBytes(filePath);
    var assembly = Assembly.Load(dll);

    var app = typeof (Application);

    var field = app.GetField("_resourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
    field.SetValue(null, assembly);

    //fix urihelper
    var helper = typeof (BaseUriHelper);
    var property = helper.GetProperty("ResourceAssembly", BindingFlags.NonPublic | BindingFlags.Static);
    property.SetValue(null, assembly, null);

    //---- Now my ERROR is in this line >>
    assembly.EntryPoint.Invoke(null, new object[] {});
}

And error in last line of code in Run Time:

An unhandled exception of type
  'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
Additional information: Exception has been thrown by the target of an
  invocation.

Finally:
I'm confused!

*

*what is my mistake in all above methods?

*why all the ways end with an ERROR!!!

Please help me with simple descriptions and some codes because I'm beginner in this scenarios (loading assembly, create AppDomain and...) but i need to load a WPF application to the memory and show its window and then delete it's file from H.D.D while it is running in the memory.

A: *

*Create a shared assembly. This will be loaded into both AppDomains ("Launcher" Domain, "Loaded" Domain) and serve as an entry point of our "Loaded" AppDomain:
Add a new project > Class library > Name: ChildDomainLoader
Add the following references to the new project: System.Xaml, WindowsBase, PresentationFramework
Add a project reference for ChildDomainLoader in your Launcher project. The Loaded project doesn't have to be modified.

*Add some code to the shared assembly. We need a MarshalByRefObject that can be called cross-domain and loads our child assembly. Let's call it Runner:
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace ChildDomainLoader
{
    public class Runner : MarshalByRefObject
    {
        public static AppDomain RunInOtherDomain(string assemblyPath)
        {
            var ownType = typeof (Runner);
            string ownAssemblyName = ownType.Assembly.FullName;

            // Create a new AppDomain and load our assembly in there.
            var childDomain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
            childDomain.Load(ownAssemblyName);

            // Call Run() in other AppDomain.
            var runner = (Runner) childDomain.CreateInstanceAndUnwrap(ownAssemblyName, ownType.FullName);
            runner.Run(assemblyPath);

            return childDomain;
        }

        public void Run(string assemblyPath)
        {
            // We load the assembly as byte array.
            var otherAssemblyBytes = File.ReadAllBytes(assemblyPath);
            var assembly = AppDomain.CurrentDomain.Load(otherAssemblyBytes);

            AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
            {
                throw new NotImplementedException("Probably need to do some work here if you depend on other assemblies.");
            };

            // Set the assembly as ResourceAssembly, as WPF will be confused otherwise.
            Application.ResourceAssembly = assembly;

            // Search for the App class.
            var app = assembly
                .GetExportedTypes()
                .Single(t => typeof(Application).IsAssignableFrom(t));

            // Invoke its Main method.
            MethodInfo main = app.GetMethod("Main", BindingFlags.Static | BindingFlags.Public);
            main.Invoke(null, null);
        }
    }
}

*Use it. Call Runner.RunInOtherDomain from your Launcher application.
var assemblyPath = "path to your loaded.exe";
ChildDomainLoader.Runner.RunInOtherDomain(assemblyPath);
File.Delete(assemblyPath);


text:
Q: create a timer using python.i cant understand the logic used to build a timer that prints "ok" after every 2 seconds in python. #while_loop i cant understand the logic used to build a timer that prints "ok" after every 2 seconds in python. Also the body of the while loop . please explain
  import time print("start") start=time.time() while True: end = time.time() if (end-start)>=2: print("ok") start=time.time()

A: There is two methods of doing that:
FIRST:
import time
while True:
    time.sleep(2)
    print('ok')

SECOND:
import time
oldtime = time.time()
while True:
    if oldtime + 2 == time.time(): #time.time() means current time
        print('ok')
        oldtime = time.time()

If your program must not pause(need to do other things) use the SECOND method if not try the FIRST one it is easy.
If you have any questions just comment this post.


text:
Q: Stop words inconsistent with preprocessing in sklearn CountVectorizer I have been trying to use the Count Vectorizer from sklearn library, however i receive the warning that the list of spanish stop words i am using are not consistent with preprocessing.
Is it an encoding problem??
The stopwords.txt file has one word per row like:
a
el
los
...
custom_stop_words = []
with open( "stopwords.txt", "r" ,encoding='latin_1') as fin:
    for line in fin.readlines():
        custom_stop_words.append( line.strip() )
# note that we need to make it hashable
print("Stopword list has %d entries" % len(custom_stop_words) )

from sklearn.feature_extraction.text import CountVectorizer
# use a custom stopwords list, set the minimum term-document frequency to 20
vectorizer = CountVectorizer(stop_words = custom_stop_words, min_df = 2,strip_accents='unicode',encoding="latin-1")
A = vectorizer.fit_transform(df_final['visita'])
print( "Created %d X %d document-term matrix" % (A.shape[0], A.shape[1]) )


text:
Q: Почему виджет не виден в списке виджетов? Внутри <application> в манифесте
    <receiver android:name=".WidgetProvider" android:label="@string/app_name" android:icon="@drawable/widget">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
        </intent-filter>
        <meta-data android:name="android.appwidget.provider"
            android:resource="@xml/widget" />
    </receiver>

xml/widget.xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="schemas.android.com/apk/res/android"
    android:minWidth="25dp"
    android:minHeight="25dp"
    android:updatePeriodMillis="2400000"
    android:initialLayout="@layout/widget"
    android:previewImage="@drawable/widget"/>

layout/widget.xml
<?xml version="1.0" encoding="utf-8"?>
<dlp.recircle.MainView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
</dlp.recircle.MainView>

A: В файле xml/widget.xml поменяйте строку :
xmlns:android="schemas.android.com/apk/res/android"

на строку:
xmlns:android="http://schemas.android.com/apk/res/android"


text:
Q: Error reading body: System.Xml.XmlException: '���Z��m' contains invalid UTF8 bytes I am developing the one WCF service, In which I create the custom MessageFormatter using the IDispatchMessageFormatter.
Here somehow I editing the request message coming from the client before the deserialize it.
public void DeserializeRequest(Message message, object[] parameters)
{
    try
    {
        RequestMessage objRequestMessage = new RequestMessage(message);
        Message objNewMessage = objRequestMessage.RecreateMessage();
        this.objMessageFormatter.DeserializeRequest(objNewMessage, parameters);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

It working fine with the all clients, but for one of the client is does not work.
When the client send the request and DeserializeRequest method is called, in the argument of the DeserializeRequest there is the object of the Message class called message.
In Which the original request is not come, but it gives me the following message.

{... Error reading body: System.Xml.XmlException: '���Z��m' contains
  invalid UTF8 bytes. ...}

It gives the above message even before the my code is executed, even the the first line of the DeserializeRequest method is not executed.
I think it must be the mismatch of the encoding types used by the client and the server.
Service:
[ServiceContract(Namespace = "http://my-wcf.com/WepAPI")]
[XmlSerializerFormat]
public interface IWWRSPFWebAPIMFPService
{
    [OperationContract(Action = "http://my-wcf.com/WepAPI#SayHello")]
    [CMessageBehavior]
    HelloReponse SayHello(HelloRequest helloRequest);
}

app.config
<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.2"/>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>


text:
Q: Error en java de casteo Hola gente de stack tengo un problema y es el siguiente:
Quiero traer los datos de mi LISTA (JPanel) a unos JTextField, y lo estuve haciendo con el evento ListSelection, el problema es que solo sé traer los datos de tipo String y no los de tipo int, ni tampoco el tipo Date, intente hacerle un casteo pero ninguno de los que probé me dieron resultado, les dejo un ejemplo de como traigo el dato de tipo String y me funciona, pero el de tipo int y Date no me trae los datos por un error de casteo. Solamente me falta castear de forma correcta, y con algunos ejemplos de google ninguno me dio resultado, espero que se me entienda y me puedan ayudar.
private void listContratoValueChanged(javax.swing.event.ListSelectionEvent evt) {
  // ITEM ACTUAL SELECCIONADO
  if(!this.listContrato.isSelectionEmpty()) {
    // obtengo el item seleccionado
    Contrato contratos = (Contrato) this.listContrato.getSelectedValue();

    //ASIGNAR VALORES
    this.labelId.setText(contratos.getIdContrato().toString());
    this.txtLugar.setText(contratos.getLugar());
    this.txtFecha.getText();
    this.txtCantidad.getText();
    this.txtTotal.getText();
  }
}

Me retornan los datos de tipo String como el Lugar, solamente, me falta retornar la cantidad y la fecha que son de tipo Date, probé casteando, al final con .toString() pero no tuve resultados, saludos.

Probé con:
this.txtFecha.getText(contratos.getFecha().toString());
this.txtCantidad.getText(contratos.getCantidad().toString());

También probé:
 precio = Double.parseDouble(this.txtPrecio.getText());
 String p = String.valueOf(this.txtPrecio.getText());

Pero sigo sin poder traer mis datos de tipo int ni Date.
Saludos! espero respuestas!

A: Debes meterlo en una variable. puesto que no tengo tus clases te pongo mi ejemplo.
yo tengo mi clase paciente que tinee
private int edad
private String nombre
private int codigo paciente

. En el Jframe tengo unos textfiel donde aparece los nombres la edad etc.
Yo le hago un paseo normal y corrienote para crear el Paciente debo de setear lo datos de sus clase y lo hago asi
  private void bntAgregarActionPerformed(java.awt.event.ActionEvent evt) {
        Cita nuevaCita;
        String nombrePaciente = jNombre.getText();
        String especialidad = cmbEspecialidad.getSelectedItem().toString();
        String nombreMedico = cmbDoctor.getSelectedItem().toString();
        Date fechaD = (Date) jSFecha.getValue();
        int codPac = Integer.parseInt(cmbPaciente.getSelectedItem().toString());
        int edadNum = Integer.parseInt(jEdad.getText());
        Paciente nPaciente = new Paciente(codPac, nombrePaciente, edadNum);


text:
Q: How can I tell whether the softkeyboard is in extract mode or not? When in landscape orientation, I want to be able to tell whether the spoftkeyboard that pops up takes up the entire screen or not.
I understand this is device dependent, but how can I tell whether the current device uses a full screen keyboard in landscape mode or not?

A: Just found out that the InputMethodManager contains a function called isFullscreenMode(). I believe this is a good way to check...


text:
Q: Macro/UDF to extract multiple occurances of text URLs from cell I have about 1000 rows of data and each cell in column C is filled with the html of a blog post article. I need to extract any URL (text string) that starts with "https://" and end with ".jpg"
there are multiple occurrences of each of these URLs in each cell, and some cells have other URLs in them too (none are hyperlinked, it's all plain text)
I've tried a bunch of FIND, IF, MID etc... but it only works for one occurrence.
can anyone help with a macro? thanks!

A: Put the following formula in D1 (or any other column that suits you):
=IF(AND(LEFT(C1,8)="https://", RIGHT(C1,4)=".jpg"),C1,"")

And copy down.

A: I ended up just doing it in a much simpler way with a basic find and replace. at first I thought each URL would be too different, but the only differences were 2 folders, (paths) at the end of each url like: 2017/01/filename.jpg. So I just did a find and replace on the root url before that to the new url path, and then did a find and replace on each month folder, to remove it. it only went back to 2010 or so.
for the record just to unnecessarily defend myself the original question says "there are multiple occurrences of each of these in each cell which is why I was fairly certain I needed a macro but obviously there was a much simpler way, per usual!


text:
Q: How do I add naudio filters to sinewave? I have created a sinewave using Naudio's portamento oscillator.
I would like to experiment on adding filters to it to make the sound less mechanical and I realized that Naudio has filters such as BiQuadfilters and fadeinfadeout and the examples that I came across were showing how to use these filters to an mp3 audio.
How do I add these filters to my sinewave generated from the portamento oscillator?

A: Take a look at the equalization demo in the NAudio WPF demo source code for a basic idea of how to use BiQuadFilter


text:
Q: Getting Exception thrown for glViewport(0, 0, framebufferWidth, framebufferHight); #include "list.h"

int main()
{
    //INIT GLFW
    glfwInit();

    //CREATE WINDOW

    const int WINDOW_WIDTH = 640;
    const int WINDOW_HEIGHT = 480;
    int framebufferWidth = 0;
    int framebufferHight = 0;

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

    glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

    glViewport(0, 0, framebufferWidth, framebufferHight);

    glfwMakeContextCurrent(window);//IMPORTIANT!!

    //INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
    glewExperimental = GL_TRUE;

    >//Error

    if (glewInit() != GLEW_OK)
    {
        std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
        glfwTerminate();
    }

    //MAIN LOOP
    while (glfwWindowShouldClose(window))
    {
        //UPDATE INPUT ---

        //UPDATE ---

        //DRAW ---
        //Clear

        //Draw

        //End Draw
    }

    //END OF PROGAM
    glfwTerminate();

    return 0;
}

glViewport(0, 0, framebufferWidth, framebufferHight); is giving me

Unhandled exception at >0x00007FF704D6E7D9 in OpenzGL4.exe: 0xC0000005: Access violation reading >location >0x0000000000000348.

when I run it.

A: For any OpenGL instruction is required a valid and current OpenGL Context. Hence glfwMakeContextCurrent hast to be invoked before any OpneGL instruction:
GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

glfwMakeContextCurrent(window); // <----- ADD

glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

glViewport(0, 0, framebufferWidth, framebufferHight);

glfwMakeContextCurrent(window); // <----- DELETE

A: In addition to what Rabbid76 already wrote in his answer, there is another problem in your code:

glViewport(0, 0, framebufferWidth, framebufferHight);

glfwMakeContextCurrent(window);//IMPORTIANT!!

//INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
glewExperimental = GL_TRUE;

>//Error

if (glewInit() != GLEW_OK) {
    std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
    glfwTerminate(); }

Since you use the GLEW OpenGL loader, every gl...() Function name is actually remapped as a preprocessor macro to a function pointer, and glewInit will query all those function pointers (and that needs an active OpenGL context, so it can't be done before the glfwMakeContextCurrent). So it is not enough to move the glViewport after the glfwMakeContextCurrent, you must also move it after glewInit.
And there is a second issue with this code: the glewExperimental =  GL_TRUE is an evil hack for a bug in GLEW 1.x with OpenGL core profiles, and it's use can't be discouraged enough. Just update to GLEW 2.x or another loader which is compatible with OpenGL core profile contexts.


text:
Q: Msbuild to confiture manageAppVersionAndBuildNumber flag as false Is there option to configure your build_app script with the following manageAppVersionAndBuildNumber when you're building it using msbuild option?
('msbuild', CONST['...'], "/p:Configuration=\"#{CONST['...']}\"", "/p:Platform=\"#{CONST['...']}\"")

this is what I exactly run on my Teamcity / Fastlane. I was looking for something similar to
build_app(scheme: "your_app_scheme",
          export_options:{
            manageAppVersionAndBuildNumber: false
          })

but obviously this exists in xCode, not in msbuild.

A: IMHO, with the following set of parameters, msbuild won't manage the app version and build number itself. It will set as you declared.
/p:SetVersion=True /p:VersionNumber=$VersionNumber /p:BuildNumber=$BuildNumber


text:
Q: Outlook: save existing search query as "Search Folder" In Outlook When I already have a search query that is displaying results on screen in the email list pane, how do I save this EXISTING search query as a "Search Folder".
i.e. Without starting again from "New Search Folder" menu item.
I'm expecting to find a button like "Save this EXISTING search query as a Search Folder".

A: Firstly, create the folder in your Outlook, then do a search query. Select one message in the result output, hold it and type Ctrl+A. Right-click and move them to the new created folder.


text:
Q: My 3n+1 solution in Java judged wrong/runtime error , Why? I just started with Programming Challenges and tryin to solve 3n+1 problem . My program gives RUNTIME ERROR in UVA judge and WRONG ANSWER in Programming challenges judge . But I dont find any error in the program .. All test cases give correct answers for me . Can anybody tell me what might be wrong
    1: import java.io.*;
    2: import java.util.*;
    3: class Main{
    4:     public static void main(String args[]) throws IOException{
    5:         BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
    6:         String s,ar[];
    7:         long aray[]=new long[50];
    8:         int n=0,maxcount=0,count;
    9:         long t,a,b,c=1,co=0;
    10:        while((s=br.readLine()).length()>0) {
    11:             ar=s.split(" ");
    12:             aray[n++]=Long.parseLong(ar[0]);
    13:             aray[n++]=Long.parseLong(ar[1]);
    14:         }
    15:
    16:         for(int j=0;j<n;) {
    17:              c=1;
    18:              maxcount=0;
    19:              a=aray[j++];
    20:              b=aray[j++];
    21:              co=b-a+1;
    22:              if(a>b){                //special case
    23:                   c=-1;
    24:                   co=a-b+1;
    25:              }
    26:              for(long i=a,k=0;k<co;i+=c,k++){
    27:                   t=i;
    28:                   count=1;
    29:                   while(t!=1){
    30:                        if(t%2==0) t=t/2;
    31:                        else t=(3*t)+1;
    32:                        count++;
    33:                   }
    34:              maxcount=(maxcount>count)?maxcount:count;
    35:         }
    36:         System.out.println(a+" "+b+" "+maxcount);
    36:         System.exit(0);
    38:     }
    39: }

A: You've got quite a few readability issues with your code.  I can't even see the errors in your algorithm because of its lack of readability.
Structurally, as others mentioned, it's not well split up.  You should at least have a getRanges() function to accept all user input and a getMaxCycleLen(i,j) method to calculate the cycle length for a particular cycle.
Style-wise, as others have mentioned, your variable names are not descriptive.  Variable names should almost never be 1 or 2 characters long (i, j, k excepted, of course).  They need to be both descriptive of what the variable is used for (counter, index, maxCycles, etc.) and long enough to search for in the code (how many times do you see "a" or "ar" in the middle of some other keyword/comment/variable?).
your aray variable would be more readable if it were an array of arrays (aray[50][2]).  The way you write it, it's very hard to keep track of what's going on.
line 7 declares aray to be 50 entries long.  This means your code will fail when more than 50 entries are provided. (this may be your runtime bug)
line 26: This loop is weird.  you i+=c in an apparent attempt to handle out of order operands.  Your loop constraints will be far more readable if you just reverse a and be (tmp=a;a=b;b=a;)
line 36: you do not need to call system.exit().  That happens for you, automatically, when main exits.
Once you make your code readable, maybe someone will be able to point to the bug(s)


text:
Q: Nodejs next function, why? I am developing apis with nodejs. I have seen there is a parameter passed in the function with req, res like this:
bookRouter.use('/:bookId', function(req,res,next){
        Book.findById(req.params.bookId, function(err,book){
            if(err)
                res.status(500).send(err);
            else if(book)
            {
                req.book = book;
                next();
            }
            else
            {
                res.status(404).send('no book found');
            }
        });
    });

I never used this function in my development and I want to know if i really need to use this?

A: From documentation:
You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there's no reason to proceed with the current route.
A single callback function can handle a route. For example:
app.get('/example/a', function (req, res) {
  res.send('Hello from A!');
});

More than one callback function can handle a route (make sure you specify the next object). For example:
app.get('/example/b', function (req, res, next) {
  console.log('the response will be sent by the next function ...');
  next();
}, function (req, res) {
  res.send('Hello from B!');
});

A: I'm not that strong in node.js but the aim is to call a function when the book with the given ID is found. The function to be called is passed in as next. There may be other middleware components involved, so calling next() makes sure that upon success of this part, the next middleware can process the request.

A: The next function will call the next middleware function in the stack. See https://expressjs.com/en/guide/using-middleware.html for more details.
Hope this helps.

A: You don't have to use next() because your action is the last action which processes request. Here's documentation fragment:

Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:

*

*Execute any code.

*Make changes to the request and the response objects.

*End the request-response cycle.

*Call the next middleware function in the stack.

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

A: Node is event based language with the callback. If your event triggered successfully and you want to execute the some function then it will be passed as an argument to this. But it does not create problem if you don't pass function or you don't use it.


text:
Q: Firebase Phone Authentication - Internalization of verification SMS text In firebase auth documentation it is mentioned that we can internationalize the authentication sms language with the following call. For instance to
FirebaseAuth.getInstance().setLanguageCode("fr");

should set the message language to french.
Actually on android I never got this to work sms are arriving on the template language set on firebase console
Any advice?

A: To change the language in the template for the following:

SMS verification
Password Reset
Email address Change

Do the following:

*

*Go to firebase console

*click on authentication

*Click on templates

Inside the templates you have this:

You can then change the language by clicking on the edit button next to Template language English.

A: Make sure you are using the Android version that supports client side localization. Also, are you using your own custom templates? If so, Firebase Auth does not localize custom email templates.


text:
Q: How to get Apollo gql codgen to work with frontend nextJS I am using nextJS,  I want my front end react queries with apollo to be typed out, but no configuration is working. I get an unknown error on my query when I use import {gql} from src/__generated__/gql and the following message when I hover over gql():
The query argument is unknown! Please regenerate the types
My question is do I need to do something different because I am using nextJS? I want to be able to use TypeScript with Apollo Client code gendocs so my gql queries will be typed
My entire pothos schema is in my pages/api/index.ts file (I do not yet know how to spread this code out into multiple files)
Example Query:
const CREATED_EVENT_QUERY = gql(`
    query EventById($id: mongoId!) {
        eventById(id: $id) {
            _id
            name
            description
            location{
              coordinates
            }
            date
            eventApplicants{
            name
            userId
            weight
          }
        link
        weights{
          weight
          spotsAvailable{
            name
            userId
          }
        }
        }
    }
            `);

// Apollo Query

    const { loading, error, data } = useQuery(CREATED_EVENT_QUERY, {
        variables: {
            id: params.id
        }
    });

I have tried the following configurations:
Apollos recommendation
Link Above
import { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
    schema: 'http://localhost:3000/api',
    documents: ['*.ts'],
    generates: {
        './src/__generated__/': {
            preset: 'client',
            plugins: [],
            presetConfig: {
                gqlTagName: 'gql',
            }
        }
    },
    ignoreNoDocuments: true,
};

export default config;

the guilds nextJS recomendation
import type { CodegenConfig } from '@graphql-codegen/cli'

const config: CodegenConfig = {
 // ...
 generates: {
 'path/to/file.ts': {
 plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
 config: {
 reactApolloVersion: 3
 }
 }
 }
}
export default config

combination of the two
import { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
    schema: 'http://localhost:3000/api',
    documents: ['*.ts'],
    generates: {
        'pages/api/index.ts': {
            plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'],
            config: {
                reactApolloVersion: 3
            }
        }
    },
    ignoreNoDocuments: true,
};

export default config;


text:
Q: Is it possible to mirror a private repository on gitlab.com using the SSH protocol? Gitlab.com has an option to mirror other repository's on their own site. (Project--> Project setting--> Mirror Repository)
But when I tried to do that using the ssh protocol, the authorization failed because the repository I wanted to clone didn't recognize the public key of Gitlab.com.
The page stated:

If your SSH repository is not publicly accessible, add the public SSH key of the GitLab server to the remote repository.

The thing is, I could not find an option to add a private key to Gitlab.com or download a public key from Gitlab.com.
Is this only possible if your own a GitLab server or did I overlook something?

A: Gitlab mirroring feature is implemented recently on Nov 2015 but unfortunately it is available only for Gitlab Enterprise Edition:

Repository Mirroring (EE only) If you want to maintain a mirror of a
  repository in a GitLab instance, you can now let GitLab handle the
  mirroring for you automatically in GitLab Enterprise Edition.

Check the features comparison  between Community and Enterprise Editions
Either you request EE or use gitlab-mirrors scripts:

The gitlab-mirrors project is designed to fill in a feature which is currently missing from GitLab: the ability to mirror remote repositories.
  gitlab-mirrors creates read only copies of remote repositories in
  gitlab. It provides a CLI management interface for managing the
  mirrored repositories (e.g. add, delete, update) so that an admin may
  regularly update all mirrors using crontab. It operates by interacting
  with the GitLab API using python-gitlab3. Also, check out this cool
  puppet module for installing and configuring gitlab-mirrors.

A: I'm not sure that this will work, but I reckon it's worth a try. To retrieve the public key of gitlab.com, I ran the following command:
nmap gitlab.com --script ssh-hostkey --script-args ssh_hostkey=all

The following 3 public keys can then be found in the output:
ssh-dss AAAAB3NzaC1kc3MAAACBAMPKInNPflcRle9F5Qt2j9aI0EZuWQzdXTbYvsl+ChaacqCOWRMiOmXHXqetFz6jD/6Fcqg20ZATxqSskQBaRn97O/mbH+GQk4d3zw9WAEURicE8rKJop3qGtdfFxLzrTuPAkKRDMmutT3hwZIOO8CFWOl1BiuUYTncJTeonrfAAAAFQCujauoy3Yy+ul72b/WsTECUPj9yQAAAIBIV2yyF7RZf7IYS8tsWcKP7Y5Bv9eFdbvbtsaxcFCHcmHIGoJQrIdPoueoOb5EUTYz0NgYKsKaZzDZkgFk28GsmLxKvhnPjaw0lJVSKRchEE5xVlamOlabiRMjQ7X/bAdejkBJe96AjZZL3UO4acpwfy3Tnnap0w6YCDeaxoyHpwAAAIAU+dyNaL3Hy15VIV32QwWMekvxeptUY/W03LNcgZZDoin87TE9xuQhM0qF3pi2i2a2ExuslgdttmYWvrbEz8eW+RFgvT5pKwWpalKWetHvtN3oYZP37ZIO1Y3Hd5A4YVcpYp1ccRayveLlCRwxb4HdGXT2OmYU+lmvimIR8zQ6A==

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCsj2bNKTBSpIYDEGk9KxsGh3mySTRgMtXL583qmBpzeQ+jqCMRgBqB98u3z++J1sKlXHWfM9dyhSevkMwSbhoR8XIq/U0tCNyokEi/ueaBMCvbcTHhO7FcwzY92WK4Yt0aGROY5qX2UKSeOvuP4D6TPqKF1onrSzH9bx9XUf2lEdWT/ia1NEKjunUqu1xOB/StKDHMoX4/OKyIzuS0q/T1zOATthvasJFoPrAjkohTyaDUz2LN5JoH839hViyEG82yB+MjcFV5MU3N1l1QL3cVUCh93xSaua1N85qivl+siMkPGbO5xR/En4iEY6K2XPASUEMaieWVNTRCtJ4S8H+9

_ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFSMqzJeV9rUzU4kWitGjeR4PWSa29SPqJ1fVkhtj3Hw9xjLVXVYrU9QlYWrOLXBpQ6KWjbjTDTdDkoohFzgbEY=

Adding these to your repository server might allow it to authenticate the connection properly.

A: According to this comment, the key is in /var/opt/gitlab/.ssh/id_rsa and /var/opt/gitlab/.ssh/id_rsa.pub by default. If the keys don't exist, you can create them manually with sudo -u git -H ssh-keygen and mashing the enter key through the prompts.
I just tried this on my gitlab-ee 8.7.2 installation and it appears to be working.


text:
Q: Sending mail via local IIS smtp server from ASP.NET core app silently fails UPDATE: This turned out to be simple operator error - I failed to read the log file properly, which did indicate successful delivery on the IIS level.
Turns out that mails to this particular test address were blocked silently for unknown reasons unrelated to dotnet or IIS, by Gmail. Very sorry for posting something with such a simple solution and thanks to those that replied with helpful advice.
ORIGINAL QUESTION:
I have a Windows server with IIS SMTP server installed.
I'm trying to send mails from my ASP.NET Core app with this code:
var client = new SmtpClient();
client.Host = "127.0.0.1";
client.Send(mailMessage);

The code doesn't throw an exception, there is nothing in Windows error logs, nothing is logged to SMTP logs. It just fails silently.
The result of the Send() method is just the message itself, no error message or anything else helpful.
I tried in IIS to configure the SMTP Server but doesn't help.
I also tried other options like UseDefaultCredentials and to have it make a file in the Drop folder - in that case it says "not supported."
This exact same code works perfectly fine from my ASP.NET Standard app on the same server.
Thanks in advance! :-)

A: This turned out to be simple operator error - I failed to read the log file which indicated successful delivery on the IIS level. The mails to this particular test address were blocked silently for unknown reasons by Gmail. Very sorry for posting something with such a simple solution and thanks to those that replied with helpful advice.


text:
Q: How to output a separate file per input record in mapper? I have a mapreduce job which consists of just mapper. I'd like this job to output a separate file (whose name is coming from the input record) per input record. How can I do that?

A: This is not how mapper interface is designed, but nothing stops you from opening a file inside the mapper code and writing something into that file.
You'll probably want to update some counters (using reporter.incrCounter()), so that Hadoop knows that your code is doing something, since you won't be calling output.collect().


text:
Q: possible socket.io memory leak Using socket.io 0.9.17 with a redis store, over time the memory usage grows from ~150mb at startup to beyond 1.0gb.
I took 2 heap snapshots using node-heapdump. One after app start and another a day later. And compared the results and it looks like the biggest offender is string objects.
Below are the screenshots of the comparison.

When I expand the string objects all I see is some trace and a uncaughtException.

The app doesn't crash and there are no exceptions when running the same code on dev environments. These strings are events that are passed to socket.io and distributed to the nodes via the redis store. The relevant code for this is below
var result = {
        posts: [postData],
        privileges: {
            'topics:reply': true
        },
        'reputation:disabled': parseInt(meta.config['reputation:disabled'], 10) === 1,
        'downvote:disabled': parseInt(meta.config['downvote:disabled'], 10) === 1,
    };

for(var i=0; i<uids.length; ++i) {
    if (parseInt(uids[i], 10) !== socket.uid) {
        websockets.in('uid_' + uids[i]).emit('event:new_post', result);
    }
}

A: Upgrading to socket.io 1.x got rid of the memory leak.


text:
Q: How to Sign-In to Google Across Multiple Activities When I sign in through Google Sign-In to ActivityA, I want ActivityB to sign in to the same account simultaneously and and have all the capabilities of ActivityA. When I sign-out of ActivityB, I want it to also sign out of ActivityA.
For example, I have a HomeActivity using Google's PlusApi and then I have a MapsActivity that will be used for my navigation and all other Api Services I want to include.
1) Is this possible?
2) Is this the best way to do this and/or is there a better way to do it?
Here is my Code:
HomeActivity
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class HomeActivity extends Activity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        View.OnClickListener {

    /* Request code used to invoke sign in user interactions. */
    private static final int RC_SIGN_IN = 0;

    /* Keys for persisting instance variables in savedInstanceState */
    private static final String KEY_IS_RESOLVING = "is_resolving";
    private static final String KEY_SHOULD_RESOLVE = "should_resolve";

    /* Client used to interact with Google APIs. */
    private GoogleApiClient mGoogleApiClient;

    /* View to display current status (signed-in, signed-out, disconnected, etc) */
    private TextView mStatus;

    /* Is there a ConnectionResult resolution in progress? */
    private boolean mIsResolving = false;

    /* Should we automatically resolve ConnectionResults when possible? */
    private boolean mShouldResolve = false;
    private static final String TAG = "SignInActivity";
//
//    private ProgressBar spinner;

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

        // Restore from saved instance state
        // [START restore_saved_instance_state]
        if (savedInstanceState != null) {
            mIsResolving = savedInstanceState.getBoolean(KEY_IS_RESOLVING);
            mShouldResolve = savedInstanceState.getBoolean(KEY_SHOULD_RESOLVE);
        }

        // [END restore_saved_instance_state]

        // Set up button click listeners
        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

//        spinner = (ProgressBar)findViewById(R.id.sign_in_loading);
//        spinner.setVisibility(View.VISIBLE);
//        Log.w(TAG, "Spinner is visible");
//
//
//        findViewById(R.id.login_screen).setVisibility(View.INVISIBLE);

        // Large sign-in
        ((SignInButton) findViewById(R.id.sign_in_button)).setSize(SignInButton.SIZE_WIDE);

        // Start with sign-in button disabled until sign-in either succeeds or fails
        findViewById(R.id.sign_in_button).setEnabled(false);

        // Set up view instances
        mStatus = (TextView) findViewById(R.id.status);

        // Build GoogleApiClient to request access to the basic user profile
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Plus.API)
                .addScope(new Scope(Scopes.PROFILE))
                .build();

    }

    private void updateUI(boolean isSignedIn) {
        if (isSignedIn) {
            // Show signed-in user's name
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            if (currentPerson != null) {
                String name = currentPerson.getDisplayName();
                mStatus.setText(getString(R.string.signed_in_fmt, name));
            } else {
                Log.w(TAG, getString(R.string.error_null_person));
                mStatus.setText(getString(R.string.signed_in_err));
            }

            // Set button visibility
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
            Log.w(TAG, "UI has been updated.");
        } else {
            // Show signed-out message
            mStatus.setText(R.string.signed_out);

            // Set button visibility
            findViewById(R.id.sign_in_button).setEnabled(true);
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
            findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        // onConnected indicates that an account was selected on the device, that the selected
        // account has granted any requested permissions to our app and that we were able to
        // establish a service connection to Google Play services.
        Log.d(TAG, "onConnected:" + bundle);

        // Show the signed-in UI

        updateUI(true);
    }

    @Override
    public void onConnectionSuspended(int i) {
        // The connection to Google Play services was lost. The GoogleApiClient will automatically
        // attempt to re-connect. Any UI elements that depend on connection to Google APIs should
        // be hidden or disabled until onConnected is called again.
        Log.w(TAG, "onConnectionSuspended:" + i);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_in_button:
                // User clicked the sign-in button, so begin the sign-in process and automatically
                // attempt to resolve any errors that occur.
                mStatus.setText(R.string.signing_in);
                // [START sign_in_clicked]
                mShouldResolve = true;
                mGoogleApiClient.connect();
                // [END sign_in_clicked]
                                break;
            case R.id.sign_out_button:
                // Clear the default account so that GoogleApiClient will not automatically
                // connect in the future.
                // [START sign_out_clicked]
                if (mGoogleApiClient.isConnected()) {
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                    mGoogleApiClient.disconnect();
                }
                // [END sign_out_clicked]
                updateUI(false);
                break;
            case R.id.disconnect_button:
                // Revoke all granted permissions and clear the default account.  The user will have
                // to pass the consent screen to sign in again.
                // [START disconnect_clicked]
                if (mGoogleApiClient.isConnected()) {
                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                    Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
                    mGoogleApiClient.disconnect();
                }
                // [END disconnect_clicked]
                updateUI(false);
                break;
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // Could not connect to Google Play Services.  The user needs to select an account,
        // grant permissions or resolve an error in order to sign in. Refer to the javadoc for
        // ConnectionResult to see possible error codes.
        Log.d(TAG, "onConnectionFailed:" + connectionResult);

        if (!mIsResolving && mShouldResolve) {
            if (connectionResult.hasResolution()) {
                try {
                    connectionResult.startResolutionForResult(this, RC_SIGN_IN);
                    mIsResolving = true;
                } catch (IntentSender.SendIntentException e) {
                    Log.e(TAG, "Could not resolve ConnectionResult.", e);
                    mIsResolving = false;
                    mGoogleApiClient.connect();
                }
            } else {
                // Could not resolve the connection result, show the user an
                // error dialog.
                showErrorDialog(connectionResult);
            }
        } else {
            // Show the signed-out UI
            updateUI(false);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);

        if (requestCode == RC_SIGN_IN) {
            // If the error resolution was not successful we should not resolve further.
            if (resultCode != RESULT_OK) {
                mShouldResolve = false;
            }

            mIsResolving = false;
            mGoogleApiClient.connect();

            Intent startMaps = new Intent(HomeActivity.this, MapsActivity.class);
            HomeActivity.this.startActivity(startMaps);
        }
    }

    private void showErrorDialog(ConnectionResult connectionResult) {
        int errorCode = connectionResult.getErrorCode();

        if (GooglePlayServicesUtil.isUserRecoverableError(errorCode)) {
            // Show the default Google Play services error dialog which may still start an intent
            // on our behalf if the user can resolve the issue.
            GooglePlayServicesUtil.getErrorDialog(errorCode, this, RC_SIGN_IN,
                    new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            mShouldResolve = false;
                            updateUI(false);
                        }
                    }).show();
        } else {
            // No default Google Play Services error, display a message to the user.
            String errorString = getString(R.string.play_services_error_fmt, errorCode);
            Toast.makeText(this, errorString, Toast.LENGTH_SHORT).show();

            mShouldResolve = false;
            updateUI(false);
        }
    }

}

MapsActivity
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.plus.Plus;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        View.OnClickListener {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private GoogleApiClient mGoogleApiClient;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private LocationRequest mLocationRequest;

    private HomeActivity  mHomeActivity = new HomeActivity();

    public static final String TAG = MapsActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        //Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                .setInterval(10*1000)           //10 seconds, in milliseconds
                .setFastestInterval(1 * 1000);   //1 second, in milliseconds

        findViewById(R.id.sign_out_button).setOnClickListener(this);
        findViewById(R.id.disconnect_button).setOnClickListener(this);

    }

    @Override
    public void onMapReady(GoogleMap map){
        //Add a marker in Sydney, Australia, and move the camera.
        LatLng sydney = new LatLng(-34, 151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause()  {
        super.onPause();
        if(mGoogleApiClient.isConnected())  {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.setMyLocationEnabled(true);
    }

    private void handleNewLocation(Location location)   {
        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
        LatLng latlng = new LatLng(currentLatitude, currentLongitude);

        mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location==null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution())   {
            try {
                //Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sign_out_button:
                // Clear the default account so that GoogleApiClient will not automatically
                // connect in the future.
                // [START sign_out_clicked]
//                if (mGoogleApiClient.isConnected()) {
//                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
//                    mGoogleApiClient.disconnect();
//                }
                // [END sign_out_clicked]
                Intent startHomeDisconnect = new Intent(MapsActivity.this, HomeActivity.class);
                MapsActivity.this.startActivity(startHomeDisconnect);
                break;
            case R.id.disconnect_button:
                // Revoke all granted permissions and clear the default account.  The user will have
                // to pass the consent screen to sign in again.
                // [START disconnect_clicked]
//                if (mGoogleApiClient.isConnected()) {
//                    Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
//                    Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient);
//                    mGoogleApiClient.disconnect();
//                }
                // [END disconnect_clicked]
                Intent startHomeSignOut = new Intent(MapsActivity.this, HomeActivity.class);
                MapsActivity.this.startActivity(startHomeSignOut);
                break;

        }

    }

}


text:
Q: Use of Jquery .not() in a variable
Possible Duplicate:
Getting text within element excluding decendants

I have the following function:
function initCBox(){
    CB_Init();
    var img1 = $(select.currentImg).attr('src');
    var label = $(select.currentImg).attr('alt');
    var desc = $('.item.active .caption').not($('.description')).text();

    CB_Open('href=' + img1 + ',,title=' + label + ',,comment=' + desc +'');
}

with the following html:

Light

Amber Light

Enter Text or HTML Here

I want my var = desc to only show the text in the class "caption", not anything in the
 ( for simplicity, I only include one
 item but I have others in the
). Need help with my excluding all but the caption text. Hope I haven't been too confusing!

A: You can do a string find and replace:
var desc = $('.caption').text(), // The caption and stuff you don't want
    noWant = $('.icon').text();  // Only stuff you don't want
desc = desc.replace(noWant,"");  // Find stuff you don't want and replace w ""

The advantage if this way over excluding descendants, is that it will grab the entire text of your description even if includes s, s, etc.


text:
Q: Getting two errors using Parsley.js to add validators to fields that are dynamically cloned I have a form which I am using Parsley.js to validate.  Everything works like a charm.  Except, there is a part of the form where users are allowed to add new fields:
addFieldsToContainer = function($fields, $container) {
    $fields.clone(true).removeClass('empty-form').appendTo($container);

    if (typeof(Parsley) !== 'undefined'){
        $('form.form-horizontal').parsley().destroy();
        addValidatorsListeners();
    }
};

My validations are a little complicated, because there are sections, and in each section, the inputs must all add up to a total number, which is the value of another input.  I've got the inputs triggered to blur, and if any of the inputs are entered and the total for the section is wrong, all the inputs for the section are given the parsley-error class, and vice versa.  Now, on the new input that is being added to the DOM, the parsley ui is not working on it, i.e. the parsley-success/error classes are not being added to it.  But the rest of the section still works fine, and even includes whatever number is in the input in the total calculation.  I'm also seeing these two errors in the dev console:
Uncaught TypeError: Cannot set property 'validatedOnce' of undefined parsley.min.js:8
Uncaught TypeError: Cannot read property '$errorsWrapper' of undefined

My code here.
How can I correctly bind these new inputs to the parsley validator?
Edit:
So I just realized that the when the user clicks the add input button, all of the inputs that have parsley:success/error classes have them all removed (because of model_form.parsley().destroy() I assume?) except for the new input that has been added.  This input class never changes with the rest of the section, as I've pointed out.  Also, the total enrollment input doesn't change, I'm guessing because of the { excluded: '[data-parsley-sum-total="all"]' } line.  So it looks like the input that is being cloned from the page isn't having it's binding destroyed or it's validators correctly added, so some sort of event handling problem?
Maybe related?

A: If you clone Parsley's elements with their data, yeah, Parsley will be confused as hell.
I'd simply recommend not doing that. More precisely, clone without the data and events, or else clone before binding with parlsey.
If you really have to go this way, you might be able to get away with cloning afterwards if you $yourClone.removeData('Parsley'). I haven't tested it and can't guarantee that even if it works now it would in the future.


text:
Q: index of bounds e problemas com timer Seguinte, eu tenho um timer que preenche 2 campos em um webbrowser, o mesmo faz a seguinte função...
var
  pega : string;
begin
  pega := Listaimportados.Items[i];
  I := i +1
  nome.text := Copy(pega, 0, 10);
  Webbrowser1.OleObject.Document.all.Item('login', 0).value := nome.text;

nisso ele vai repetindo a ação a cada 4 segundos, como vocês podem ver o i+1 pula para a próxima linha, que no caso está importada em listaimportados(listbox).
porém eu tenho um problema, se eu inserir menos de um item no listbox(listaimportados) ele começa a dar erro, list of bounds, como resolver?

A: Você disse nos comentários que quando chegasse ao fim, você deveria parar o timer.
Nesse caso é simples:
var
  pega : string;
begin
  if I = Listaimportados.Count then
  begin
    timer1.Enabled:= False;
    Exit;
  end;
  pega := Listaimportados.Items[i];
  I := i +1
  nome.text := Copy(pega, 0, 10);
  Webbrowser1.OleObject.Document.all.Item('login', 0).value := nome.text;

Nesse código, estou assumindo que Listaimportados é uma instancia de uma classe TStringList


text:
Q: Complex analysis objective type question. Let $f(z)=u+iv$ be an entire function. If the Jacobian matrix $$\begin{bmatrix}
    u_{x}(a)       & u_{y}(a)  \\
    v_{x}(a)       & v_{y}(a)   \\
\end{bmatrix}$$ is symmetric for all complex $a$. Then
$1.$ $f$ is a polynomial.
$2.$ $f$ is a polynomial of degree at most $1.$
$3.$ $f$ is constant.
$4.$ $f$ is a polynomial of degree at least $2.$
I have no idea how to solve this problem. It is clear that $4$th option is wrong as constant function satisfied given condition. From given symmetric matrix i just have that $u_{y}(a)=v_{x}(a) $. How to proceed further. Please help. Thanks a lot.

A: Since $u_y=v_x$ by the symmetry condition and $u_y=-v_x$ by Cauchy-Riemann we deduce that $u_y=v_x=0$, so that $u$ and $v$ are functions depending only on $x$ and $y$ respectively, i.e. $$f(z)=f(x+iy)=u(x)+iv(y)$$
Now $f'(z)=\frac {\partial f}{\partial x}(z)=u'(x)$ is a real-valued holomorphic function, which implies that it is a real constant: $f'(z)=r\in \mathbb R$.
This immediately forces  the conclusion that the required entire functions are the polynomials of degree at most one with real linear coefficient $r$: $$f(z)=rz+b \quad (r\in\mathbb R, b\in \mathbb C)$$
Warning
Note carefully that the class  of entire functions with symmetric Jacobians is none of the suggested four classes  and note also that $iz$ is a polynomial of degree one whose Jacobian is not symmetric!

A: Break out the Cauchy-Riemann equations.  What does the symmetry say about them?

A: For symmetry $u_y=v_x$ for all $z\in\mathbb C$. As $f$ is entire, use C-R equations in it to get $u_y=-u_y$ which gives $u_y=0$.
Now think of an entire $f=u+iv$ having expansion like this:
$f(z)=a_0+a_1.z+a_2.z^2+....$.
For what choices of $a_{i's}$ do you always have Re($f$) free of variable $y$ such that $u_y=0$?

A: Here's a way of doing it which is, I think, similar in spirit to the solution of Georges Elencwajg, although the view presented here is a little different:
If the Jacobean matrix
$\begin{bmatrix} u_{x} & u_{y} \\ v_{x} & v_{y} \end{bmatrix} \tag{1}$
is in fact symmetric, we have
$u_y = v_x; \tag{2}$
we also have the Cauchy-Riemann equations, which tell us that
$u_x = v_y \tag{3}$
and
$u_y = - v_x; \tag{4}$
combining (2) and (4) we find
$v_x = u_y = -v_x, \tag{5}$
forcing
$v_x = 0, \tag{6}$
and hence
$u_y = 0 \tag{7}$
as well, also by virtue of (2)-(4).  It of course follows from (6) and (7) that $u$ depends only on $x$ and $v$ depends only on $y$.
We compute the second derivatives of $u$ and $v$, $u_{xx}$, $u_{xy} = u_{yx}$, $u_{yy}$, $v_{xx}$, $v_{xy} = v_{yx}$, and $v_{yy}$.  Since $u_y = 0$, (7), we have
$u_{yy} = u_{yx} = u_{xy} = 0; \tag{8}$
likewise, $v_x = 0$ yields
$v_{xx} = v_{xy} = v_{yx}  = 0; \tag{9}$
also, from (3), (8) and (9),
$u_{xx} = v_{yx} = 0 \tag{10}$
and
$v_{yy} = u_{xy} = 0. \tag{11}$
We see that all the second partials of $u$ and $v$ with respect to $x$ and $y$ are $0$.  It follows that $u$ is a linear function of $x$, and that $v$ is a linear function of $y$, since the only possible non-vanishing derivatives are $u_x$ and $v_y$.  We may thus write
$u = u_0 + u_1x, \tag{12}$
$v = v_0 + v_1y, \tag{13}$
and it follows from (2) that
$u_1 = u_x = v_y = v_1 = \alpha \in \Bbb R; \tag{14}$
thus
$f(z) = u + iv = u_0 + iv_0 + \alpha x + i \alpha y = u_0 + i v_0 + \alpha (x + iy) = u_0 + i v_0 + \alpha z, \tag{14}$
in agreement with Georges Elencwajg's result.  Assertion (2) of the question binds.


text:
Q: Update an existing value in Firebase Realtime Database I want to add to an existing value in Firebase
I have an updatePoints function that looks up a user, if they already exist I want to lookup up the existing points and add the newPoints value. How can I do this with the below please?
updatePoints(userID, newPoints){
firebase.database().ref('/userProfile').child(userID).once('value', function(snapshot) {
  var exists = (snapshot.val() !== null);

  if (exists) {
      console.log('user ' + userID + ' exists!');

        firebase.database().ref('markets/'+userID).update({
        points: newPoints  // I want to look up eixsitg points and add on newPoints,

      });

    } else {
      console.log('user ' + userID + ' does not exist!');
      firebase.database().ref('/markets').child(userID).set({
      points: 1

      });

    }
});

A: Worked it out, if this helps someone...
console.log("val",snapshot.val().points);