text:
Q: I want a regex that will select all characters including special characters, except the Last 4 Characters. Vanilla JS let str = "AAAAA-0000021111-1111";
let res = str.match(/\d(?=\d{4})/g);
document.write(res);

//This didnt work, the output is given below:
Output:
0,0,0,0,0,2
// its only selecting these characters which are highlighted in bold AAAAA-0000021111-1111
And this is what I am expecting:
A,A,A,A,A,-,0,0,0,0,0,2,1,1,1,1,-
Basically, I want all characters to be selected including - or any other special characters except the last 4.
I am listing a couple of extra samples for a better understanding
Sample1: ABC-101010-1111
Expected output is: A,B,C,-,1,0,1,0,1,0,-
Sample2: ABCD101010-11111
Expected output is: A,B,C,D,1,0,1,0,1,0,-,1
I am using Vanilla JS.
Really appreciate your involvement in this.
Thanks in Advance Sir/Ma'am!!!

A: You can use
/(?!\d{1,4}$)./g

See the regex demo.
NOTE: If you need to match all chars except last four any chars, you will need to replace \d with . in the lookahead, and it can be even written in a bit more succint way:
/.(?!.{0,3}$)/g

See this regex demo.
Details:

*

*. - any single char other than line break char

*(?!.{0,3}$) - a negative lookahead that matches a location not immediately followed with zero to three chars other than line break chars, till end of string.

The regex will match any char other than a line break char (., to match line breaks, use [^], [\s\S]/[\d\D]/[\w\W] or add s flag) that does not start a sequence of one, two, three or four digits at the end of string ((?!\d{1,4}$)).
See a JavaScript demo:

console.log("AAAAA-0000021111-1111".match(/(?!\d{1,4}$)./g))
console.log("AAAAA-0000021111-1111".match(/.(?!.{0,3}$)/g))


text:
Q: when i was compile, i passed configure but encounter errors when i was 'making' I use ./configure and make to compile Dragon from Github on Ubuntu. i passed my configure process even though there is a warning for DarkSUSY which is optional according to the installation document. and i just run 'make' process. after some time, i encounter an error here is my error
make  all-recursive
make[1]: Entering directory '/media/rainman/d/DM/DRAGON'
Making all in cparamlib
make[2]: Entering directory '/media/rainman/d/DM/DRAGON/cparamlib'
make[2]: Nothing to be done for 'all'.
make[2]: Leaving directory '/media/rainman/d/DM/DRAGON/cparamlib'
make[2]: Entering directory '/media/rainman/d/DM/DRAGON'
/bin/bash ./libtool  --tag=F77   --mode=compile  -DHAVE_CONFIG_H -I.  -I/media/rainman/d/DM/DRAGON/include -I/media/rainman/d/DM/DRAGON/cparamlib -DTIXML_USE_STL -I/media/rainman/d/DM/gsl/scalar/include -I/media/rainman/d/DM/cfitsio/scalar//include   -c -o dmspec.lo dmspec.F
Usage: /media/rainman/d/DM/DRAGON/libtool [OPTION]... [MODE-ARG]..
``Try 'libtool --help' for more information.
libtool:   error: unrecognised option: '-DHAVE_CONFIG_H'
Makefile:756: recipe for target 'dmspec.lo' failed
make[2]: *** [dmspec.lo] Error 1
make[2]: Leaving directory '/media/rainman/d/DM/DRAGON'
Makefile:806: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/media/rainman/d/DM/DRAGON'
Makefile:573: recipe for target 'all' failed
make: *** [all] Error 2

on the other computer i successfully pass 'make' while did the same thing but failed. i do not know how to deal with this. could anyone help me out? thanks

A: The most relevant part of the error you recieved is
libtool:   error: unrecognised option: '-DHAVE_CONFIG_H'

This error looks similar to that encountered in Error installing PCRE, which was due to not having the 'g++' c++ compiler installed.
Try installing build-essential (apt-get install build-essential) which should ensure you have the bare minimum necessary installed to compile most software, including g++.

redpajama_set_name: RedPajamaStackExchange


text:
Q: VM has become 'inaccessible' - Vagrant no longer working For some reason this morning when I run 'vagrant up' I get the following error (this has worked absolutely fine for over a year)
Your VM has become "inaccessible". Unfortunately, this is a critical error with VirtualBox that Vagrant can not cleanly recover from. Please open VirtualBox and clear out your inaccessible virtual machines or find a way to fix them.

I could try removing my existing .vagrant folder and doing a vagrant up but that will take forever on our very slow internet speeds - can anyone suggest how to fix this quickly?

A: Nothing here worked for me.

*

*I deleted (or renamed see first comment) all files from

C:\Users[YourNameHere].VirtualBox

*Run vagrant again:
vagrant up
Now it's up.

A: VirtualBox Manager will likely give you a bit more useful information, for example in my case it reported that the .vbox file did not exist.
After taking a look the problem was indeed that the file didn't exist - something had renamed it to x.vbox-tmp (shutting the PC down with the VM still running maybe?)
I copied the x.vbox-prev file to x.vbox and tried booting the VM again and everything worked fine.

A: Find the one which is inaccessible with one of the following commands:
$ vagrant global-status

or:
$ VBoxManage list vms

Then note the GUID, and remove it from VirtualBox.xml file (OS X: ~/Library/VirtualBox/VirtualBox.xml, Windows: %HOME%/.VirtualBox).
Alternatively remove .vagrant folder from the folder where is your VM and start from scratch (vagrant up).
See also: Cannot Delete "Inaccessible" virtual machines from Virtualbox GUI at VirtualBox

A: You can simply delete the .vagrant folder from your project folder and run vagrant up again.

A: By chance if someone deletes your vm from VirtualBox VMs folder manually, also in this case your vm would become inaccessible. However, you will not be able to get your machine back but vagrant will still show your vm in the list. To remove it completely from the vm list, go to
\.vagrant.d\data\machine-index

and open index file. Delete the reference of inaccessible machine. Next time when you run below command, it will not show your inaccessible machine.
vagrant global-status --prune

A: My problem was the same, but the fix was quite different... my VMs are stored on a network drive, accessible by NFS share. The remote drive had failed to come up after a reboot, so the VMs weren't accessible.
Took me a while to realise the reason, and meantime hunted all over SO without a solution.
Then I realised, facepalmed, mounted the paths, and it all worked.
So in a nutshell, it was a path issue.
I felt I should include it here in case it helps someone in the same boat.

A: By using command line, you can remove all inaccessible boxes by using an one-liner:
VBoxManage list vms |grep inaccessible |cut -d "{" -f2 |cut -d "}" -f1 |xargs -L1 VBoxManage unregistervm

See https://phz.fi/?p=8422

A: This worked for me
After some digging through the debug output, I discovered that even though the actual VM is intact (I can load and run it from the VirtualBox GUI app), somewhere in its guts, VirtualBox flagged this VM as "". Vagrant, rightly believing what it's told, spits out the error message.
After looking at VBoxManage's help, I found that one its commands, list vms, unsurprisingly lists all of the VMs registered with VirtualBox:
$ /cygdrive/c/Program\ Files/Oracle/VirtualBox/VBoxManage.exe list vms
"precise64" {3613de48-6295-4a91-81fd-36e936beda4b}
"<inaccessible>" {2568227e-e73d-4056-978e-9ae8596493d9}
"<inaccessible>" {0fb42965-61cb-4388-89c4-de572d4ea7fc}
"<inaccessible>" {c65b1456-5771-4617-a6fb-869dffebeddd}
"<inaccessible>" {9709d3d5-ce4d-42b9-ad5e-07726823fd02}

One of those VMs flagged as inaccessible is my lost VM! Time to fix VBoxManage's wagon, by unregistering the VM as inaccessible, then re-registering it with the correct name:

*

*Open the configuration file for your lost VM. Mine was saved to C:\cygwin\home\Philip\VirtualBox VMs\rails-vm-v2\rails-vm-v2.vbox

*Find and copy the value of the uuid attribute of the Machine node. Mine was 9709d3d5-ce4d-42b9-ad5e-07726823fd02.

*In a Windows command prompt (or Cygwin terminal), unregister the VM with the unregistervm command, using the [uuid] value from step 2:
$ C:\Program Files\Oracle\VirtualBox\VBoxManage.exe unregistervm [uuid]

*Now register the VM using the registervm command, with the path to the VM configuration file:
$ C:\Program Files\Oracle\VirtualBox\VBoxManage.exe registervm C:\cygwin\home\Philip\Virtual VMs\rails-vm-v2\rails-vm-v2.vbox

Now you should be able to start the VM as expected.
Source :
http://www.psteiner.com/2013/04/vagrant-how-to-fix-vm-inaccessible-error.html

A: this works for me:
In my "C:\Users{user}\VirtualBox VMs{vm-id}" folder are two files

*

*{vm-id}.vbox-prev

*{vm-id}.vbox-tmp

Renaming from "{vm-id}.vbox-tmp" to "{vm-id}.vbox" solved my problem and i can call "vagrant up"

A: I had to rename [vm-id].vbox-tmp (on VirtualBox VMs) to [vm-id].vbox. After that, without delete the .vagrant folder, I could run vagrant up and it worked very well.

A: On Linux the following will unregister the machines:
VBoxManage list vms
VBoxManage unregistervm <inaccessible machine UID>

After that you may want to restart VB services:
sudo /sbin/vboxconfig

Deleting .vagrant folder may help but you had to rebuild the machines.

A: I also had this problem.
when change directory of virtualBox after restart macOS virtualbox get inaccessible to all vms.
my solution worked.
just move virtual box to default directory.
remove all inaccesible vms from gui, then register vms from default path next run it.
or
vagrant up

A: try deleting from oracle VM manager. You can see inaccessible boxes, by removing  them it should fix it. worked for me.


text:
Q: Using backquote (backtick) in JavaScript will result in "can not read property 'style' of null ' I am trying to generate a click event on dynamically generated html id using JavaScript.
I used backquote to register the click event, but I get
can not read property 'style' of null
If you check the rendered HTML, ${post_.id} is normally output after the css id identifier, but the style registered by the event listener can not be read.
What mistakes have I made?
index.pug
...
head
      script.
      function click(id) => {
        let element = document.getElementById(id);
        if element.style.display == 'none' {
          element.style.display = 'block'
        }
        else {
          element.style.display = 'none'
        }
      }
...
body
...
      //- pug templates
      each post in posts

      //- not working
      a(onclick=`click(div_${post._id})`) update

      div(id=`div_${post._id}` style="display: none;)


text:
Q: Camera preview in another view issue with width I have added camera preview on the half of the iPhone screen.
-(void) viewDidAppear:(BOOL)animated
{
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    CALayer *viewLayer = self.vImagePreview.view.layer;
    NSLog(@"viewLayer = %@", viewLayer);

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];

    captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;
    [self.vImagePreview.view.layer addSublayer:captureVideoPreviewLayer];

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    [session startRunning];
}

I added camera view controller in viewDidLoad method and set it's frame:
vImagePreview.view.frame = CGRectMake(0, 44, 320, 179);

But camera view isn't 320. Any idea how to set width of the camera view add this way?
Height is fine but width is about 100 wide.
It's like on this link width is 320 but camera view is from some reason smaller (width).
![enter image description here][1]

A:  captureVideoPreviewLayer.frame = self.vImagePreview.view.bounds;

This is the culprit.
You need to add videoGravity(Indicates how the video is displayed within a player layer's bounds rect.) with AVLayerVideoGravityResizeAspectFill property
and then assign the bounds and the last but not the least,
you need to give the x and y- coordinates that establishes the center of a rectangle.
CGRect bounds=self.vImagePreview.view.layer.bounds;
avLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
avLayer.bounds=bounds;
avLayer.position=CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));

A: Change your camera preview screen width and check.


text:
Q: Measuring distances from a time series of images in R, for snow-depth calculation I am looking to calculate snow-depth for a timeseries of timelapse images in R.  In each image there is a snow stake that represents a certain length from which we can get snow depth from.  I wish to instead of reading the depth form each image, automate this process.
My idea is to first draw a reference line over the length of the snow stake, so we know how long the snow stake is in pixels. Then to, as it snows, reduce or grow that line based on the snow line, or automatically redraw the line to where the snow starts. I am wondering, a)whether this can be done, b)if any one has tried something similar to this and c)whether someone can point me in the right direction on where to start the process.
Currently I have tried drawing the line and then using edge detection to automatically redraw the line for every picture and then measure that line, but there is too much noise and our snow stakes don't stand out enough.  I have also been using the magick package but haven't found a viable solution yet.  Let me know if you have any ideas! Thanks!
Here is an example of a snow stake site in summer.


text:
Q: Calculation between columns per group in pandas Hello I have a dataframe such as :
COL1 COL2 COL3
A    30   400
A    32   400
A    70   400
B    32   700
B    10   700

And I would like for each COL1, to calculate the sum of COL2 / COL3.unique()
Example = 30+32+70/400 = 0.33
Here I should then get:
COL1 COL2 COL3 New_col
A    30   400  0.33
A    32   400  0.33
A    70   400  0.33
B    32   700  0.06
B    10   700  0.06

Does someone have an idea please ?

A: In your case do groupby with transform
df['new'] = df.COL3.rdiv(df.groupby('COL1')['COL2'].transform('sum'))
df
Out[19]:
  COL1  COL2  COL3   new
0    A    30   400  0.33
1    A    32   400  0.33
2    A    70   400  0.33
3    B    32   700  0.06
4    B    10   700  0.06


text:
Q: How do you Find/Close process when running from TaskScheduler? I have two programs that conflict with each other.  One of them is a C# console app that is launched by Task Scheduler (Program1) in the middle of the night, the other (Program2) is a C# WPF program that is typically run by users during the day.  I attempted to use the following to shut down Program2 from Program1:
public static void CloseProgram2()
{
    var process = System.Diagnostics.Process.GetProcessesByName("Program2").FirstOrDefault();
    if (process != null)
    {
        if (process.CloseMainWindow())
        {
            SpinWait.SpinUntil(() => null == System.Diagnostics.Process.GetProcessesByName("Program2").FirstOrDefault(),
                TimeSpan.FromSeconds(30));
        }
    }
}

For some reason, Program2 does not shut down when Program1 is run from the TaskScheduler.  However, if I run Program1 manually, it always shuts down Program2. I have task scheduler set to provide credentials so that Program1 will run whether or not anybody is logged into the computer.  I notice that the output window for Program1 is not displayed while it is running from Task Scheduler, but it does successfully run.  I am wondering if perhaps Task Scheduler is running Program1 in such a way that it does not see processes that were not started up by Task Scheduler, and that's why Program2 doesn't get shut down.
Any ideas or solutions that can help me close Program2 from Program1 when Program1 is run using TaskScheduler would be greatly appreciated.

A: Found another solution to use.  Instead of using proccess.CloseMainWindow()  I created a batch file with the following:
taskkill /F /IM Program2.exe

And then just ran that batch file from Task Scheduler.
What's weird, is that I needed to put a blank line before the taskkill command in my bat file.  Without it, I get a bunch of gibberish and it says it doesn't know how to run that command.  Almost as if garbage was inserted before the taskkill command.  Very strange...


text:
Q: Any error found in R responds with Error in app$vspace(new_style$`margin-top` %||% 0) : attempt to apply non-function I honestly don't know how to make this reproducible. Any error that occurs in R, using tidyverse throws:
Error in app$vspace(new_style$`margin-top` %||% 0) :
  attempt to apply non-function

Has anybody else seen this?
Edit:
Here is the sessionInfo() output:
R version 4.0.4 (2021-02-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252    LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C
[5] LC_TIME=English_United Kingdom.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] rstatix_0.7.0   plotly_4.10.0   ggpubr_0.4.0    forcats_0.5.1   stringr_1.4.0   dplyr_1.0.4     purrr_0.3.4     readr_2.1.2     tidyr_1.2.0     tibble_3.0.6
[11] ggplot2_3.3.5   tidyverse_1.3.1

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.8.3      lubridate_1.7.10  assertthat_0.2.1  digest_0.6.29     utf8_1.1.4        R6_2.5.1          cellranger_1.1.0  backports_1.2.1   reprex_2.0.1
[10] evaluate_0.15     httr_1.4.2        pillar_1.7.0      rlang_1.0.2       lazyeval_0.2.2    readxl_1.3.1      rstudioapi_0.13   data.table_1.14.2 car_3.0-12
[19] rmarkdown_2.13    labeling_0.4.2    htmlwidgets_1.5.4 munsell_0.5.0     broom_0.7.12      xfun_0.30         compiler_4.0.4    modelr_0.1.8      pkgconfig_2.0.3
[28] htmltools_0.5.2   tidyselect_1.1.2  fansi_0.4.2       viridisLite_0.4.0 crayon_1.5.1      tzdb_0.3.0        dbplyr_2.1.1      withr_2.5.0       grid_4.0.4
[37] jsonlite_1.7.2    gtable_0.3.0      lifecycle_1.0.1   DBI_1.1.2         magrittr_2.0.1    scales_1.1.1      cli_3.2.0         stringi_1.5.3     carData_3.0-5
[46] farver_2.1.0      ggsignif_0.6.3    fs_1.5.0          xml2_1.3.2        ellipsis_0.3.2    generics_0.1.2    vctrs_0.4.0       tools_4.0.4       glue_1.4.2
[55] hms_1.1.1         yaml_2.3.5        abind_1.4-5       fastmap_1.1.0     colorspace_2.0-0  rvest_1.0.2       knitr_1.38        haven_2.3.1

A: I got this exact error in R studio. I reviewed the code and noticed a typo in a variable name. I corrected a typo in the variable name-->it solved this error. My two cents would be to review your code for any such typo including variable names, and function names etc.


text:
Q: What is the different between Scheduler and Strategy in Apache Storm I'm studying Apache Storm. I read the source code && developer documentation && JavaDoc && other useful blogs about Storm.
A question confused me a lot. Most documentation and blogs said that different scheduler lead to different assignment style when Storm Cluster assign a topology to Workers. But I confused that what is the role performed by Strategies in package "org.apache.storm.scheduler.resource.strategies.XXX" such as DefaultResourceAwareStrategy and other two strategies when Storm assign a topology ?
In Storm example program, I remembered these strategies applied in method setTopologyStrategy() to choose a strategy when create a topology. So,what is the different between Scheduler like ResourceAwareSchedule and Strategies like DefaultResourceAwareStrategy in the task assignment? Which one is the real factor to decide the task assignment?
I searched this problem on google but it not have a very clearly answer. I wish I can get a reply as clear as possible to explain the difference of Scheduler and Strategy. Thanks a lot.

A: Storm has a few different schedulers as you note. Some of them don't take the resources of the supervisor nodes into account. ResourceAwareScheduler is a scheduler implementation that can take supervisor resources/load into account when deciding where to assign a topology.
In order for ResourceAwareScheduler to be flexible, it uses a strategy to figure out how to rank the different supervisors. ResourceAwareScheduler contains the common code necessary to be resource aware, while the strategies do the actual scheduling. The ResourceAwareScheduler uses the strategy to do the scheduling, if that makes sense.
Look at https://github.com/apache/storm/blob/master/storm-server/src/main/java/org/apache/storm/scheduler/resource/strategies/scheduling/DefaultResourceAwareStrategy.java#L108 and the corresponding line in GenericResourceAwareStrategy. The comments there explain what the different strategies do.


text:
Q: fputcsv only returning one row from array This must be really simple... Following examples on here and php.net, I'm trying to get records from a mysql query, convert them to csv format, and assign this data to a variable for use in a program I have created. I would like to accomplish this without creating temporary files.
  public function export3() {
      $order_data = array();
      $order_data[] = array(
        'order_id',
        'email',
        'telephone',
        'shipping_address',
        'payment_address',
        'comment'
    );

    // Mysql returns data and is assigned to this array in the following format

    $order_data[] = array(
        '1',
        'blank@blank',
        '123456789',
        '123 Lane',
        '123 Lane',
        'no comment'
    );

    $order_data[] = array(
        '2',
        'blank3@blank3',
        '987654321',
        '321 Lane',
        '321 Lane',
        'no comment'
    );

    $outstream = fopen("php://temp", 'r+');

    foreach($order_data as $csv_data) {
        fputcsv($outstream, $csv_data);
    }

    rewind($outstream);
    $export_data = fgets($outstream);
    fclose($outstream);

    $response->output($export_data);

}

Unfortunately, I occasionally get complaints of "array to string" conversion, but even without any errors, I only get the first array (in csv format) but not the others. Any suggestions? Thank you

A: Use stream_get_contents() in place of fgets(), since the latter only fetches a single line.
$export_data = stream_get_contents($outstream);


text:
Q: How to change @DrawableRes parameter to Drawable in @Compose function? Picture function draws picture out of resource id; like R.drawable.icon.
   @Composable
    fun Picture(@DrawableRes resId: Int, modifier: Modifier = Modifier) {
        val rectModifier = loadVectorResource(resId).resource.resource
                ?.let { asset ->
                    modifier.paint(
                            painter = VectorPainter(asset)
                    )
                }
                ?: modifier
        Box(modifier = rectModifier)
    }

How can I change this, so it takes a Drawable argument instead of an @DrawableRes?

A: I am not sure about your scenario, to which you need Drawable instead of the given API.
But we can achieve using the following way. Modifier.paint need just a Painter Object, Painter we can create using both ImagePainter and VectorPainter.
In our case, we want to use Drawable, so we can use ImagePainter and its need ImageAsset, so we can use Bitmap to create ImageAsset.
So the final result will be like:
@Composable
fun Picture(@DrawableRes resId: Int, modifier: Modifier = Modifier) {
    val resources = ResourcesCompat.getDrawable(ContextAmbient.current.resources, resId, null)
    resources?.let {
        Picture(drawable = it, modifier = modifier)
    }
}

@Composable
fun Picture(drawable: Drawable, modifier: Modifier = Modifier) {
    Box(
        modifier = modifier.paint(
            ImagePainter(
                drawable.toBitmap().asImageAsset()
            )
        )
    )
}


text:
Q: QNA chatbot "say the feedback" with Cortana I created a QNA (qnamaker.ai) and a chatbot in Azure. They connected and doing what they should do. I activated Cortana channel on azure than if I use the right invocation method its giving the right feedback just it doesn't talk at all. I saw that Cortana will answer verbally if you invoked or queried with speech but seems not working.
I tried to recreate the whole app but it doesn't resolve my issue.
I have created a basic C# UWP app with basic question and with that Cortana talks.
The code now is the default chatbot code from Microsoft.
I would ask your advice that if I miss some setting or I just need to modify the code?
Thanks for your help.
Gabor
    protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
    {
        var httpClient = _httpClientFactory.CreateClient();

        var qnaMaker = new QnAMaker(new QnAMakerEndpoint
        {
            KnowledgeBaseId = _configuration["QnAKnowledgebaseId"],
            EndpointKey = _configuration["QnAAuthKey"],
            Host = GetHostname()
        },
        null,
        httpClient);

        _logger.LogInformation("Calling QnA Maker");

        // The actual call to the QnA Maker service.
        var response = await qnaMaker.GetAnswersAsync(turnContext);
        if (response != null && response.Length > 0)
        {
            await turnContext.SendActivityAsync(MessageFactory.Text(response[0].Answer), cancellationToken);
        }
        else
        {
            await turnContext.SendActivityAsync(MessageFactory.Text("No QnA Maker answers were found."), cancellationToken);
        }

A: Bot samples do not call the appropriate API to speak results.  You need to add parameters for speech and input hints.  Please see
https://github.com/microsoft/cortana-skills-samples/blob/master/Consumer/CSharp/V4Patches/11.qnamaker.diff
That shows a change to do this
                 await turnContext.SendActivityAsync(msg, speak: msg, inputHint: InputHints.AcceptingInput, cancellationToken: cancellationToken);


text:
Q: Label foreground resource I've got a small WPF issue here that I can't figure out.
I'm trying to set up a ResourceDictionary containing a number of colors, brushes and ControlTemplate entries.
My problem is that I'm trying the set the foreground brush of a Label to a resource in the same file and that bit isn't working and there's no trace messages about it.
<Color x:Shared="false" x:Key="DefaultForegroundColor" A="255" R="0" G="0" B="0" />
<!--<Color x:Shared="false" x:Key="DefaultForegroundColor" A="255" R="255" G="0" B="0" />-->
<SolidColorBrush x:Shared="false" x:Key="DefaultForegroundBrush" Color="{DynamicResource DefaultForegroundColor}"/>

<Color x:Shared="false" x:Key="HeadingColor" A="255" R="17" G="158" B="218" />
<SolidColorBrush x:Shared="false" x:Key="HeadingBrush" Color="{DynamicResource HeadingColor}"/>

<Style TargetType="{x:Type Label}" x:Key="SectionHeadingStyle">
   <Setter Property="FontSize" Value="18"/>
   <Setter Property="Foreground" Value="{DynamicResource HeadingBrush}"/>
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="Label">
            <Border BorderThickness="0,0,0,2" BorderBrush="{DynamicResource DefaultForegroundBrush}" HorizontalAlignment="Left">
               <ContentPresenter Margin="5"/>
            </Border>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>

The border colour works fine (even when it's not black) but the foreground of the label remains black instead of a light blue. Any ideas what I'm doing wrong?
Thanks.
UPDATE
Forgot to mention that it looks good in the designer too.
UPDATE 2
Upon Snooping the Visual Tree it appears that the Foreground colour makes it most of way through the template until the ContentPresenter uses a TextBlock to display the header text. The TextBlock remains black while the ContentPresenter above has a nice shade of blue  set to TextElement.Foreground. Is there something else I can do in the Template to give the created TextBlock the foreground colour?

A: I see two possible solutions
you need to make the resource a StaticResource.  For example, if you change the brush to this it works:
<SolidColorBrush x:Shared="false" x:Key="HeadingBrush" Color="{StaticResource HeadingColor}"/>

Or if you change the Foreground in the style to a StaticResource, it will work.
The other option is to remove the x:Shared="false" from both the brush and the color.  That resolves the issue also.
<Color x:Key="HeadingColor" A="255" R="17" G="158" B="218" />
<SolidColorBrush x:Key="HeadingBrush" Color="{DynamicResource HeadingColor}"/>

It seems to be an issue with the combination of multiple layers of DynamicResource plus the non-shared resources.

A: Just realised I never closed this question:
In the end there was a library importing resources at application level. For some reason these caused a conflict with my resources and neither were applied. Moving the library's resources to Window or UserControl level fixed the issue.


text: Q: test for measuring affect of one multilevel categorical variable on a continuous one I have a continuous dependent variable income and i want to check the effect of age group on income. Age group is categorical( 15-25, 26-35 etc) with 7 levels and income is not normally disributed as you can see below. Which test is more appropriate for checking the effect of my independent var on income? Thank you.


text:
Q: i could not add horizontal scrollbar to iframe I am shaping a family tree using list as element to build the tree
my problem is when the get larger no horizontal scrollbar appears
I am using iframe and css to control the style of the tree
this is the style of the iframe
 .frame
 {
     overflow: scroll;
     width: 149px;
     height: 100%;
 }

and I added this attribute to the tag but it didn't work also
 <iframe class = "frame" width="200" height="200" scrolling="yes" src="">
 </iframe>

can someone help me please.

A: Correct me if I'm wrong but shouldn't it be
 <iframe class="frame" width="200" height="200" scrolling="yes" src=""></iframe>

to apply the .frame class to the iframe

A: Please run the code and let me know where your having problem may be i am unable to understand your question

 .frame
 {
     overflow: scroll;
     width: 149px;
     height: 100%;
 }
 <iframe width="800" height="800" scrolling="yes" src="stackoverflow.com">
 </iframe>


text:
Q: How to send the formated data to fire store I have few data like below:
Name (string),
Age (string),
Number (string),
ContactList (Array of string),
messages (Array of string),
callHistory (Array of string)

All these above values i have collected from each screen and i saved it in AsyncStorage. I want to send these data as in same format as i mentioned in bracket. But how can i do formated and send to firestore ?.I am new bie. I tried all wasy but not able to understand about doing the formating and sending to fire store.
In my firestore my collection will look like is :
Details (Collection Name) -> UserID(DocumentID) ->Data[]` (In this data i need to save as array. Like each time when i push data to this collection i need to save all in array (index format)).
How can i do that ?.
Any help would be great !

A: You would do this in 2 steps.
1) Get the data from AsyncStorage[1], store it in a variable in the format you want.
2) Set the variable in firestore.[2]
 db.collection("Details").doc("UserID").set(variable).then(function(){
 });

[1]https://reactnative.dev/docs/asyncstorage#getitem
[2]https://cloud.google.com/firestore/docs/manage-data/add-data#data_types


text:
Q: Loading style button doesn't reset when called in quick succession I am using Inline Button Loader For Bootstrap 4 - Bootstrap4C Spinners to show loading action when clicked.
I am also calling the click action manually in my javascript for every word that gets entered. Problem is when I type the word one by one and waiting for the response (which takes a second), the button transition works correctly. However if i type multiple words back to back without waiting for the response then the button always gets stuck in loading state.
You can observe the behavior here: http://34.66.22.154:8000/
Here is my index.html:

        <meta charset='utf-8'>
        <link rel='stylesheet' href='../static/style.css'>
        <link rel="stylesheet" href="../static/cmGauge.css">

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet">
        <link href="../static/component-spinners.css" rel="stylesheet">

Sentiment Analysis of Movie Reviews

                    <form action="/analyze" id="analyzeForm" class="form" method="post">

                            <textarea id = "review_id" rows = "10" cols = "100" name = "review_name" class="review_class"></textarea>

                            <button id="submit_button" type="submit" class="btn btn-primary btn-spinner btn-spinner-example" value="Analyze" data-spinner-text="Analyzing...">Analyze</button>

                    </form>
                    Negative

                    Positive

Code on GitHub

Powered by Hugging Face's awesome pytorch-transformers library

Can you please let me know how to fix this? Thank you.

A: The problem seems to be in the spinner component.
When buttonLoader('start') is called, it saves the original button text in an attribute:
$(self).attr('data-btn-text', $(self).text());

But if the button is already spinning and its text is already set to data-spinner-text, then both data-spinner-text and data-btn-text are set to the same value and the original button text is lost.
It seems that this is supposed to be prevented by returning false if the button is already disabled:
if ($(self).attr('disabled') == 'disabled') {
  return false;
}

But the component doesn't set the disabled attribute when it's started:
$(self).addClass('disabled');

One quick solution is to stop the button before starting it.
This should prevent multiple overlapping calls to start the button.
$('.btn-spinner-example').click(function() {
  console.log("Button click start");
  $btn = $(this);
  $btn.buttonLoader('stop');
  $btn.buttonLoader('start');
});

Note that it's not necessary to make a jQuery object of a variable that's already a jQuery object:
btn = $(this);
$(btn).buttonLoader('start');

In fact, I might define the submit button once and use that definition throughout:
let $submitBtn = $('#submit_button');

$submitBtn.on('click',(function() {
  console.log("Button click start");
  $submitBtn.buttonLoader('stop');
  $submitBtn.buttonLoader('start');
});

Also, it seems that you're including the jQuery library twice in your document.


text:
Q: Counting array accesses I am trying to figure out how to determine the complexity(array accesses) of certain simple methods.
I'd like some confirmation if I'm doing this right.
For example this method.
    int i = 0;
    while(i < N){
        clone[i][j] = clone[++i][j];
        clone[i][j] = 0;
    }

Do the array accesses sum up to three here? One forclone[i][j] another for clone[++i][j] and lastly another one for clone[i][j]. Meaning this has ± 3N array accesses?
How about something like this:
if(clone[i][j] == value1 || clone[i][j] == value2)
Can I consider this to be one array access, or two?
Thanks in advance!

A: I'd count these as six array accesses.
You are accessing 2D arrays, and a statement like
clone[i][j] = 0;

could be written analogously as
int temp[] = clone[i];
temp[j] = 0;

You can also have a look at the bytecode: A a class like
class ArrayAcc
{
    static void foo()
    {
        int array[][] = new int[2][2];
        array[1][1] = 123;
    }

}

compiled and disassembled with

javap -c ArrayAcc.class

gives the following output:
....
static void foo();
Code:
   0: iconst_2
   1: iconst_2
   2: multianewarray #2,  2             // class "[[I"
   6: astore_0
   7: aload_0
   8: iconst_1
   9: aaload
  10: iconst_1
  11: bipush        123
  13: iastore
  14: return

The aaload instruction loads the reference to the "inner" array on the stack. The iastore instruction puts the value 123 into this "inner" array.

For the other part of the question,
if(clone[i][j] == value1 || clone[i][j] == value2)

Here it depends on whether the first condition is true or not. If the first condition is true, then the second one will not be evaluated. If you wrote
if(clone[i][j] == value1 | clone[i][j] == value2)

(with a single |) then you'd always check both conditions.


text:
Q: Add irregular data lat/lons to Xarray Dataset for interpolation So I have an Xarray dataset, ds, with 3 variables  in it: (example data)
Data variables:
    CO2      (time, data) float32 400.0 400.0 ... 400.0
    ...

Where the data dimension is a 1D array, for which I have 1D arrays of matching length containing latitude and longitude for each entry in data. The latitudes and longitudes are not sampled regularly. Ideally I would add the lat and lon so it showed up like this:
Data variables:
    CO2      (time, data, lat, lon) float32 400.0 400.0 ... 400.0
    ...

How can I add the lat/lon as a dimension so that I can interpolate along it using the Xarray interp function? (or is there some other, better way to interpolate this data?)
Eg: ds_interp = ds.interp(time=dt, lat=dlat, lon=dlon, assume_sorted=False)

A: In the xarray documentation, at the bottom of this section, you can see a note saying the interpolation only works over regular grids. I will have to either grid the data and interpolate it, which I was hoping to avoid, or interpolate it as numpy arrays manually with scipy.interpolate, which supports irregular grids.


text:
Q: Using Entity Framework & Linq to retrieve inserted ID with DomainCollectionView I'm using Entity Framework in Silverlight 4.0. When a user enters a keyword on my form, I check my EntityList<Keyword> see if the keyword exists or not. If not, I add it to the database & refresh my EntityList. I'm not sure if the way I'm doing it is 100% on track with best practice.
I'm using an MVVM-Friendly DomainDataSource, the DataCollectionView, thanks to Kyle McClellan. Here is my code for loading my keywords entity, in my constructor (with declarations above):
private readonly MI2DomainContext _context = new MI2DomainContext();
private readonly DomainCollectionView<Keyword> _keywordView;
private readonly DomainCollectionViewLoader<Keyword> _keywordLoader;
private readonly EntityList<Keyword> _keywordSource;
private int enteredKeywordID = 0;

public ProvisionDashboardViewModel()
{
    this._keywordSource = new EntityList<Keyword>(this._context.Keywords);
    this._keywordLoader = new DomainCollectionViewLoader<Keyword>(LoadKeywords, LoadKeywordsCompleted);
    this._keywordView = new DomainCollectionView<Keyword>(this._keywordLoader, this._keywordSource);
    this._keywordView.MoveToFirstPage();
}

After a user enters a keyword and clicks Search, I use commanding to call a method containing this code, where 'searchText' contains the user-entered value to search for. This creates a new instance of my Keyword class, adds it to my context, submits the changes, including the callback function upon completion:
enteredKeywordID = (int)(from d in this._keywordSource.Source where d.keyword.ToLower() == searchText.ToLower() select d.keywordID).FirstOrDefault();
if (0 == enteredKeywordID) {
    Keyword kw = new Keyword() { keyword = searchText };
    this._context.Keywords.Add(kw);
    this._context.SubmitChanges(KeywordsAddedCompleted, null);
}

The callback function iterates through the AddedEntities collection (of 1) and sets the enteredKeywordID value. It then sends out a message using MVVM-light messaging to call an API that uses the keyword search entered earlier. This API returns data that is later saved to my database, requiring the enteredKeywordID variable set here:
private void KeywordsAddedCompleted(SubmitOperation so)
{
    if (so.HasError)
    {
        so.MarkErrorAsHandled();
     }
     else
     {
         foreach (Keyword item in so.ChangeSet.AddedEntities) {
             enteredKeywordID = item.keywordID;
         }
        Messenger.Default.Send<string>(SearchText, "GenerateKeywords");
     }
  }

Is there a better way to do this?


text:
Q: How to go back to UiTabBar home page from UiTableViewController that is loaded upon button click from a button within the homepage tab? i have created a universal tabbed iOS application in Swift 2.0, the application has 3 tabs in the first tab, in the viewcontroller in storyboard i have placed a button upon which when pressed a UiTableView is loaded and it has a feature to add cell (a note taking feature embedded within the app), my issue is that once the UITableViewController is loaded i cannot go back to the previous page, its like this:
I have a TabBarController linked to a NavigationController which is linked to a HomepageViewController and When button is clicked, NavigationController linked to UITableView which shows ItemDetailViewController
My problem is that once i get to the UITableViewController i cannot go back to the home tab - HomeViewController
I have tried adding a UiBarButton to the top left of the UITableController and using poptorootviewcontroller , but it didnt work, any help will be appreciated.

A: According to my understanding, your tabbar controller is at the root of window. You can access it as self.window.rootviewcontroller. After that, you can use tabar.selectedIndex to switch tabs.


text:
Q: file preview and re-upload using gcanti/tcomb-form I followed File upload example and this example I can now upload the file to s3. but when it comes to editing or replacing that file how should I handle that.
const CustomFile = t.irreducible('File', x => x instanceof File);

// MyModel
const BusinessModel = t.struct({
  logo: t.maybe(CustomFile),
  name: t.String,
}, 'BusinessModel');

// options
const options = {
  fields: {
    logo: {
      type: 'file'
    }
  }
};

My response object is
{
  "name": "business name",
  "logo": {
    "url": "https://some.url.to/s3/logo.png",
    "large": {
      "url": "https://some.url.to/s3/logo_large.png"
    }
  }
}

So how do I get response logo to fit in BusinessModel such that it shows preview if file exists.
onChange it shows preview of new file
onSubmit uploads the newly selected file
is this something that I should be considering

A: class MyFileComponent extends t.form.Component {
  getTemplate() {
    return (locals) => {
      return (

          {
            getLabel({
              label: locals.label,
            })
          }

          { this.renderPreview(locals) }

              <input type="file" className="custom-file-input" accept="image/*" onChange={evt => locals.onChange(evt.target.files[0])} />

          { getError(locals) }
          { getHelp(locals) }

      );
    };
  }

  renderPreview(locals) {
    // your code
  }
}

This is what I did I'm yet to handle the errors highlighting but this works of course for single file upload.


text:
Q: Drawing the Bode Plot of a loop gain Below I have the loop gain and the Bode plot for it, however I do not understand the phase plot. Why does it start at -90 degrees instead of 90 degrees since we have a zero? Please explain.

A: Well, we have the following transfer function:
$$\mathcal{H}\left(\text{s}\right)=-\frac{\text{GLCs}}{\text{LCs}^2+\text{CRs}+1}\tag1$$
Now, in order to plot the the bode-diagram we need to use \$\text{s}=\text{j}\omega\$, where \$\text{j}^2=-1\$:
$$\underline{\mathcal{H}}\left(\text{j}\omega\right)=-\frac{\text{GLC}\text{j}\omega}{\text{LC}\left(\text{j}\omega\right)^2+\text{CR}\text{j}\omega+1}=\frac{\text{GLC}\omega\text{j}}{\text{LC}\omega^2-1-\text{CR}\omega\text{j}}\tag2$$
Now, the amplitude can be plot using:
$$\left|\underline{\mathcal{H}}\left(\text{j}\omega\right)\right|=\frac{\left|\text{GLC}\omega\text{j}\right|}{\left|\text{LC}\omega^2-1-\text{CR}\omega\text{j}\right|}=\frac{\text{GLC}\omega}{\sqrt{\left(\text{LC}\omega^2-1\right)^2+\left(\text{CR}\omega\right)^2}}\tag3$$
And for the phase we get (assuming that all the variables are positive and real):
$$\arg\left(\underline{\mathcal{H}}\left(\text{j}\omega\right)\right)=\arg\left(\frac{\text{GLC}\omega\text{j}}{\text{LC}\omega^2-1-\text{CR}\omega\text{j}}\right)=$$
$$\arg\left(\text{GLC}\omega\text{j}\right)-\arg\left(\text{LC}\omega^2-1-\text{CR}\omega\text{j}\right)=$$
$$\frac{\pi}{2}-\begin{cases}
0,\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\space\text{when}\space\text{LC}\omega^2-1=0\\
\\
\frac{3\pi}{2}+\arctan\left(\frac{\text{LC}\omega^2-1}{\text{CR}\omega}\right),\space\space\space\space\space\space\space\space\space\space\space\space\text{when}\space\text{LC}\omega^2-1>0\\
\\
\pi+\arctan\left(\frac{\text{CR}\omega}{\left|\text{LC}\omega^2-1\right|}\right),\space\space\space\space\space\space\space\space\space\space\space\space\text{when}\space\text{LC}\omega^2-1<0
\end{cases}\tag4$$

A: Because the plot is of -BA (minus sign included) I would have expected the phase plot to start at -180 as a result of the minus sign before almost immediately adding +90 from the +20dB/decade zero giving -90 during the rising slope. At the apex the rising slope levels off removing the 90 degrees of lead thereby reverting the phase back to -180 (as shown). Next the -20dB negative slope kicks in giving an extra 90 lag resulting in -270 in total. The double pole gives a change in slope of -40dB/decade changing the slope from +20dB/decade to -20dB/decade and the phase from -90 to -270. (With -180 of that coming from the minus in -BA). That is to say the double pole changes the slope by -40dB/decade and adds 180 degrees of phase lag.
When the minus is included in the loop gain (-BA) it means that the complete loop is taken into account including the inverting input on the difference amplifier which changes the Nyquist criteria to loop gain must be less than unity before the loop phase lag reaches -360 degrees. (instead of -180 degrees).


text:
Q: Can't Publish ASP.NET Project Because Of One Of My ASPX Files I wanted to publish my project with "PreCompile During Publish" option checked but I get this error:

Copying file VERYLONGDIRECTORY\P.aspx to obj\Release\AspnetCompileMerge\Source\VERYLONGDIRECTORY\P.aspx failed. Could not find a part of the path 'obj\Release\AspnetCompileMerge\Source\VERYLONGDIRECTORY\P.aspx'.

I deleted the file from the project and the publish succeeded. Then, re-added the ASPX file to the project and the error is popping up again. I excluded it from the project and it works. I need the ASPX file to be in my project, this is a bit weird...
What should I do?

A: Please tell me that the above exception was copied and pasted for this question?
Because, I could find a Typo in the exception which is given below:
Copying file VERYLONGDIRECTORY\P.aspx to obj\Release\AspnetCompileMerge\Source\VERYLONGDIRECTORY\P.aspx.aspx failed ,this line ends with dual P.aspx.aspx extension. This typo would be a reason if not then do check some links below.
I have provided some links related to your exception, If you have not already visited, then do check their are multiple solutions and you could find one.
IntelliSense keeps giving [Failure] Could not find a part of the path C:\TEMP
ASP.NET publish trying to copy a non-existant file

A: Try put the following in your publish profile (.pubxml)
<aspnetcompilemergeintermediateoutputpath>c:\temp</aspnetcompilemergeintermediateoutputpath>
This will change the temporary path where the project is built.
Windows has a max length of 260 characters for file path.


text:
Q: Evolution operator Please, what are the requirements, the Hamiltonian should satisfy before we can use the evolution operator:
$$U(t) =\exp\left[-~\mathrm i \int_0^t \mathcal{H}(t^\prime)~\mathrm dt^\prime\right]$$
Can it be applied with the following?
$$\mathcal {H}(t^\prime) =\epsilon (t^\prime) \sigma_z +\Delta(t^\prime) \sigma_x.$$
$\sigma_x $ and $\sigma_z$ are Pauli matrices ;  $\epsilon (t) $ and $\Delta(t) $ are real time-dependent parameters.

A: This formula can be used whenever you have a time dependent Hamiltonian provided the H's at different times commute.
For a particle with a magnetic moment moving in a magnetic field:

*

*If the magnetic field intensity is varying with time but is in a constant direction then the Hamiltonian will be proportional to a fixed Pauli matrix, so H's at different times will commute.

*If the magnetic field intensity is varying with time and the magnetic field direction is also varying with time then the Hamiltonian at different times will not commute.

If the Hamilonian at different times do not commute, you need to use the Dyson Series.

A: Yes if the exponential can be time ordered. ie
$$U(t) = \mathcal{T}\exp\left[-~\mathrm i\int_{0}^{t}\mathrm{d}t^\prime ~\mathcal{H}(t')\right]$$
or equivalently stated
$$\partial_t U(t) = - ~\mathrm i~ \mathcal{H}(t)U(t)\,.$$
As noted by Bruce Greetham, the time ordering has no effect, and can be dropped, only if $[\mathcal{H}(t),\mathcal{H}(t^\prime)]=0$, only in this (quite common) case is the form given by he OP correct.


text:
Q: How does the lack of partitions of unity affect the structure of analytic/holomorphic manifolds? The standard way to define integration on a smooth manifold is to use partitions of unity, to extend to the case where the form you're integrating isn't supported on just one coordinate patch. Of course, in the analytic/holomorphic case, we don't have partitions of unity. So how do we do integration?
Furthermore, how does this affect the space $\mathcal{T}(M)$  of analytic vector fields (analytic global sections of the tangent bundle)? The usual extension lemma for smooth sections of a vector bundle depends on partitions of unity, so there doesn't seem to be any reason you should always be able to find an nonzero analytic section. Does it ever happen that $\mathcal{T}(M) = 0$?
Also in that vein - I remember needing to use partitions of unity to prove in an exercise that the space of 1-forms $\mathcal{T}^*(M)$ is actually the dual $C^\infty(M)$ module $\, \text{Hom}(\mathcal{T}(M),C^\infty(M))$ - because given a map $\mathcal{T}(M) \to C^\infty(M)$, it seems like you need some kind of extension lemma to construct a 1-form that induces it. Does this fail in the analytic case?
I imagine the answer to the previous two questions will involve sheaves, but I don't quite know enough about sheaves to frame them in the appropriate sheaf-theoretic way. Maybe per this question, I should ask if this means the sheaves are not soft and the sheaf cohomology doesn't vanish?
And in general, any good references (or just explanations you care to give) on the major differences between the smooth and analytic cases? It seems like most differential geometry books pay almost no attention to the analytic case.

A: (1) A holomorphic manifold is also (or "can also be viewed as") a smooth manifold, and that lets you define integration.  To put it another way, you do have partitions of unity, just not holomorphic ones.
(2) Even before you get to tangent bundles, there are well-known cases where local things can't be patched globally.  For example, on the Riemann sphere, there are non-trivial holomorphic functions in neighborhoods of every point, but the only global holomorphic functions are the constants.  In the case of the tangent bundle, it seems to me (experts please edit if I mess this up) that there are no non-zero global tangent vector fields on Riemann surfaces of genus 2 or more, though of course there are such fields locally everywhere.
(3) You're right that this phenomenon (and related ones) are the beginning of sheaf cohomology.
(4) I won't try to answer your question about 1-forms being the dual of tangent vectors, since it seems to mix pointwise things (the space of 1-forms $T^*(X)$) with global things in a way that I don't understand.


text:
Q: Android Network provider, internet needed? I'm using network provider for location updates. Do I need to to have internet on my cell?
Here is my code
LocationMngr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationMngr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, inteval, 0, this);

A: I'm getting confused of seeing other's Answer. Then I searched a lot and get some idea about that. While searching only, I have learnt about new concept of A-GPS. I would like to share those things with you.
There are three location providers.
1. GPS Provider

2. Network Provider (AGPS, CellID, WiFi MACID)

3. Passive Provider.

Note: I refer this from this site. As you asked question related to network provider, I will share regarding to that.
Network provider, name itself says that it needs network connection. Refer this article. It need network or WIFI connection to proceed.
A-GPS
GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.
For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).
This particular kind of GPS is called Assisted GPS (AGPS).
Note: Even if phone supports it, and network does not then this does not work

A: No need for Internet for retrieving location (GPS or Network provider). Using Internet can speed up the process and giving you more accurate locations (when dealing with Network provider).

A: No, the GPS sensors are independent of connections to the internet, so you don't need to worry about internet connectivity if you just want to get your location via GPS.  I have a Nexus 10 which has a GPS sensor, and it works just fine when I'm roaming without internet connectivitiy.

A: no you don't need internet conection.but in some roms it may be some errors in conection.
in gps module you don't need internet but some ways you can use wifi for more performance in.such as google navigation services.


text:
Q: New to E4 (Styling UI with css). Met problems on set css to a child composite I'm a beginner of E4 and i've added CSS to my RCP application. The common widgets work fine.
I've heard of the E4 could use the components class name as the selector.
So i've written a child class named DateFilterComposite which is extended to Composite, and tried to add css to style this components. However it not woks. Could anyone give me some suggestion?
The code is
DateFilterComposite {
    background-color: rgb(227,230,235);
}

A: Class names in CSS start with a dot:
.DateFilterComposite {
    background-color: rgb(227,230,235);
}


text:
Q: Explain "There can be many keys (and their associated values) in each partition, but the records for any given key are all in a single partition" "There can be many keys (and their associated values) in each partition, but the records for any given key are all in a single partition." This is a line of a famous hadoop text book. I am not getting the entire meaning of the second part of it which says "but the records for any given key are all in a single partition." Is this mean that all the records for a single key should be in a single partition or something else.

A:
but the records for any given key are all in a single partition

If you have one key, the key and its associated value, must be on a single partition. Sometimes the value can be rather large. But this is a constraint on the size of a value. It must be small enough to fit on a single partition.
Note, there maybe other constants on both keys and values, depending on what you use for back-end storage, for example, a single key-value pair may be required to fit into the node's memory.


text:
Q: Concurrent API calls for enriching Panda dataframe I need to call an API to enrich some data in panda data frame.
The records are in huge number and I want to make it concurrent and fast
Adding sample code
def process(session, somevalue):
    url = "http://Api/toEnrich?id=%s"
    with session.get(url.replace('%s',somevalue), headers=headers) as response:
        result = ""
        if response.status_code !=200:
            return result
        responseData=response.json()
        if "payload" in responseData:
            payload = responseData['payload']
            result = responseData['payload']['data'][0]
    return result

async def start_async_process(objs):
   with requests.Session() as session:
      resp = await process(session,objs)
      return resp

 chunks = pd.read_sql_query(sqlquery, cnxn, chunksize=1000,params=[in])
      for chunk in chunks:
          chunk['enriched_data'] = await asyncio.gather(*[start_async_process(v) for v in chunk['input']])

Currently code is working. But the processing is slow. Please help me.
I am from Java house and not much into python :-)


text:
Q: How to run system() as administrator in PHP? I need to send some commands as system admin throught PHP system() function on Windows environment.
I know that it can be dangerous, but I need that.

A: I have solved this issue by using a toolkit named cpau
By using it I can exec command very simply:
cpau -u administrator -p PWD_HERE -LWP -ex "net user myuser mypwd /add"

To make this work I've needed to change my Administrator password in Computer Management > Users.
For those people saying "use runas"
I could not use runas because it prompts for a password and I can't pass it in the same command line.
PS: Remember to place cpau in PHP folder.


text:
Q: How to add a plone.registry record programatically I'm writing an upgrade step that adds a record to a registry that will be used on a control panel configlet.
I started by adding a profile with a registry.xml file on it but then I though there should be a way to accomplish this programatically to avoid the creation and registration of a GS profile just for this.
I read the documentation of plone.registtry and according to it, the value_type properties of List may only contain persistent fields, so I came out with this code:
from collective.cover import _
from collective.cover.config import DEFAULT_AVAILABLE_TILES
from collective.cover.config import PROJECTNAME
from plone.registry import field
from plone.registry import Record
from plone.registry.interfaces import IRegistry
from zope.component import getUtility

import logging

def register_available_tiles_record(context, logger=None):
    """Handler for upgrade step from 2 to 3; adds the 'available_tiles' record
    to the registry.
    """
    if logger is None:
        logger = logging.getLogger(PROJECTNAME)

    registry = getUtility(IRegistry)
    record = 'collective.cover.controlpanel.ICoverSettings.available_tiles'

    if record not in registry.records:
        available_tiles = field.List(
            title=_(u"Available tiles"),
            description=_(u"This tiles will be available for layout creation."),
            required=True,
            default=DEFAULT_AVAILABLE_TILES,
            value_type=field.Choice(
                vocabulary=u'collective.cover.EnabledTiles'),
        )

        registry.records[record] = Record(available_tiles)
        logger.info("'available_tiles' record was added to the registry")
    else:
        logger.info("'available_tiles' record already exists in the registry")

but when I run the handler, I'm getting the following error:
Error in test test_from_2_to_3 (collective.cover.tests.test_upgrades.UpgradeStepsTestCase)
Traceback (most recent call last):
  File "/home/hvelarde/buildout.python/parts/opt/lib/python2.7/unittest/case.py", line 327, in run
    testMethod()
  File "/home/hvelarde/collective/cover/src/collective/cover/tests/test_upgrades.py", line 35, in test_from_2_to_3
    register_available_tiles_record(self.portal)
  File "/home/hvelarde/collective/cover/src/collective/cover/upgrades.py", line 31, in register_available_tiles_record
    vocabulary=u'collective.cover.EnabledTiles'),
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_field.py", line 458, in __init__
    super(AbstractCollection, self).__init__(**kw)
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 306, in __init__
    super(MinMaxLen, self).__init__(**kw)
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 157, in __init__
    self.default = default
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 53, in __set__
    inst.validate(value)
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 182, in validate
    self._validate(value)
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_field.py", line 476, in _validate
    errors = _validate_sequence(self.value_type, value)
  File "/home/hvelarde/.buildout/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_field.py", line 438, in _validate_sequence
    value_type.validate(item)
AttributeError: 'InterfaceConstrainedProperty' object has no attribute 'validate'

what I'm doing wrong here?

A: seems to me this is a limitation/bug of plone.registry; I ended up with a normal registry registration on the upgrade step.
anybody interested can see it here: https://github.com/collective/collective.cover/commit/137211a84a575fc03fbb84e0cbd091bec85a6ab7


text:
Q: List with multiple indexes Given a generic List I would need some kind of index (in the database sense) that would allow me fast retrieval. The keys for this index would not be unique, so I can't use a dictionary. Here's what I have in mind: Given a class Foo { P1, P2, P3 } that may have data like this
{ "aaa", 111, "yes" }
{ "aaa", 112, "no" }
{ "bbb", 111, "no" }
{ "bbb", 220, "yes" }
{ "bbb", 220, "no" }
{ "ccc", 300, "yes" }

I would need to quickly access all the records where P1 is "bbb" (3rd,4th, and 5th) or all the ones where P2 is 111 (1st and 3rd). I could use a sorted List but if I need more than one way of sorting / indexing I would end up with duplicated lists.
Is there something built-in into the .NET framework or maybe an OS library that would do something like this? Thanks.
P.S. I mentioned "sorted List" with the idea that a sorted list will return / find an item much faster. I do not need the list to be necessarily sorted; I'm just looking for fast retrieval / finding.

A: I've never actually had a chance to use it, but you may try i4o.  Its supposed to provide indexes for in-memory objects for usage with Linq.  You specify the indexes for a class using either attributes or as part of constructing the indexer, then you create an IndexableCollection.
At that point, you just query the collection using Linq, and the indexes work behind the scenes to optomize the access patterns for the data.

A: One route would be to just use an embedded relational database a la SQLite (there's an ADO.NET binding here: http://sqlite.phxsoftware.com/)
Most data structures aren't going to meet your requirements unless you're willing to re-sort the list/whatever each time as you need a different ordering.

A: Don't ever forget this principle: Make it correct, make it clear, make it concise, make it fast. In that order. So, first code up the naive implementation:
static IEnumerable<T> GetByIndex<T>(
    List<T> list,
    Func<T, TIndex> func,
    TIndex key
) {
    return list.Where(x => func(x) == key);
}

Usage:
List<Test> tests = new List<Test>() {
            new Test { Name = "aaa", Value = 111, Valid = Valid.Yes },
            new Test { Name = "aaa", Value = 111, Valid = Valid.Yes },
            new Test { Name = "bbb", Value = 112, Valid = Valid.No },
            new Test { Name = "bbb", Value = 111, Valid = Valid.No },
            new Test { Name = "bbb", Value = 220, Valid = Valid.No },
            new Test { Name = "ccc", Value = 220, Valid = Valid.Yes }
};
IEnumerable<Test> lookup = GetByIndex(tests, x => x.Name, "bbb");

The above is correct, clear and concise. Almost surely it is fast enough for your purposes.
So, as far as making it fast you must first measure:

*

*Establish reasonable performance criterion.

*Establish a test-bed of real-world data.

*Profile the simple approach against the test-bed of real-world data. Note here that profiling includes deducing whether or not this functionality is a bottleneck in your application.

Then, if and only if this is not fast enough for you should you try to optimize. It wouldn't be too hard to implement an IndexedList<T> : ICollection<T> that would allow you to index off of various properties.
Here is a naive implementation that could get you started:
class IndexedList<T> : IEnumerable<T> {
    List<T> _list;
    Dictionary<string, Dictionary<object, List<T>>> _dictionary;
    Dictionary<string, Func<T, object>> _propertyDictionary;

    public IndexedList(IEnumerable<string> propertyNames) : this(propertyNames, new List<T>()) { }

    public IndexedList(IEnumerable<string> propertyNames, IEnumerable<T> source) {
        _list = new List<T>();
        _dictionary = new Dictionary<string, Dictionary<object, List<T>>>();
        _propertyDictionary = BuildPropertyDictionary(propertyNames);
        foreach (var item in source) {
            Add(item);
        }
    }

    static Dictionary<string, Func<T, object>> BuildPropertyDictionary(IEnumerable<string> keys) {
        var propertyDictionary = new Dictionary<string,Func<T,object>>();
        foreach (string key in keys) {
            ParameterExpression parameter = Expression.Parameter(typeof(T), "parameter");
            Expression property = Expression.Property(parameter, key);
            Expression converted = Expression.Convert(property, typeof(object));
            Func<T, object> func = Expression.Lambda<Func<T, object>>(converted, parameter).Compile();
            propertyDictionary.Add(key, func);
        }
        return propertyDictionary;
    }

    public void Add(T item) {
        _list.Add(item);
        foreach (var kvp in _propertyDictionary) {
            object key = kvp.Value(item);
            Dictionary<object, List<T>> propertyIndex;
            if (!_dictionary.TryGetValue(kvp.Key, out propertyIndex)) {
                propertyIndex = new Dictionary<object, List<T>>();
                _dictionary.Add(kvp.Key, propertyIndex);
            }
            List<T> list;
            if (!propertyIndex.TryGetValue(key, out list)) {
                list = new List<T>();
                propertyIndex.Add(key, list);
            }
            propertyIndex[key].Add(item);
        }
    }

    public IEnumerable<T> GetByIndex<TIndex>(string propertyName, TIndex index) {
        return _dictionary[propertyName][index];
    }

    public IEnumerator<T> GetEnumerator() {
        return _list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator() {
        return GetEnumerator();
    }
}

Usage:
List<Test> tests = new List<Test>() {
            new Test { Name = "aaa", Value = 111, Valid = Valid.Yes },
            new Test { Name = "aaa", Value = 111, Valid = Valid.Yes },
            new Test { Name = "bbb", Value = 112, Valid = Valid.No },
            new Test { Name = "bbb", Value = 111, Valid = Valid.No },
            new Test { Name = "bbb", Value = 220, Valid = Valid.No },
            new Test { Name = "ccc", Value = 220, Valid = Valid.Yes }
};
// build an IndexedList<Text> indexed by Name and Value
IndexedList<Test> indexed = new IndexedList<Test>(new List<string>() { "Name", "Value" }, tests);
// lookup where Name == "bbb"
foreach (var result in indexed.GetByIndex("Name", "bbb")) {
    Console.WriteLine(result.Value);
}

But see, the reason you don't do this unless the naive implementation is not already fast enough is because of the additional complexity you just added to your system. You just added new code to maintain, new code to test and might not gain anything if this isn't faster on your real-world data or is not a bottleneck of your application.

A: (Edited to elaborate on collection-based strategy)
There is no intrinsic structure in .NET for looking up using various indexes.  Here are two good strategies:
Option 1: LINQ, for flexibility and simplicity
For simplicity and a lot of other integrated options, create a List (or something else that implements IEnumerable) of custom types and use LINQ to do your on demand lookups.  Note that you could use anonymous types if that's convenient for you.  You can also have your data in an XML structure and still do all this.  You'll likely be able to get your data, do your lookups, and manipulate the results in a small amount of clear code.  In .Net 4.0 you can use parallel Ling (PLINQ) to effortlessly have this process take advantage of multi-core processing.
List<foo> bigFooList = new List<foo>
{
     new Foo {"aaa", 111, "yes"},
     new Foo {"aaa", 112, "no"},
     new Foo {"bbb", 111, "no"},
     new Foo {"bbb", 220, "yes"},
     new Foo {"bbb", 220, "no"},
     new Foo {"ccc", 300, "yes"}
};
var smallFooList = From f In bigFooList Where f.P2 = 220 Select f;

Option 2: Multiple collections, for indexed look-up power.
If you're doing a lot of lookups on a large set and need power, you can use multiple collections to achieve faster lookups.  The tricky part is your requirement that the index values can be duplicated.  Here are some strategies:

*

*Check out the Lookup class.  Create your List.  Then for each fields for which you want an indexed lookup, create a Lookup object.  They cannot be constructed, but are derived from your IEnumerable collection:
Lookup<string, foo> LookupP1 = (Lookup<string, foo>) fooList.ToLookup(f => f.P1, f => p)
See the link for syntax for retrieving your items.  Basically LookupP1 contains IGrouping objects for each unique value of P1, keyed on that P1 value.  You iterate through that object to get your matching items.  A key attribute of Lookup objects is that they are immutable; so each time you add/subtract from your fooList, you'll have to redo all your Lookup objects.  But if you seldom alter your fooList, this is the way to go.

*Create a Dictionary<T, List<foo>> for each field upon which you will need to search by index, where T is the type of that value.  So for your example we would create:
var FoosByP1 = new Dictionary<String,List<foo>>
var FoosByP2 = new Dictionary<Int32,List<foo>> etc.
Then add to FoosByP1, keyed on each unique P1 value, a List containing all the foo items where P1 has that value. (ex.  keyed by "aaa", a List containing all foo objects for which P1 is "aaa".)  Repeat for each Foo field.  Based on your data, FoosByP1You would contain 3 List objects, containing 2, 3 and 1 foo items respectively.  With this scheme you can then retrieve very quickly.  (A dictionary is basically a hash table).
The main catch is that your data would be duplicated in each of these dictionaries, which may or may not be a problem.  If Foo has 20 fields and you have many foo items, you can save memory by having a central dictionary with a numeric key and all your foo items, and the individual indexed dictionaries would instead be Dictionary<T, List<Int32>>, where the integer would be the index of a Foo item in your central dictionary.  This would save memory and still be quite fast.
Whether you have a central dictionary or not, building your Dictonaries will take some cpu cycles, but once you have them you'll be in great shape.  And use Linq to build your dictionaries!

A: You might want to consider something like Lucene.Net, an indexing and search library.  I don't know if this may be a more complex solution than you were looking for, but it would definitely meet your performance needs.

A: I know you said you couldn't use a Dictionary, but would the following work?
For your example data set:
{ "aaa", 111, "yes" }
{ "aaa", 112, "no"  }
{ "bbb", 111, "no"  }
{ "bbb", 220, "yes" }
{ "bbb", 220, "no"  }
{ "ccc", 300, "yes" }

You could use the following:
var p1Lookup = new Dictionary<string,int []>();
p1Lookup.Add( "aaa", new int [] {0, 1} );
p1Lookup.Add( "bbb", new int [] {2, 3, 4} );
p1Lookup.Add( "ccc", new int [] {5} );

var p2Lookup = new Dictionary<int,int []>();
p1Lookup.Add( 111, new int [] {0, 2} );
p1Lookup.Add( 112, new int [] {1} );
p1Lookup.Add( 220, new int [] {3, 4} );
p1Lookup.Add( 300, new int [] {5} );

var p3Lookup = new Dictionary<int,int []>();
p1Lookup.Add( "yes", new int [] {0, 3, 5} );
p1Lookup.Add(  "no", new int [] {1, 2, 4} );

Depending on the usage, you could build the look-up dictionaries just once

A: If you only need to iterate the list once, but search it many times, and change it very little (as DB indexes are best at). A dictionary would be very fast once built. My method doesn't create duplicates.
var indexDict = new Dictionary<string, List<int>>();

for(int ct = 0; ct < pList.length; ct++)
{
    var item = pList[ct];

    if (!indexDict.ContainsKey(item.toIndexBy))
    {
        indexDict.Add(item.toIndexBy, new List<int> { ct };
    }
    else
    {
        indexDict[item.toIndexBy].add(ct);
    }
}

Now you have a super fast lookup for the indexes.
So if you want "bbb"'s indexes you could do:
int bbbIndexes = indexDict["bbb"];

A: Why not use a HashSet to store the different instances of the Foo object (which will be unique) and then use a LINQ query to retrieve the ones that match the given criteria?
Something like:
var hash = new HashSet<Foo>
{
new Foo { P1 = "aaa", P2 = 111, P3 = "yes"},
new Foo { P1 = "aaa", P2 = 112, P3 = "no"},
new Foo { P1 = "bbb", P2 = 111, P3 = "no"},
new Foo { P1 = "bbb", P2 = 220, P3 = "yes"},
new Foo { P1 = "bbb", P2 = 220, P3 = "no"},
new Foo { P1 = "ccc", P2 = 300, P3 = "yes"},
};

var results = from match in hash
where match.P1 == "aaa"
select match;


text:
Q: centered div does not overflow correctly I have a centered div(inner) in another div(outer). If the inner div is bigger than the outer div i want to have scrollbars to scroll to the top or bottom of the element. Sadly I can't scroll to the top completely. I think this is caused by the transform:translate trick.

.outer {
    overflow: scroll;
    width:100%;
    height:100%;
    position:relative;
}

.inner {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);

    background-color:red;
    overflow:hidden;
}

/* normalize */
body,html{
  width:100%;
  height:100%;
  margin:0;
  padding:0;
}

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

I used inline-style for the width and height of the inner div because im changing this with js dynamically.
This question was asked before here. But noone unterstood what hes trying to do.

A: Maybe you should try auto instead of hidden and change your code acording to this one:

.outer {
  overflow: scroll;
  width: 100%;
  height: 100%;
  position: relative;
}

.inner {
  background-color: red;
  overflow: auto;
}

/* normalize */

body,
html {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

    Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
    sanctus est Lorem ipsum dolor sit amet.

I basically deleted your position property to make the inner div inherit it from the outer div. Plus I deleted your transform property since you don´t necessarily need it.
I hope this will help!

A:

.outer {
    overflow: scroll;
    width:100%;
    height:100%;
    position:relative;
}

.inner {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
    background-color:red;
    overflow:hidden;
}

/* normalize */
body,html{
  width:100%;
  height:100%;
  margin:0;
  padding:0;
}

  Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

Please remove the transform css because it is sending the content -50% out of box and you can use
left: 0;
right: 0;
margin: auto;

to center the position:absoute content you don't need to use left:50%


text:
Q: Terraform Vm Provision attached 2 NIC I am working on provisioning the new azure VM using terraform and attached 2 nic to that VM.
I am getting below error.
azurerm_virtual_machine.vm: compute.VirtualMachinesClient#CreateOrUpdate: Failure sending request: StatusCode=400 -- Original Error: Code="VirtualMachineMustHaveOneNetworkInterfaceAsPrimary" Message="Virtual machine AZLXSPTOPTFWTEST must have one network interface set as the primary." Details=[]

I have referred https://www.terraform.io/docs/providers/azurerm/r/network_interface.html this URL for creating NIC
This is my Terraform code.
resource "azurerm_resource_group" "main" {
  name     = "RG-EASTUS-FW-TEST"
  location = "eastus"
}

#create a virtual Network
resource "azurerm_virtual_network" "privatenetwork" {
    name = "VNET-EASTUS-FWTEST"
    address_space = ["10.100.0.0/16"]
    location = "${azurerm_resource_group.main.location}"
    resource_group_name = "${azurerm_resource_group.main.name}"

}
#create a subnet with externel virtual network

resource "azurerm_subnet" "external"{
    name = "SNET-FWTEST-OUT"
    virtual_network_name = "${azurerm_virtual_network.privatenetwork.name}"
    resource_group_name = "${azurerm_resource_group.main.name}"
    address_prefix = "10.100.10.0/24"

}

#Create a public IP address

resource "azurerm_public_ip" "public" {
    name = "PFTEST-PUBLIC"
    location = "${azurerm_resource_group.main.location}"
    resource_group_name = "${azurerm_resource_group.main.name}"
    allocation_method  = "Static"

}

# Create a Subnet within the Virtual Network
resource "azurerm_subnet" "internal" {
  name                 = "SNET-FWTEST-IN"
  virtual_network_name = "${azurerm_virtual_network.privatenetwork.name}"
  resource_group_name  = "${azurerm_resource_group.main.name}"
  address_prefix       = "10.100.11.0/24"

}

resource "azurerm_network_interface" "OUT" {
    name = "NIC-FWTEST-OUT"
    location = "${azurerm_resource_group.main.location}"
    resource_group_name = "${azurerm_resource_group.main.name}"
  #  network_security_group_id = "${azurerm_network_interface.main.id}"
    primary = "true"
    ip_configuration {

        name = "OUT"
        subnet_id = "${azurerm_subnet.external.id}"
        private_ip_address_allocation = "static"
        private_ip_address = "10.100.10.5"
        public_ip_address_id = "${azurerm_public_ip.public.id}"

    }

}

# Create a network interface for VMs and attach the PIP and the NSG
resource "azurerm_network_interface" "main" {
  name                      = "NIC-FWTEST-IN"
  location                  = "${azurerm_resource_group.main.location}"
  resource_group_name       = "${azurerm_resource_group.main.name}"
 # network_security_group_id = "${azurerm_network_security_group.main.id}"

  ip_configuration {
    name = "IN"
    subnet_id                     = "${azurerm_subnet.internal.id}"
    private_ip_address_allocation = "static"
    private_ip_address            = "10.100.11.5"
  }
}

# Create a new Virtual Machine based on the Golden Image
resource "azurerm_virtual_machine" "vm" {
  name                             = "AZLXSPTOPTFWTEST"
  location                         = "${azurerm_resource_group.main.location}"
  resource_group_name              = "${azurerm_resource_group.main.name}"
  network_interface_ids            = ["${azurerm_network_interface.OUT.id}","${azurerm_network_interface.main.id}"]
  vm_size                          = "Standard_DS12_v2"
  delete_os_disk_on_termination    = true
  delete_data_disks_on_termination = true

I am expecting result as provision azure VM with 2 nic.
Thanks In Advance

A: I got the solution as we need to specify the primary network interface id and add this to the network interface id. As well as we need to add in ipconfiguration while creating network interface.
Please refer below code.
ip_configuration {

        name = "OUT"
        subnet_id = "${azurerm_subnet.external.id}"
        primary  = true
        private_ip_address_allocation = "static"
        private_ip_address = "10.100.10.5"
        public_ip_address_id = "${azurerm_public_ip.public.id}"

    }

resource "azurerm_virtual_machine" "vm" {
  name                             = "AZLXSPTOPTFWTEST"
  location                         = "${azurerm_resource_group.main.location}"
  resource_group_name              = "${azurerm_resource_group.main.name}"
  network_interface_ids            = ["${azurerm_network_interface.main.id}","${azurerm_network_interface.OUT.id}"]
  primary_network_interface_id     = "${azurerm_network_interface.OUT.id}"
  vm_size                          = "Standard_DS12_v2"
  delete_os_disk_on_termination    = true
  delete_data_disks_on_termination = true


text:
Q: Do REST APIs require password and login at every request? Suppose I develop a social networking site and I decide that I want the core of the application to be completely REST'ed. A user logs in with a password. Now, my question is does every request require password and login pairs (assuming that you need to provide your identity) at the end of URL like www.site.com/index.php?p=pass&l=login? I would be a little nervous about asking for that at every request. I know that I am missing something… it can't be like that because anyone could snoop into packets and capture the password and login easily. I don't think having all requests done in HTTPS would make sense (I read it's taxing on resources).
So please fill in the missing part that I need to understand.

A: Typically, you make a call to a login method that will generate a token that can be reused in all the next requests.
My advice is to force the use of SSL on every request, if that is not possible you should probably request a secure login and generate a temporary token for that particular session (similarly to session IDs).
You can see how OAuth is being used by the Flickr API to provide authentication in the diagram below. In this scenario, a temporary token is used to ask for a permanent token and a token secret.

Taken from: http://www.flickr.com/services/api/auth.oauth.html#access_token

A: First off, unless you know that using SSL is too expensive for you, use SSL. Security comes before performance optimizations.
Now, about passing usernames and passwords: usually you have an "API access token" or the like. It's not actually the username/password, but when someone has it they're granted the ability to make API requests. These can have limited or unlimited validity as you like. You can even make the token a signature - the user signs the request with some key, and you validate the signature.
But yes, since each API request is independent of the last, you're going to either have to use HTTP Basic authentication or its equivalent, or pass the API token (or other signatory device) with every request.

A: Traditional session tracking rules apply to REST just like any other system. Your best bet is to do a login up front, then return to the client a token which they then pass to you on every request (be it in query string, a cookie, or what have you). The token indexes into some server-site datastore that contains all the appropriate session information -- and specifically the user's identity etc.


text:
Q: Adding a line of text to php code My wordpress theme has a button to turn breadcrumbs on or off.
I want to leave the breadcrumb turned off and place a line of text where the breadcrumb would display on all pages except the home page.
You can see the breadcrumb here: http://greenesrelease.com/what-is-it/
I see in the sub_page_header.php where the breadcrumb is called
if(!is_front_page() &&  ( get_option('rttheme_breadcrumb_menus') || get_option(THEMESLUG.'_show_search') )){
    $info_bar = TRUE;
}else{$info_bar = FALSE;}

A: There is a difference between the home page and the front page. Since the code uses is_front_page I assume that is what you want, but check the Codex for the difference.
I don't know how your theme works, but it looks like the theme rolls several things into the "info bar". The code you posted just checks to see if there is any reason to display that bar.
if (
  !is_front_page()                          // does not show on the front page
  && (                                      // shows if either
    get_option('rttheme_breadcrumb_menus')  //     there is a breadcrumb option saved
    || get_option(THEMESLUG.'_show_search') //     or a search option
  )
){
  $info_bar = TRUE;
} else {
  $info_bar = FALSE;
}

You might be able to hack those conditionals to get something close to what you want but because the "info bar" does several different things I don't know that you can alter that to get exactly what you want. I think that the thing you need to alter is the code that generates the "info bar" itself.
I am refering to an "info bar" because there is an $info_bar variable. Right now, that variable name is all I have to go on. You will need to look for something that uses that $info_bar variable.  I expect if will look something like...
if($info_bar) {
  // some code probably
  a_function_that_makes_the_infobar();
}

... but that is a guess. If you can find that function name then find the function itself...
a_function_that_makes_the_infobar() {
  // some code
}

... and edit the code into your question, I will revise the answer.


text:
Q: Keystore from digital signature e-token using java How to create the keystore from digital signature e-token? How crate the path of keystore? How to sign with the keystore in any document using java application?

A: Cryptographic hardware devices can usually be interfaced via PKCS#11 API. You will need PKCS#11 library (.dll on Windows or .so on Unix) acting as a "device driver" which gets usually installed along with the software provided by the device vendor (consult your e-token documentation for the exact library location). You have mentioned "keystore" in your question therefore I guess you are using JAVA language and you can use SunPKCS11 provider to access PKCS#11 compatible cryptographic store. Here is the quick sample:
// Create instance of SunPKCS11 provider
String pkcs11Config = "name=eToken\nlibrary=C:\\path\\to\\your\\pkcs11.dll";
java.io.ByteArrayInputStream pkcs11ConfigStream = new java.io.ByteArrayInputStream(pkcs11Config.getBytes());
sun.security.pkcs11.SunPKCS11 providerPKCS11 = new sun.security.pkcs11.SunPKCS11(pkcs11ConfigStream);
java.security.Security.addProvider(providerPKCS11);

// Get provider KeyStore and login with PIN
String pin = "11111111";
java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS11", providerPKCS11);
keyStore.load(null, pin.toCharArray());

// Enumerate items (certificates and private keys) in the KeyStore
java.util.Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
    String alias = aliases.nextElement();
    System.out.println(alias);
}


text:
Q: Why does chmod +w not give write permission to other(o) When I run chmod +w filename it doesn't give write permission to other, it just gives write permission to user and group.
After executing this command
chmod +w testfile.txt

running ls -l testfile.txt prints
-rw-rw-r-- 1 ravi ravi 20 Mar 10 18:09 testfile.txt

but in case of +r and +x it works properly.
I don't want to use chmod ugo+w filename.

A: Your specific situation
In your specific situation, we can guess that your current umask is 002 (this is a common default value) and this explains your surprise.
In that specific situation where umask value is 002 (all numbers octal).

*

*+r means ugo+r because 002 & 444 is 000, which lets all bits to be set

*+x means ugo+x because 002 & 111 is 000, which lets all bits to be set

*but +w means ug+w because 002 & 222 is 002, which prevents the "o" bit to be set.

Other examples

*

*With umask 022 +w would mean u+w.

*With umask 007 +rwx would mean ug+rwx.

*With umask 077 +rwx would mean u+rwx.

What would have matched your expectations
When you change umask to 000, by executing
umask 000

in your terminal, then
chmod +w file

will set permissions to ugo+w.
Side note
As suggested by ilkkachu, note that umask 000 doesn't mean that everybody can read and write all your files.
But umask 000 means everyone that has some kind of access to any user account on your machine (which may include programs running server services ofc) can read and write all the files you make with that mask active and don't change (if the containing chain of directories up to the root also allows them).

A: With:
chmod +<perms>

the perms are added to user, group and other but with the umask still applying. It makes sure the file is not granted more permission than a newly created file would.
If you want to add the perms to user, groups and other regardless of the umask, use
chmod a+<perms>

which is short for
chmod ugo+<perms>

A: You need to specify to whom you are giving the permissions to, such as other, by using chmod o+w testfile.txt


text:
Q: How can I increase other teams' transfer budgets? So basically in FIFA 14, my pro in career mode is too valuable to be sold to other teams because my value is super high and team transfer budgets are too low.  I don't want to be stuck in La Liga. I'm at Barcalona but the only team that seems to have enough money to spend is Real Madrid, is there a way to increase transfer budgets on other teams to be able to buy me or is my player stuck?

A: There is no way to increase other teams budget. You should try to get your player away from the club.
You should have thought this through. Though you can just wait till your contract has expired so people can get you for free. You can also ask your club if you can go out on a loan in the meanwhile or just ask them to put you on the transferlist so they sell you for probably less than they want to sell you. Though as a pro in career mode you should just sign short contracts if you're good enough to go to other clubs. Don't sign a 5 year contract.


text:
Q: How can I add multiple components to a vertically scrollable panel with different sizes So I have been trying to come up with a good layout manager that will enable me to put multiple components in a scrollable panel with different sizes. The only one I found was gridlayout, but it forces the same size.
here is the current code I have:
package main;

import java.awt.Dimension;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {

    public static void main(String[] args) {

        // Create and set up a frame window
        JFrame frame = new JFrame("Layout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Define the panel to hold the components
        JPanel panel = new JPanel(new GridLayout(0, 1, 0, 0));
        panel.setPreferredSize(new Dimension(500, 800));

        for (int i = 0; i < 20; i++) {
            JButton button = new JButton("Button " + i);
            button.setPreferredSize(new Dimension(50, 100 + (i * 10)));
            panel.add(button);
        }

        // Add the panel and set the window to be visible
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);

    }

}

I also do know about GridBagLayout, but I do want a layout that wouldn't require me to enter the numbers manually.

A:
I also do know about GridBagLayout, but I do want a layout that wouldn't require me to enter the numbers manually.

You can specify:
 constraint.gridWidth = GridBagConstraints.REMAINDER;

and each component will be placed on a new row.
Or you can use a BoxLayout, as I suggested in my comment, and not worry about constraints.
Read the tutorial. The constraints for the GridBagLayout are explained in more detail.


text:
Q: Finding RGB values from an jpeg image in R I am trying to find RGB values in R.
The jpeg images that I am using have an object with white background.
Like this one: http://www.wild-wonders.com/blog/wp-content/uploads/2009/11/nba_france_16.jpg
Right now, in order to just select the object, I have to trace each object manually (by plotting dots which makes the selection into a shape that will later be used to get the RGB values). Is there any tools or packages like magic wand tool in photoshop that will automatically select the white background?

A: Have a look at the functionality provided by the Bioconductor package EBImage, an image processing and analysis toolbox for R. To install the package use:
source("http://bioconductor.org/biocLite.R")
biocLite("EBImage")

The example below illustrates how to automatically extract an object from white background, and get its #rrggbb pixel values. I used a value of 0.95  for thresholding rather than 1.0 (corresponding to white pixels) because of the artifacts introduced by jpeg compression.
library(EBImage)

## load the array representing pixel intensities into R
img <- readImage("http://www.wild-wonders.com/blog/wp-content/uploads/2009/11/nba_france_16.jpg")

## convert to grayscale before thresholding
gray <- channel(img, "gray")

## create a mask separating objects from background
mask <- gray < 0.95

## label objects (connected sets of pixels)
obj <- bwlabel(mask)

## indices of pixels within the object
idx <- which(mask==1, arr.ind=TRUE)

## extract the red, green, and blue pixel intensities
rgb <- cbind(channel(img, "r")[idx],
             channel(img, "g")[idx],
             channel(img, "b")[idx])

## convert to #RRGGBB representation
rgb(rgb)


text:
Q: Azure B2B Integration Fails with Office 365 APIs In doing some more testing today, I am finding that when I get an access token for a user that has been added to a tenant via the Azure B2B feature, I cannot access the site content using the Office 365 APIs.
Is there any plan to enable this scenario by RTM for Azure B2B?  I'm finding more and more blocking scenarios like this where a user has been granted access to a resource, but access through the Office 365 APIs is not working.


text:
Q: pass argument to mysql connection string Below is my code (under file db.js)
function connection() {
  try {
    const mysql = require('mysql2');

    const pool = mysql.createPool({
      host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase",
      user: "user",
      password: "password",
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
    });

    const promisePool = pool.promise();

    return promisePool;
  } catch (error) {
    return console.log(`Could not connect - ${error}`);
  }
}

const pool = connection();

module.exports = {
  connection: async () => pool.getConnection(),
  execute: (...params) => pool.execute(...params)
};

And to use it, I simply add var db = require('./../db.js'); at the top of the files that requires it. Additionally, below is how I'd execute any sql statements
const myResult = await db.execute("Select COUNT(*) AS dataCount from teachers WHERE username = ?", [username]);

But now I need to separate my database according to countries. So my database would be named with mydatabase_ + the country code, for example mydatabase_my , mydatabase_jp, mydatabase_uk etc etc. So how do I pass the country code to the function connection() ?
I tried something like
function connection(country) {
  try {
    const mysql = require('mysql2');

    const pool = mysql.createPool({
      host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase_" + country,
      user: "user",
      password: "password",
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
    });

    const promisePool = pool.promise();

    return promisePool;
  } catch (error) {
    return console.log(`Could not connect - ${error}`);
  }
}

const pool = connection(country);

module.exports = {
  connection: async (country) => pool.getConnection(country),
  execute: (...params) => pool.execute(...params)
};

and at the calling page, I did
var db = require('./../db.js');
db.connection("my")

but for the above, I will get ReferenceError: country is not defined which refers to country at the line const pool = connection(country);

A: Here's how I did it:
const mysql = require('mysql2');

const pool = function(country){
  var mydb = mysql.createPool({
    host: "mydb.abcd1234.ap-southeast-1.rds.amazonaws.com",
      database: "mydatabase_" + country,
      user: "user",
      password: "password",
      connectionLimit: 11,
      waitForConnections: true,
      queueLimit: 0,
      namedPlaceholders: true
  });
  return mydb;
}

const promisePool = function(country){
  return pool(country).promise();
}

module.exports = {
  connection: async (country) => promisePool(country).getConnection(),
  execute: (country,...params) => promisePool(country).execute(...params)
};

And in the page that uses mysql will have something like this:
db.connection(country)
const myResult = await db.execute(country, "Select * from schools");