text:
Q: Ember JS Dynamically render template based on content in model I am trying to programmatically render different templates into a named outlet based on a specific value in my model.
Here are two JSBin examples:
This one shows the basic structure but the specific render code is commented out.
http://jsbin.com/OhegexO/1/
But when I try to use the renderTemplate method in my route it doesn't work
http://jsbin.com/OhegexO/2/
I see the following errors in my console
Error while loading route: TypeError {}

Uncaught TypeError: Cannot call method 'connectOutlet' of undefined

I can seem to figure this out. The use case is that I want to use different templates based on some parameter that will be in my model.

A: Admittedly I'm not very familiar with rendering into named outlets, but it appears it won't render into an outlet that hasn't been rendered yet.  That being said it's possible instead of doing it from renderTemplate, you could allow the product template to render normally (don't override renderTemplate), then render the edit form delayed, into the product template afterward (see 2nd jsbin).  That's a little awkward, so if you wanna hijack the renderTemplate for the sake of it, see this first jsbin.  They both involve waiting for the product template to render, then rendering it.
And I believe if you override the renderTemplate hook, it skips the default rendering, hence never rendering the product template.  After further investigation, this is true, if you super it, it works as well.  BTW this._super() says run the default implementation of this method as well.
http://jsbin.com/ujiKire/5/edit
Using setup controller:
http://jsbin.com/OvONejo/1/edit
  setupController: function(controller, model){
     var templateEditForm = model.get('editform');
     var templateInto = 'product';
     var templateOutlet = 'editform';

     console.log("render the [%s] form into the [%s] template, using the [%s] outlet",templateEditForm, templateInto, templateOutlet);

     // Why does this code not work

     var self = this;
     Ember.run.later(function(){
     self.render(templateEditForm, {   // the template to render
       into: 'product',                // the template to render into
       outlet: templateOutlet,              // the name of the outlet in that template
       controller: controller        // the controller to use for the template
     });
     },1);
   }


text:
Q: d3dcompiler.dll missing error with Need for Speed: Most Wanted 2012 on Windows 8 I installed Need for Speed: Most Wanted on my laptop but when I launch it it gives me a d3dcompiler.dll is missing error.
How can I fix this? The game has been reinstalled but still gives me the error!

A: Try downloading this version of DirectX from Microsoft and running it:  http://www.microsoft.com/en-us/download/details.aspx?id=35
Even though it only says it updates DX9, it also updates components in DX10 and DX11.  Running this fixed a very similar error message that I was getting.

A: Try and install to a different location.

A: you will need a file d3dcompiler.dll which will be available at dllfiles.com .but you will need to uninstall the game and paste tis file in System32 folder in c drive and reinstall it again

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to call url with basic authentication inside application I need to create an application (ASP.NET or WinForms or Windows Service, not sure) that needs to make a call to a url including username and password for basic authentication and have the url return a csv file.  I then need to use the csv file in the application.  I don't know how to do this.  How do I call the url in my app.  There can be no user interaction, it needs to be completely automated in the returning of the csv file.

A: Try something like this:
var webClient = new WebClient();
webClient.Credentials = new NetworkCredential("username", "password");
webClient.DownloadFile("http://someurl/file.csv", "c:\\file.csv");

A: Try out the System.Net.WebRequest class. Here is a page showing general usage:
http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx
You can swap out the assignment of the Credentials property with your own NetworkCredential object to pass a custom user name and password.
I actually handle the class a little differently than the example. I ensure that every class that is IDisposable is initialized in a using statement to avoid accidentally leaving unclaimed resources. This is especially important if your service will receive frequent or rapid traffic.
Edit:
If you're interested in a CSV parsing library, there are many you can find from any search. You might like the code from this CodeProject article. This library is flexible enough to handle properly-escaped multi-line fields.
Good luck!


text:
Q: coffeescript prime number generation I am trying to generate prime numbers like this:
generatePrimeNumbersBelowN = (n) ->
  for i in [2..n-1]
    isPrime = true
    for j in [2..i-1]
      isPrime = false if i % j == 0
      break if not isPrime
    console.log(i, "is Prime Number.") if isPrime

generatePrimeNumbersBelowN(100);

I am getting prime numbers from 3 to 97, inclusive. I am new to JavaScript/CoffeeScript, so please tell me what's happening to 2?
Here's the generated JS code:
var generatePrimeNumbersBelowN;

generatePrimeNumbersBelowN = function(n) {
  var i, isPrime, j, k, l, ref, ref1, results;
  results = [];
  for (i = k = 2, ref = n - 1; 2 <= ref ? k <= ref : k >= ref; i = 2 <= ref ? ++k : --k) {
    isPrime = true;
    for (j = l = 2, ref1 = i - 1; 2 <= ref1 ? l <= ref1 : l >= ref1; j = 2 <= ref1 ? ++l : --l) {
      if (i % j === 0) {
        isPrime = false;
      }
      if (!isPrime) {
        break;
      }
    }
    if (isPrime) {
      results.push(console.log(i, "is Prime Number."));
    } else {
      results.push(void 0);
    }
  }
  return results;
};

generatePrimeNumbersBelowN(100);

A:
generatePrimeNumbersBelowN = (n) ->
  for i in [2..n-1]
    isPrime = true
    for j in [2..i-1]
      isPrime = false if i % j == 0
      break if not isPrime
    console.log(i, "is Prime Number.") if isPrime

When i is 2, j ranges from 2 down to 1.  You then check i % j which is 2 % 1 which is zero and claim that 2 is not a prime.
Because for x in [b..a] delivers a downward loop from b to a, while loop construct solves this problem.
generatePrimeNumbersBelowN = (n) ->
  i = 2
  while i < n
    isPrime = true
    j = 2
    while j < i
      isPrime = false if i % j == 0
      break if not isPrime
      j++
    console.log(i, "is Prime Number.") if isPrime
    i++

generatePrimeNumbersBelowN(100);


text:
Q: Improve appearance of GTK apps in Plasma5 installed on top Ubuntu Gnome I've installed Ubuntu 18.04 then with tasksel, kubuntu-desktop full along with sddm.
Now most of the application in KDE look like this:

Plasma look on top and gnome border/colors below. How can I fix this?

A: The issue is the look of certain applications that have a GTK GUI within the KDE/Plasma desktop which is a Qt desktop. You surely have a lot of GTK applications because you also have the Gnome desktop and Ubuntu Gnome is your first system, Gnome being a GTK desktop.
Main GTK desktops are: Gnome, Cinnamon, Mate, Xfce, Pantheon (elementary), Budgie. Qt desktops are fewer: most popular are KDE/Plasma and LXQt (of Lubuntu 18.10).
Main GTK applications (that are hard to avoid even in a Qt desktop) are: Firefox, Chrome, Audacious, Rhythmbox, Synaptic, Skype etc. Main Qt applications (that are popular on all desktops) are: VLC, SMPlayer, Audacity, Qmmp, K3b etc.
The look of GTK applications within the KDE desktop can be greatly improved though, even if a lot of them will keep their "Gnome" (GTK) look, by installing GTK themes that fit the KDE look. There is a Breeze GTK theme for example.
sudo apt install breeze-gtk-theme

Plasma 5 has an appearance setting for GTK/Gnome applications:
Go to System Settings > Application style > Gnome Application Style and there set your GTK2 and GTK3 themes (select Breeze etc).
Note that GTK apps that need administrator rights usually do not follow those settings (which seems to be the case with the gdebi application in your image).

Beside the GTK-specific aspects of this problem, there are some Gnome-specific problems of appearance. As described here, "Starting with GNOME 3.10, some GNOME applications have switched to "header bars" or "client-side decorations". These CSD (client-side decorations) don't work properly in some desktop environments". These can be disabled by simply installing the gtk3-nocsd package. You have to see if you need that or not. I haven't seen much change in Kubuntu after that (but I don't have a lot of Gnome-specific programs and maybe none that uses CSD); and, if you still want to use Gnome in parallel and keep those decorations, installing "nocsd" is not a good idea I imagine.

If you prefer KDE/Plasma to Gnome you should install Kubuntu from scratch if possible and thus avoid a lot of problems. Both Gnome and Plasma5 are heavy desktops that come with a lot of dependencies and possible compatibility problems.


text:
Q: Access MessageResources from javascript/jQuery Does this remain the "only" way to localize a javascript/jquery text or is there another way to access the MessageResources from javascript/jQuery?

A: The technique described at that link is a generic way to access strings in a JavaScript scope. So the example is not the "only" way at all.
If your question is whether JavaScript or jQuery has a built-in method for handling localization/translation of message strings, then I suppose the answer is no. In order to access your message resources (which I assume are sitting in your back end, or in a file somewhere?) you will have to load them into your JavaScript scope somehow and access them in some meaningful way.
This could be coded any way you like, but there are a number of projects designed to standardize the approach. Take a look at 1i8next  It has jQuery integration too.


text:
Q: syncing CloudKit and iCloud I have an app which currently syncs via iCloud, so the user can use the app on multiple iOS devices and has the same data everywhere.
Now I'd like to switch to CloudKit; but how is this possible if the user e.g. only updates on one device? So it's the same user, one time with CloudKit, one time still with iCloud... I guess syncing isn't possible then if I get it right?

A: just check if there is data in the private container. If not, then migrate and sync the data from iCloud to CloudKit. Then if he opens the app on another device then the data is already migrated to CloudKit and you can just sync that data.


text:
Q: asyncstorage doesn't keep data I'm storing images in my app with asyncStorage, at first everything goes well, I store the images and am able to display them calling from storage. Now my problem is that the photos I stored don't stay in the storage forever, I am using expo in react-native and when I open my app like a week after having stored some photos, the displayed photos I stored are empty, but everything else I stored in my storage hasn't moved. Does anyone know why? And how I can fix this, allowing my photos to stay in storage?
Thanks!
Code :
In my render I have 2 touchable opacity :
        <TouchableOpacity onPress={this.snap}>
          <Text>CAPTURE PHOTO</Text>
        </TouchableOpacity>

        <TouchableOpacity onPress={() => this.savePhoto()} style={{marginRight: 40}}>
          <Text>SAVE PHOTO</Text>
        </TouchableOpacity>

snap() function :
snap = async () => {
  if (this.camera) {
    let photo = await this.camera.takePictureAsync()
    if (photo) {
      this.setState({ imageuri: photo.uri })
    }
  }
}

Savephoto() function :
savePhoto() {
   const { goBack } = this.props.navigation
   var todayDate = moment(new Date()).format('dddd DD MMMM YYYY HH:mm:ss')
   this._storeData("image:" + todayDate, this.state.imageuri)
   goBack()

}
And my store data function :
_storeData = async (name, data) => {
  try {
    await AsyncStorage.setItem('@MySuperStore:' + name, data)
  } catch (error) {
    console.log("failed storing data")
  }
}


text:
Q: I got error "The DELETE statement conflicted with the REFERENCE constraint" I tried to truncate a table with foreign keys and got the message:

"Cannot truncate table  because it is being referenced by a FOREIGN KEY constraint".

I read a lot of literature about the problem and thought that I found the solution by using delete
DELETE FROM table_name DBCC CHECKIDENT (table_name, RESEED, 0)

But I still got an error message:

"The DELETE statement conflicted with the REFERENCE constraint".

When I try to delete with Microsoft Management Studio and execute the previous query
DELETE FROM table_name DBCC CHECKIDENT (table_name, RESEED, 0)

it doesn't give an error and works properly. I want to delete all information from a table and add new into it, but I don't want to drop and create foreign keys.

A: The error means that you have data in other tables that references the data you are trying to delete.
You would need to either drop and recreate the constraints or delete the data that the Foreign Key references.
Suppose you have the following tables
dbo.Students
(
StudentId
StudentName
StudentTypeId
)

dbo.StudentTypes
(
StudentTypeId
StudentType
)

Suppose a Foreign Key constraint exists between the StudentTypeId column in StudentTypes and the StudentTypeId column in Students
If you try to delete all the data in StudentTypes an error will occur as the StudentTypeId column in Students reference the data in the StudentTypes table.
EDIT:
DELETE and TRUNCATE essentially do the same thing.  The only difference is that TRUNCATE does not save the changes in to the Log file.  Also you can't use a WHERE clause with TRUNCATE
AS to why you can run this in SSMS but not via your Application.  I really can't see this happening.  The FK constraint would still throw an error regardless of where the transaction originated from.

A: To DELETE, without changing the references, you should first delete or otherwise alter (in a manner suitable for your purposes) all relevant rows in other tables.
To TRUNCATE you must remove the references. TRUNCATE is a DDL statement (comparable to CREATE and DROP) not a DML statement (like INSERT and DELETE) and doesn't cause triggers, whether explicit or those associated with references and other constraints, to be fired. Because of this, the database could be put into an inconsistent state if TRUNCATE was allowed on tables with references. This was a rule when TRUNCATE was an extension to the standard used by some systems, and is mandated by the the standard, now that it has been added.

A: Have you considered applying ON DELETE CASCADE where relevant?

A: You are trying to delete a row that is referenced by another row (possibly in another table).
You need to delete that row first (or at least re-set its foreign key to something else), otherwise you'd end up with a row that references a non-existing row. The database forbids that.

A: In SQL server
go to the database diagram and choose relation properties
go to insert and update Specification column
make the delete rule set to null


text:
Q: override @spring.showErrors to show single error? hi guys
i am new to freemarker and not very familiar with it
and i need a little help in overriding the following code, to show only one error instead of list of errors for each field:
<#macro showErrors separator classOrStyle="">
    <#list spring.status.errorMessages as error>
    <#if classOrStyle == "">
    ${error}
    <#else>
    <#if classOrStyle?index_of(":") == -1><#assign attr="class"><#else><#assign attr="style"></#if>
    ${error}
    </#if>${separator}
    </#list>
</#macro>

A: You can show only the first error with the following macro:
<#macro showFirstError classOrStyle="">
    <#if (spring.status.errorMessages?has_content)>
        <#local error = spring.status.errorMessages[0] />
        <#if classOrStyle == "">
            ${error}
        <#else>
            <#if classOrStyle?index_of(":") == -1>
                <#local attr="class">
            <#else>
                <#local attr="style">
            </#if>
            ${error}
        </#if>
    </#if>
</#macro>


text:
Q: using Ajax with 3 consecutive dependable drop down lists peace be with you All, i am new to using Ajax , the issue is, i am having 3 drop down lists connected to a database, the first one is "name" and the second one is "age" and the third one is "country"! so, i have connected to the database, and retrieved data from it in the first list "name" and then using Ajax, i have successfully retrieved matching data after selecting any option of first list and put them into the second list called "age", the problem is that when i use a very exact same way with the second list called "age" to retrieve matching data into third list called "country" it doesn't work! so please help me cuz, i am using this example to learn Ajax and then apply on a larger real project! here is the code :- firstly, the home.php page:-
<?php
include "config.php";
?>
<html>
<head>
<script type="text/javascript">
function agematch() {
 if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest();
}
 else {
 xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
 }

xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {

  document.getElementById('age').innerHTML = xmlhttp.responseText;
  }

}
xmlhttp.open('GET', 'connection.inc.php?name='+document.ajax.name.value, true );
xmlhttp.send();

}

function countrymatch() {
 if (window.XMLHttpRequest) {
  xmlhttp = new XMLHttpRequest();
}
 else {
 xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
 }

xmlhttp.onreadystatechange = function() {
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {

  document.getElementById('country').innerHTML = xmlhttp.responseText;
  }

}
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
xmlhttp.send();

}

</script>
</head>
<body>
<form id="ajax" name="ajax" >
Choose your name : <select name="name" id="name" select="selected"  onchange="agematch();"> <option>  </option>
 <?php

   $query = "SELECT DISTINCT name FROM info";
   $result = mysql_query($query);
   while($row = mysql_fetch_array($result)){
   echo"<option  value ='".$row[0]."'> '".@$row[0]."'</option>";
                                }
 ?>
</select>
Age : <select id="age" name="age" onchange="countrymatch();">  </select>
country : <select id="country" name="country"> <option> </option> </select>

</form>
</body>
</html>

now, the page for first Ajax call :-
<?php
include "config.php";
echo " <option>  </option> " ;
if(isset( $_GET['name']) ) {
  @$name = $_GET['name'];
  }

  $query = "SELECT age FROM info WHERE name = '".@$name."' ";
  $result = mysql_query($query);
    while ($query_row = mysql_fetch_array($result)) {

      echo " <option  value ='".$query_row[0]."'> $query_row[0]</option> ";
      }

 ?>

Now, with the page for the second Ajax call for the third drop menu :-
<?php
include "config.php";

  if (isset( $_GET['age']) ) {
     @$age=$_GET['age'];
   }

  $query = "SELECT country FROM info WHERE name='".@$name."' AND age='".@$age."'  ";
  $result= mysql_query($query);
  while  ($query_row = mysql_fetch_array($result)) {

   echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";

  }

 ?>

so as you see, here is the code, and of course i am connected to the database through a page called "config.php", so i want you to help me to solve this issue and retrieve the data from database into the third drop down list "country". Thanks in Advance!

A: You are not passing name in the second call.
Replace
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
with
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value+'&name='+document.ajax.name.value, true );
Hope that helps.


text:
Q: Struts 2 action call loses the xwork i18n language setting I call a function "foo.action?request_locale=en" on my form. There is an xwork-validation on that page and I expect to get an validation error in the given language. What I get is a page in Finnish - my browser default language - and I expected one in English.
How it is possible to change the used language on a jsp page (that's where the request_locale comes from) so that the called action from my form will show up with that selected language and not the browser default one?
Some specs:
struts.xml has a line

because my actions are at fi.foo.action directory and i18n resources at fi/foo/package_en.properties and such files.
Validators are at barAction-foo-validation.xml kind of files at fi.foo.action folder.
fi = Finnish
My application works otherwise fine but this language setting is giving wrong language on screen.

A: It sounds like the i18n interceptor is not configured for your action's interceptor stack. The i18n interceptor is defined fourth in the defaultStack. Make sure you are not overriding the stack for your action. If it appears to be configured, then try setting a breakpoint in the intercept method of the I18nInterceptor to confirm that it is being invoked. Otherwise, what you have should work.


text: Q: netbeans 8.0.2 html preview I just installed netbeans 8.0.2 for an html/css/js project, and realized it doesn't have an included html preview function that allows me to see what my webpage looks like as I develop it.  To view the page I need to save the file and open it in a dedicated browser.  I found a plugin for an older version of netbeans (7.0.4) that allows this functionality, but I don't believe it will work for this newer version.  Any solutions?   Should I just abandon netbeans and use a different IDE?


text:
Q: parallel programming and datasets with datatables I have a taskfactory application that generates new tasks to complete processing using multiple classes. Everything seems to work fine with occasional IOEXception errors at times. The latest errors involve the use of datasets and datatables where in each process that runs, I access a database table to extract 100000 ids which I use in my process. In doing so I add a datatable to the dataset and use the datatable in a different portion of the process.
When creating a new task I assumed that it would generate its own datatable and dataset in memory as a new process involves a new instance of the classes involved and it should be threadsafe. However I get the error
' Datatable already belongs in this dataset'
Now after researching I found that you cannot create multiple datatables in the same set. So is there anyway around this or should I consider a different data structure like perhaps using a list?
Public class tprocess
....
 ....
   public shared dsCountry as new dataset
   public shared dstable as new datatable

  public shared sub main()

      do_processing()
 end sub

  public shared do_processing()

      try
        dscountry.tables.add(dsTable)
        ...' sql steps to get data with sqldatareader

A: It sounds like you're sharing the same DataSet and creating new DataTable instances in that one DS. Is that the case?
It can be tricky. For example, this would use the same instance of a DataSet:
void Method()
{
   DataSet ds = null;

   Task t1 = Task.Factory.StartNew(delegate {ds = new DataSet(); /*work with ds */});
   Task t2 = Task.Factory.StartNew(delegate {ds = new DataSet(); /*work with ds */});
}


text:
Q: AVPlayerItem.loadedTimeRanges notifications aren't working with custom AVAssetResourceLoaderDelegate I use AVAssetResourceLoaderDelegate for video caching but the video plays after it will be fully downloaded.
I add KVO observer to loadedTimeRanges property:
[self.player.currentItem addObserver:self
                          forKeyPath:@"loadedTimeRanges"
                             options:NSKeyValueObservingOptionNew
                             context:nil];

Check ranges and start playing:
- (void)checkRanges {
  if (self.player.currentItem.asset) {
    CMTimeRange loadedTimeRange =
    [[self.player.currentItem.loadedTimeRanges firstObject] CMTimeRangeValue];
    Float64 videoDuration = CMTimeGetSeconds(self.player.currentItem.asset.duration);
    Float64 buffered = CMTimeGetSeconds(loadedTimeRange.duration);
    Float64 percent = buffered / videoDuration;
    if (percent > 0.2) {
      [self.player play];
    }
  }
}

But notifications aren't working, for some reason, I get a notification when the video is almost downloaded.
Video downloading is implemented by using AVAssetResourceLoaderDelegate that allow use cache within video playing.
The downloading is initialized in the method AVAssetResourceLoaderDelegate:
func resourceLoader(_ resourceLoader: AVAssetResourceLoader,
                  shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
 if let resourceURL = loadingRequest.request.url, resourceURL.isVCSVideoScheme(),
   let originalURL = resourceURL.vcsRemoteVideoURL() {
   let assetLoader: VideoAssetLoader
   if let loader = assetLoaderForRequest(loadingRequest) {
     assetLoader = loader
   } else {
     assetLoader = VideoAssetLoader(url: originalURL)
     assetLoader.delegate = self
     assetLoaders[keyForAssetLoaderWithURL(resourceURL)] = assetLoader
   }
   assetLoader.addRequest(loadingRequest)
   return true
 }
 return false
}

VideoAssetLoader receives a HEAD request with file information and then updates AVAssetResourceLoadingRequest:
private func fillInContentInformation(_ contentInformationRequest: AVAssetResourceLoadingContentInformationRequest?) {
  guard let contentInformationRequest = contentInformationRequest,
    let contentInformation = self.contentInformation else {
      return
  }
  contentInformationRequest.isByteRangeAccessSupported = contentInformation.byteRangeAccessSupported
  contentInformationRequest.contentType = contentInformation.contentType
  contentInformationRequest.contentLength = Int64(contentInformation.contentLength)
}

Then VideoAssetLoader downloads requested range of bytes and then updates AVAssetResourceLoadingDataRequest:
private func processPendingRequests() {
  for request in pendingRequests {
    fillInContentInformation(request.contentInformationRequest)
    let didRespondCompletely = respondWithDataForRequest(request.dataRequest)
    if didRespondCompletely {
      request.finishLoading()
    }
  }
  pendingRequests = pendingRequests.filter({ !$0.isFinished })
}

private func respondWithDataForRequest(_ dataRequest: AVAssetResourceLoadingDataRequest?) -> Bool {
  guard let dataRequest = dataRequest, let downloadTask = videoDownloadTask else {
    return false
  }
  var startOffset: UInt64 = UInt64(dataRequest.requestedOffset)
  if dataRequest.currentOffset != 0 {
    startOffset = UInt64(dataRequest.currentOffset)
  }
  let numberOfBytesToRespondWith = UInt64(dataRequest.requestedLength)
  var didRespondFully = false
  if let data = downloadTask.readCachedDataWithOffset(startOffset, lenght: numberOfBytesToRespondWith) {
    dataRequest.respond(with: data)
    didRespondFully = data.count >= dataRequest.requestedLength
  }
  return didRespondFully
}

Unfortunately, the video isn't playing while it won't be completely downloaded  (AVAssetResourceLoadingRequest.finishLoading()), also  not getting notification loadedTimeRanges.
Does anyone have experience with this to point me toward an area where I may be doing something wrong?
Thanks!


text:
Q: webpack require.ensure first parameter use What is the use of first parameter of webpack require.ensure first parameter?
https://webpack.github.io/docs/code-splitting.html
require.ensure(dependencies, callback)

I tried to let the first parameter filled or empty like:
require.ensure(['./module'], function() {  //filled first param

require.ensure([], function() {  //empty first param
  let module = require('./module');
  $ocLazyLoad.load([{
    name: module.default,
  }]);
});

Both are working. So what is the use of the first parameter?
There is also a require.include function in the documentation which I do not understand the use case of this function. Can anyone explain it too?

A: These functions have to do with Code Splitting, which allows some sections of code to be bundled separate from the main code, and loaded and run later, while the code is running.
Code Sample 1:
require.ensure(['./module'], function() {  //filled first param

The first parameter is an array of modules to ensure are loaded before running the callback. If ./module has not been loaded in one of the bundles yet, it will load the chunk this module is contained in a new HTTP request, then call the callback function.
To use Webpack's example:
require.ensure(["module-a", "module-b"], function(require) {
    var a = require("module-a");
    // ...
});

module-a and module-b can now be split into different files, and the callback function will not run until they have loaded.
Code Sample 2:
require.ensure([], function() {  //empty first param
  let module = require('./module');
  $ocLazyLoad.load([{
    name: module.default,
  }]);
});

Here require.ensure defines a split point. As it does not have any dependencies in the array, it does not itself load any modules. However, require statements inside the callback will still be dynamically loaded through the magic of webpack and ./module will be bundled in a separate file.
require.include

There is also a require.include function in the documentation which I do not understand the use case of this function. Can anyone explain it too?

require.include can be used to ensure a module is bundled, even if it is not require-ed. Normally if a module is not require-ed, it will not be bundled at all. This can be used to force it to include the module, even it not requir-ed in the bundle itself.

A: The first parameter is rarely useful. To learn why it is there and causes confusion, please see my another answer.
Comply with the spec
One use case for the first parameter could be to specify all dependencies for clarity and to comply with the spec. But that's completely optional.
Add modules to chunks to make the chunks similar
Consider you have two split points in different parts of an app. The first split point depends on module a, the second depends on modules a and b.
To eliminate the risk of downloading a twice, you could decide to place both modules into a single chunk:
// First split point
require.ensure(['b'], (require) => {
  require('a');
});

Pull modules into parent chunks
Consider the following code splitting scenario:
require.ensure([], (require) => {
  ...
  require.ensure([], (require) => {
    require('a');
    require('b');
  });

  require.ensure([], (require) => {
    require('a');
    require('c');
  });
  ...
});

In this case, module a will end up in both nested chunks. If at least one of the nested chunks is frequently loaded, you could decide to move a into the parent chunk:
require.ensure(['a'], (require) => {
  ...

Add modules to chunks with require.include
Consider the previous example. There is another way to pull a into the parent chunk:
require.ensure([], (require) => {
  require.include('a');
  ...

In this particular example, both solutions are equivalent and there is no advantage in using require.include. However, if you don't have access to the split point's code, parent chunk is an entry chunk or you use the modern import() syntax, require.include is your only choice.
It is possible to pull modules into chunks using synchronous require or import. The advantage of require.include is that it only loads modules and doesn't evaluate them. This could be useful to defer modules' evaluation if it is expensive or depends on the application state, e.g., requires polyfills to be loaded, DOM nodes to be present, etc.


text:
Q: MYSQL wrong results output I have 3 tables with the following data:
1st table called connections where connections.username1 is the one who follows and connections.username2 is the one who is followed.
It has the following rows:
connections.username1 | connections.username2
      mikha           |          guy
      guy             |          maricela
      maricela        |          guy

2nd table called questions. It has a column for for the asker called questions.asker_username and another for the one who receives the question called questions.target_username. When the asker is called "sys.tem" and the target called "every.one", it's considered a global question and could be answered by all members.
Anonymous users could ask and their ip is recorded as the asker_username.
It has the following rows:
questions.id | questions.asker_username | questions.target_username | questions.question
  1          |      mikha               |       guy                 | what's your name?
  2          |      mikha               |       maricela            | What's your age?
  3          |      guy                 |       mikha               | what's your name?
  4          |      maricela            |       guy                 | favorite food?
  5          |      xx.xx.xxx.xx        |       mikha               | favorite pet?
  6          |      xx.xx.xxx.xx        |       guy                 | first name?
  7          |      xx.xx.xxx.xx        |       maricela            | first name?
  8          |      sys.tem             |       every.one           | what's ur name?
  9          |      sys.tem             |       every.one           | favorite movie?
 10          |      sys.tem             |       every.one           | favorite game?

The 3rd table is called answers. The id in the answers table is the same as the question id. This table has a column for id and username and answer.
answers.id  |  answers.username | answers.answer
   1        |       guy         | my name is guy
   2        |     maricela      | my name is maricela
   3        |       mikha       | my name is mikha
   4        |       guy         | pizza
   8        |       guy         | guy is my name
   8        |       maricela    | maricela is my name
   9        |       maricela    | avatar

I want a query which combines the following conditions related to "mikha" and the people he follows:
1) questions.asker_username is NOT "mikha"
2)  questions.target_username is either "mikha" or any of the users he follows.
3) If questions.target_username equals to "every.one" and answered by "mikha", show the question.
4) If questions.target_username equals to "every.one" and answered by any of the people whom "mikha" follows, show the question and its answer. If no answer by the users whom "mikha" follow, don't show the question.
5) If questions.target_username equals to "every.one" and is not answered by any one at all, show the question once.
6) If questions.target_username equals to "every.one" and is not answered by "mikha" and not answered by any of the people he follows, show the question only once.
I use the following query:
SELECT questions.id,answers.id,questions.asker_username,questions.target_username,
    answers.username,questions.question,answers.answer
FROM questions
    LEFT JOIN answers ON (questions.id = answers.id)
    LEFT JOIN connections ON connections.username1 = 'mikha'
        AND (questions.target_username = connections.username2
            OR questions.asker_username = connections.username2
            OR connections.username2 = answers.username)
WHERE questions.asker_username <> 'mikha'
    AND (questions.target_username = 'mikha'
        OR questions.target_username = connections.username2
        OR (questions.target_username = 'every.one'
            AND (answers.username = 'mikha'
                OR answers.username = connections.username2
                OR answers.username IS NULL)
            )
        )
GROUP BY questions.id,answers.username

The result I expect:
questions.id | answers.id | questions.asker_username | questions.target_username | answers.username | questions.question | answers.answer
    3        |      3     |        guy               |          mikha            |    mikha         | what's your name?  | my name is mikha
    4        |      4     |        maricela          |          guy              |    guy           | favorite food?     | pizza
    5        |      5     |        xx.xx.xxx.xx      |          mikha            |    NULL          | favorite pet?      | NULL
    6        |      6     |        xx.xx.xxx.xx      |          guy              |    NULL          | first name?        | NULL
    8        |      8     |        sys.tem           |         every.one         |    NULL          | what's ur name?    | NULL
    8        |      8     |        sys.tem           |         every.one         |    guy           | what's ur name?    | guy is my name
    9        |      9     |        sys.tem           |         every.one         |    NULL          | favorite movie?    | NULL
    10       |      10    |        sys.tem           |         every.one         |    NULL          | favorite game?     | NULL

The result I actually get:
 questions.id | answers.id | questions.asker_username | questions.target_username | answers.username | questions.question | answers.answer
    3        |      3     |        guy               |          mikha            |    mikha         | what's your name?  | my name is mikha
    4        |      4     |        maricela          |          guy              |    guy           | favorite food?     | pizza
    5        |      5     |        xx.xx.xxx.xx      |          mikha            |    NULL          | favorite pet?      | NULL
    6        |      6     |        xx.xx.xxx.xx      |          guy              |    NULL          | first name?        | NULL
    8        |      8     |        sys.tem           |         every.one         |    guy           | what's ur name?    | guy is my name
    10       |      10    |        sys.tem           |         every.one         |    NULL          | favorite game?     | NULL

I built a scheme on http://sqlfiddle.com/#!2/29929e/1 to show you the results I actually get
Thanks :)

A: OK, lets start from the simplest one (Your first rule):
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
GROUP BY q.id,a.username

Now lets add Your second rule - now more complexity is added...
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
    AND q.target_username = 'mikha'
        OR q.target_username IN (
            SELECT username2
            FROM connections
            WHERE username1 = 'mikha'
        )
GROUP BY q.id,a.username

Now the third rule (for everyone answered by mikha):
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
    AND q.target_username = 'mikha'
        OR q.target_username IN (
            SELECT username2
            FROM connections
            WHERE username1 = 'mikha'
        )
        OR (q.target_username = 'every.one' AND a.username = 'mikha')
GROUP BY q.id,a.username

Now for the fourth rule:
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
    AND q.target_username = 'mikha'
        OR q.target_username IN (
            SELECT username2
            FROM connections
            WHERE username1 = 'mikha'
        )
        OR (q.target_username = 'every.one' AND a.username = 'mikha')
        OR (q.target_username = 'every.one' AND a.username IN (
            SELECT username2
            FROM connections
                INNER JOIN answers ON answers.username = connections.username2
                    AND answers.answers IS NOT NULL
            WHERE username1 = 'mikha'
        ))
GROUP BY q.id,a.username

Fifth rule (Jesus!):
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
    AND q.target_username = 'mikha'
        OR q.target_username IN (
            SELECT username2
            FROM connections
            WHERE username1 = 'mikha'
        )
        OR (q.target_username = 'every.one' AND a.username = 'mikha')
        OR (q.target_username = 'every.one' AND a.username IN (
            SELECT username2
            FROM connections
                INNER JOIN answers ON answers.username = connections.username2
                    AND answers.answers IS NOT NULL
            WHERE username1 = 'mikha'
        ))
        OR (q.target_username = 'every.one' AND a.answer IS NULL)
GROUP BY q.id,a.username

And for the last one:
SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer
FROM questions q
    LEFT JOIN answers a ON q.id = a.id
WHERE q.asker_username <> 'mikha'
    AND q.target_username = 'mikha'
        OR q.target_username IN (
            SELECT username2
            FROM connections
            WHERE username1 = 'mikha'
        )
        OR (q.target_username = 'every.one' AND a.username = 'mikha')
        OR (q.target_username = 'every.one' AND a.username IN (
            SELECT username2
            FROM connections
                INNER JOIN answers ON answers.username = connections.username2
                    AND answers.answers IS NOT NULL
            WHERE username1 = 'mikha'
        ))
        OR (q.target_username = 'every.one' AND a.answer IS NULL)
        OR (q.target_username = 'every.one' AND a.username NOT IN (
            SELECT username2
            FROM connections
                INNER JOIN answers ON answers.username = connections.username2
                    AND answers.answers IS NOT NULL
            WHERE username1 = 'mikha'
        ))
GROUP BY q.id,a.username

I think that rule 4 and rule 6 are kinda against each other (contradicting could be said) and when used in one query it would have the same effect as if omitted...
I didn't test any of the queries but I believe they work.

A: The problem is that - in some circumstances - you want to show a question twice when only one matching answer exists. I quote:

So, i want to show it only once for "mikha" whether it's answered or not and show it again each time it's answered by any of the people "mikha" follows

This duplication makes things pretty hard.
I tried to solve that with a UNION and it seems to work. However, I still haven't fully understood your requirements...
Anyway, here we go:
select * from
(
  select
    q.id as q_id, a.id as a_id, q.asker_username,
    q.target_username, a.username, q.question, a.answer
  from
    questions q
    left outer join answers a on q.id = a.id
  where
    q.asker_username <> 'mikha'
    and
    (
      q.target_username = 'mikha'
      or q.target_username in
         (select username2 from connections where username1 = 'mikha')
      or
      (
        q.target_username = 'every.one'
        and
        (
          a.username = 'mikha'
          or a.username in
             (select username2 from connections where username1 = 'mikha')
          or a.id is null
        )
      )
    )
  union
  select
    q.id as q_id, NULL as a_id, q.asker_username,
    q.target_username, NULL, q.question, NULL
  from
    questions q
  where
    q.asker_username <> 'mikha'
    and q.target_username = 'every.one'
    and not exists (select id
                    from answers
                    where
                      id = q.id
                      and username = 'mikha'
                    )
) r
order by q_id;

Test it live:
With answer from mikha for question 8
Without answer from mikha for question 8

A: I would suggest that one of the main issues with your starting point is that you need to join your connections table twice - once for answers and once for questions.
The code below gives inline comments on what it's doing. I would also agree with other answers in suggesting that numeric id fields would be better for comparisons - and I would also advise putting a unique rowid field on the answers table (better still, change id to question_id and then make id the unique field.
SELECT DISTINCT q.id,a.id,q.asker_username,q.target_username,a.username,q.question,a.answer
FROM questions q
  /* Answers */
  LEFT JOIN answers a ON (q.id=a.id)
  /* connection entries where the person being followed is the target */
  LEFT JOIN (SELECT username2 FROM connections WHERE username1='mikha') c_q
    ON c_q.username2=q.target_username
  /* connection entries where the person being followed answered the question */
  LEFT JOIN (SELECT username2 FROM connections WHERE username1='mikha') c_a
    ON c_a.username2=a.username
  /* Own answers */
  LEFT JOIN (SELECT id FROM answers WHERE username='mikha') a_own
    ON (q.id=a_own.id)
  WHERE
  /* Asker not mikha, target is mikha or followed user - rules 1,2 */
  (q.asker_username <> 'mikha'
  AND (q.target_username='mikha' OR c_q.username2 IS NOT NULL))
  OR
  /* sys.tem/every.one, answered by mikha - rule 3 */
  (q.target_username='every.one' AND a.username='mikha')
  OR
  /* Rules 4, 5 & 6 combine to give "show the answer at least once, and once for every followed user who answered" - here we select any every.one messages where mikha didn't answer and nor did the people he follows */
  (q.target_username='every.one' AND a_own.id IS NULL AND c_a.username2 IS NULL);

It doesn't give you two rows for question 8, but I couldn't really work out why you wanted that. The issue there is that it's not clear which of your rules are additive and which are combinatory. If you can explain which rules should "add" a row rather than just providing another reason to show a row, maybe we can get you that extra row for question 8 too.


text:
Q: Changing passwords from existing database in laravel 4 I have an existing mysql database with a column of encrypted passwords using:
crypt($password, "ab");

I would like to change all those current passwords, so that Laravel 4 will recognize them and not fail authentication. How would I got about doing that?

A: You can make a new column, new_password for example, when users log in, then first check the passwords against the old encryption column, if it matches: hash the password with Laravel and  put them in the new_password column. After a while you can remove the old password column.


text:
Q: Array as a list of matrices? I would like to have an array as a list of matrices but keep getting the error "Extra }, or forgotten \right.". As an example, I have the following:
\begin{align*}
    \mathcal{X} = \left[ \left[
    \begin{bmatrix}
        5 & 1 & 4 & 5 \\
        1 & 1 & 1 & 4 \\
        5 & 3 & 1 & 4
    \end{bmatrix},
    \begin{bmatrix}
        5 & 3 & 4 & 4 \\
        2 & 5 & 3 & 4 \\
        2 & 2 & 4 & 4
    \end{bmatrix} \right], \left[
    \begin{bmatrix}
        2 & 3 & 1 & 2 \\
        1 & 5 & 4 & 2 \\
        3 & 4 & 5 & 3
    \end{bmatrix},
    \begin{bmatrix}
        2 & 3 & 1 & 4 \\
        4 & 4 & 2 & 1 \\
        4 & 1 & 1 & 1
    \end{bmatrix} \right], \\ \left[
    \begin{bmatrix}
        5 & 5 & 4 & 3 \\
        5 & 1 & 4 & 2 \\
        1 & 2 & 1 & 2
    \end{bmatrix},
    \begin{bmatrix}
        5 & 1 & 4 & 1 \\
        3 & 1 & 5 & 4 \\
        5 & 4 & 2 & 3
\end{bmatrix} \right] \right]
\end{align*}

but the final bracket will not be printed on the screen. This is shown here

Is there a way of making the bracket appear or better yet, doing this in a more organized way? I have tried \Biggr[ but the bracket is not of the same size. Likewise I have tried creating more matrices but has similarly not worked. Thanks.

A: \left and \right cannot straddle two lines in an alignment display.
In this case you can match the opening \left[ with \right. and do similarly in the second line.
\documentclass{article}
\usepackage{amsmath}
\usepackage{showframe}% just to see the page margins

\begin{document}

\begin{align*}
\mathcal{X} =
% outer
\left[
  \left[
    \begin{bmatrix}
        5 & 1 & 4 & 5 \\
        1 & 1 & 1 & 4 \\
        5 & 3 & 1 & 4
    \end{bmatrix},
    \begin{bmatrix}
        5 & 3 & 4 & 4 \\
        2 & 5 & 3 & 4 \\
        2 & 2 & 4 & 4
    \end{bmatrix}
  \right],
  \left[
    \begin{bmatrix}
        2 & 3 & 1 & 2 \\
        1 & 5 & 4 & 2 \\
        3 & 4 & 5 & 3
    \end{bmatrix},
    \begin{bmatrix}
        2 & 3 & 1 & 4 \\
        4 & 4 & 2 & 1 \\
        4 & 1 & 1 & 1
    \end{bmatrix}
  \right],
\right. % match with \left[
 \\
\left.
  \left[
    \begin{bmatrix}
        5 & 5 & 4 & 3 \\
        5 & 1 & 4 & 2 \\
        1 & 2 & 1 & 2
    \end{bmatrix},
    \begin{bmatrix}
        5 & 1 & 4 & 1 \\
        3 & 1 & 5 & 4 \\
        5 & 4 & 2 & 3
    \end{bmatrix}
  \right]
\right]
\end{align*}

\end{document}

Remove showframe that's used here just to see that the alignment fits.
An alternative version:
\documentclass{article}
\usepackage{amsmath}
\usepackage{showframe}% just to see the page margins

\begin{document}

\begin{align*}
\mathcal{X} =
% outer
\left[ \vphantom{\begin{matrix}0\\0\\0\end{matrix}}\right.
& \left[
    \begin{bmatrix}
        5 & 1 & 4 & 5 \\
        1 & 1 & 1 & 4 \\
        5 & 3 & 1 & 4
    \end{bmatrix},
    \begin{bmatrix}
        5 & 3 & 4 & 4 \\
        2 & 5 & 3 & 4 \\
        2 & 2 & 4 & 4
    \end{bmatrix}
  \right],
\\
& \left[
    \begin{bmatrix}
        2 & 3 & 1 & 2 \\
        1 & 5 & 4 & 2 \\
        3 & 4 & 5 & 3
    \end{bmatrix},
    \begin{bmatrix}
        2 & 3 & 1 & 4 \\
        4 & 4 & 2 & 1 \\
        4 & 1 & 1 & 1
    \end{bmatrix}
  \right],
\\
& \left[
    \begin{bmatrix}
        5 & 5 & 4 & 3 \\
        5 & 1 & 4 & 2 \\
        1 & 2 & 1 & 2
    \end{bmatrix},
    \begin{bmatrix}
        5 & 1 & 4 & 1 \\
        3 & 1 & 5 & 4 \\
        5 & 4 & 2 & 3
    \end{bmatrix}
  \right]
\left.\vphantom{\begin{matrix}0\\9\\9\end{matrix}}\right]
\end{align*}

\end{document}


text:
Q: Finding the probability of an $n$-th day being dry given independence and constant probability assumptions Problem
I am trying to solve the following question (3.34 from Paul Meyer's "Introductory probability and Statistics", 2nd ed.):
The following (somewhat simple-minded) weather forecasting is used by an amateur forecaster. Each day is classified as "wet" or "dry" and the probability that any given day is the same as the preceding one is assumed to be a constant $\boldsymbol{p}$ ($0<p<1$). Based on past records, it is supposed that January 1 has a probability of $\beta$ of being "dry". Letting $\beta_n$ equal the probability that the $n$-th day of the year is "dry", obtain an expression for $\beta_n$ in terms of $\beta$ and $p$. Also evaluate $\lim\limits_{n \to \infty}\beta_n$ and interpret your result.
(Hint: Express $\beta_n$ in terms of $\beta_{n-1}$.)
My attempt of a solution
So far I've managed to write an equation
$$P(\text{dry}\mid\text{Jan 2})=P(\text{dry}\mid\text{Jan 1}) \cdot p + P(\text{wet}\mid\text{Jan 1}) \cdot (1-p)$$
or
\begin{gather*}
\beta_2=\beta \cdot p +(1-\beta)\cdot (1-p)=2\beta p +1-\beta-p\\
=1-p+\beta(2p-1)=p+(2p-1)(\beta-1)
\end{gather*}
By the same logic, I can write $\beta_n=p+(2p-1)(\beta_{n-1}-1)$. But after that I stumbled. The answer at the back of the book is $\beta_n=\frac{1}{2}+(2p-1)^n(\beta - \frac{1}{2})$. I do not have a clue as to how to arrive at that. What am I missing?

A: We start from $P_0=\beta$. The recursive relationship is
$$\begin{aligned}P(D_n)&=P(D_n|D_{n-1})P(D_{n-1})+P(D_n|W_{n-1})P(W_{n-1})=\\
&=pP(D_{n-1})+(1-p)(1-P(D_{n-1}))\end{aligned}$$
If a limit exists, then for $n$ sufficiently large $P_n\approx P_{n-1}$ so
$$P_{\infty}=\frac{1}{2}$$
Now observe:
$$\begin{aligned}
P_1&=\beta(2p-1)^\color{blue}{1}+(2p-1)^\color{red}{0}(1-p)\\
P_2&=\beta(2p-1)^\color{blue}{2}+(2p-1)^\color{red}{1}(1-p)+(2p-1)^\color{red}{0}(1-p)\\
P_3&=\beta(2p-1)^\color{blue}{3}+(2p-1)^\color{red}{2}(1-p)+(2p-1)^\color{red}{1}(1-p)+(2p-1)^\color{red}{0}(1-p)\\
&(...)
\end{aligned}$$
The pattern is clear:
$$\begin{aligned}P_n&=\beta(2p-1)^{n}+(1-p)\sum_{1\leq k\leq n}(2p-1)^{n-k}=\\
&=\beta(2p-1)^{n}+(1-p)(2p-1)^n\frac{(2p-1)^{-1}-(2p-1)^{-n-1}}{1-(2p-1)^{-1}}=\\
&=\beta(2p-1)^{n}+(1-p)(2p-1)^n\frac{1-(2p-1)^{-n}}{2(p-1)}=\\
&=\beta(2p-1)^{n}-\frac{(2p-1)^{n}-1}{2}\end{aligned}$$


text:
Q: C# dllimport problem with passing a float I'm trying to get my dll import working.
This is the current import in C#
[DllImport(SpectrumDll, ExactSpelling = true, PreserveSig = true, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
    //SCLIB_ERROR_CODE DLLEXPORT SPECTRUM_SetUserFloat(char *name, float value, int index);
    public static extern SCLIB_ERROR_CODE SPECTRUM_SetUserFloat([MarshalAs(UnmanagedType.LPStr)] string name, float value, int index);

This is the C call from the dll header file.
SCLIB_ERROR_CODE DLLEXPORT SPECTRUM_SetUserFloat(char *name, float value, int index);

This is how I call it in code.
public bool SetUserFloat(string varName, float value, int index = 0)
        {
            try
            {
                var res = spectrum_dll_import.SPECTRUM_SetUserFloat(varName, value, index);
                return true;
            }
            catch (Exception exc)
            {
                return false;
            }
        }

The function it self works, however it cuts off the part behind the comma.
So, If I want to write "5.343F", the value which the C DLL sets, is "5.000"
Is there something wrong with my "dllimport" and the "float" parameter?
Thanks for helping!

A: The code you present is correct in so far as we can tell. We can't verify the return type or the calling convention, so we will have to trust that you have translated them correctly. But we can state that the arguments are correctly translated in your pinvoke code.
The most likely explanation is simply that the DLL is truncating the value for this particular property.


text:
Q: Wicket Form changes randomly being ignored I had a problem with a Form Field (Transient wicket form field ignored) and I had no much luck with the answers, so I made some changes and now the field is sometimes updated, and sometimes not... here's the current code:
The User entity:
@Entity(name = "user")
@Audited
public class User extends DataObjectAudit {

    private static final long serialVersionUID = 1L;

    private RoleTypeEnum role = null;

    public RoleTypeEnum getRole() {
        return role;
    }

    public void setRole(RoleTypeEnum role) {
        this.role = role;
    }
}

And in the panel, there is a drop down panel (extends GenericPanel) and the options possible are the current active role of the user is loaded among with the "lower" possible roles. The chosen option should be loaded into the "role" property.
User sessionUser = StudySession.getSessionUser();
List<RoleTypeEnum> roles = new ArrayList<RoleTypeEnum>();
roles.addAll(sessionUser.getRole().getLowerAndEqualsThanSelf());

WefDropDownPanel<RoleTypeEnum> role = new WefDropDownPanel<RoleTypeEnum>(helper.of(RoleTypeEnum.class, "role").errorRequired(), roles).setSizes(Size.S0, Size.S1, Size.S4);
add(role);

There is no validation for that field, others have though.
The only thing that is made before saving the form is:
@Override
    protected void onBeforeSave(AjaxRequestTarget target, WefForm<User> form) {
        User user = getModelObject();
        DataService dataService = ServiceFactory.getBean(DataService.class);
        ProjectCenter projectCenter = dataService.findUniqueByParameters(ProjectCenter.class, new Parameter<Object>("center", user.getCenter()));
        if (projectCenter != null) {
            user.setProject(projectCenter.getProject());
        }
    }

So the result is that sometimes "role" is updated, and sometimes it is not... Also, all the other fields (that I have erased to simplify) are also being ignored...
If I erase the onBeforeSubmit method, the result is the same... sometimes the entity is updated with the values the user entered, sometimes not...
The funny thing is that sometimes the entity is updated, and sometimes it is not... most of the time it works...

A: Create a quickstart and report back on the user list - I'll happily debug the problem.


text:
Q: What is the good place to add object attribute in XAML? By MSDN: Gets or sets a window's border style.
The code is:<object WindowStyle="WindowStyle" .../>
I added it but failed.
<Window x:Class="ClosingWindowAsync.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Closing="MainWindow_Closing"
    Title="MainWindow" Height="350" Width="525">
<object WindowStyle="WindowStyle" />

The error is:

object is not supported in a Windows Presentation Foundation (WPF) project

Why?

A: You should place the property inside the Window-element, like this:
<Window x:Class="ClosingWindowAsync.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Closing="MainWindow_Closing"
        Title="MainWindow" Height="350" Width="525"
        WindowStyle="SingleBorderWindow">
  <Grid>
  </Grid>
</Window>

The link you provided from MSDN clears this out. Above the code it says:

XAML Attribute Usage

This is just an example usage for the property. The line:
<object WindowStyle="WindowStyle" .../>

is an example of how to use it. In real code it looks like:
<Window WindowStyle="SingleBorderWindow />

A: object in the XAML Attribute Usage example is only a placehorder. It can be also found in the description of other properties, for example:
<object Title="string" .../>
<object Top="double" .../>

This approach is described in more details in the XAML Usage Syntax article in the section Generalized Placeholders:
The object and property placeholders are used in syntaxes where there is no realistic way to anticipate which property is being set, or what specific object the property exists on. This might be either because there are many possibilities, or because the range is not a fixed set. (For example, someone could implement a property that takes a value of a particular type, and the type-backed XAML syntax still works the same.) You can see object and property placeholders as part of syntaxes for types with type converters for attribute usages of the type, or for enumerations.
Or in the Basic XAML syntax guide article:
object property: object property in combination is used for cases where the syntax being shown is the syntax for a type that can be used as an attribute value for many properties. For example, the Xaml Attribute Usage shown for Brush includes: <object property="predefinedColorName"/>
In your case object = Window and your code should look in the following way:
<Window WindowStyle="SingleBorderWindow" ... >


text:
Q: C macro to enable and disable code features I've used a code base before that had a macro system for enabling and disabling sections of code.  It looked something like the following:
#define IN_USE      X
#define NOT_IN_USE  _

#if defined( WIN32 )
    #define FEATURE_A       IN_USE
    #define FEATURE_B       IN_USE
    #define FEATURE_C       NOT_IN_USE
#elif defined( OSX )
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       IN_USE
#else
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       NOT_IN_USE
#endif

Then the code for the features would look like:
void DoFeatures()
{
#if USING( FEATURE_A )
    // Feature A code...
#endif

#if USING( FEATURE_B )
    // Feature B code...
#endif

#if USING( FEATURE_C )
    // Feature C code...
#endif

#if USING( FEATURE_D ) // Compile error since FEATURE_D was never defined
    // Feature D code...
#endif
}

My question (the part I don't remember) is how to define the 'USING' macro so that it errors if the feature hasn't been defined as 'IN_USE' or 'NOT_IN_USE'? Which could be the case if you forget to include the correct header file.
#define USING( feature ) ((feature == IN_USE) ? 1 : ((feature == NOT_IN_USE) ? 0 : COMPILE_ERROR?))

A: Your example already achieves what you want, since #if USING(x) will produce an error message if USING isn't defined. All you need in your header file is something like
#define IN_USE 1
#define NOT_IN_USE 0
#define USING(feature) feature

If you want to be sure that you also get an error just for doing something like
#if FEATURE

or
#if USING(UNDEFINED_MISPELED_FEETURE)

then you could do, say,
#define IN_USE == 1
#define NOT_IN_USE == 0
#define USING(feature) 1 feature

but you won't be able to prevent such misuse as
#ifdef FEATURE

A: The following works. It will give you compile error for FEATURE_D. If you comment out the code for FEATURE_D, then it will execute code for FEATURE_A and FEATURE_B. The code is pretty much self-explanatory. Instead of checking whether FEATURE_D or others are defined inside DoFeatures function, you can just put them inside an if block. In that way, the compiler will try to execute the code block. If it is 1, then the code inside if block will get executed; in case of 0, it will not get executed. And if it is never defined, then will get a compile error.
#include <stdio.h>

#define IN_USE      1
#define NOT_IN_USE  0

#define FEATURE_A       IN_USE
#define FEATURE_B       IN_USE
#define FEATURE_C       NOT_IN_USE

void DoFeatures()
{
    if(FEATURE_A){
        // Feature A code...
        printf("Feature A\n");
    }

    if(FEATURE_B){
        // Feature B code...
        printf("Feature B\n");
    }

    if(FEATURE_C){
        // Feature C code...
        printf("Feature C\n");
    }

    if(FEATURE_D) {// Compile error since FEATURE_D was never defined
        // Feature D code...
        printf("Feature D\n");
    }
}

int main(int argc, char **argv)
{
    DoFeatures();
    return 0;
}

A: Just don't define it if it is not in use
#if defined( WIN32 )
    #define FEATURE_A
    #define FEATURE_B
#else if defined( OSX )
    #define FEATURE_C
#else

#endif

Then In you code:
void DoFeatures()
{
#ifdef FEATURE_A
    // Feature A code...
#endif

#ifdef FEATURE_B
    // Feature B code...
#endif

#ifdef FEATURE_C
    // Feature C code...
#endif

#ifdef FEATURE_D // Compile error since FEATURE_D was never defined
    // Feature D code...
#endif
}

A: Couldn't you just use another group of #ifdefs?
#if defined(WIN32)
    #define FEATURE_A
    #define FEATURE_B
#elif defined (OSX)
    #define FEATURE_C
#endif

// ...

#if defined(FEATURE_A)
    do_a();
#endif

etc.

A: #define IN_USE      1
//#define NOT_IN_USE  _  //Not required

#if defined( WIN32 )
    #define FEATURE_A       IN_USE
    #define FEATURE_B       IN_USE
    #define FEATURE_C       NOT_IN_USE
#elif defined( OSX )
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       IN_USE
#else
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       NOT_IN_USE
#endif

#define USING( feature ) feature

And then your code

A: How about something like this?
#define IN_USE      1
#define NOT_IN_USE  0

#if defined( WIN32 )
    #define FEATURE_A       IN_USE
    #define FEATURE_B       IN_USE
    #define FEATURE_C       NOT_IN_USE
#elif defined( OSX )
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       IN_USE
#else
    #define FEATURE_A       NOT_IN_USE
    #define FEATURE_B       NOT_IN_USE
    #define FEATURE_C       NOT_IN_USE
#endif

#define USING(f) ((f == IN_USE) ? 1 : (f == NOT_IN_USE) ? 0 : (f))

#include <stdio.h>

void DoFeatures()
{
#if USING( FEATURE_A )
    // Feature A code...
    printf("Feature A\n");
#endif

#if USING( FEATURE_B )
    // Feature B code...
    printf("Feature B\n");
#endif

#if USING( FEATURE_C )
    // Feature C code...
    printf("Feature C\n");
#endif

#if defined( FEATURE_D ) // Compile error since FEATURE_D was never defined
    // Feature D code...
    printf("Feature D\n");
#else
#error FEATURE_D not defined.
#endif
}

int main(int argc, char **argv)
{
    DoFeatures();
    return 0;
}

For the compilation error, I have no idea how to integrate it into the macro.  It would be appreciated if somebody could shed us some light.  :P


text:
Q: Problem with function that accepts (object or array, iterator) I think my biggest question is regarding the parameter "iterator".
I'm guessing that it accepts a function.
Am I supposed to provide parameters for that function?
// Call iterator(value, key, collection) for each element of collection.
// Accepts both arrays and objects.

_.each = function(collection, iterator)
{
  if (typeof collection=='object')
  {
    for(let i=0; i<Object.keys(collection).length; i++)
    {
      iterator(collection[i],Object.keys(collection)[i],collection);
    }
  }
  else
  {
    for(let i=0; i<collection.length; i++)
    {
      iterator(collection[i],i,collection);
    }
  }
};

A: Both lodash and underscore refer to this an an iteratee not iterator.  This is probably to help avoid confusion with javascript iterators.
The iteratee is a function the will be called for you. You defined the function and the each will call it for each item in the collection. The documentation will tell you what the signature of the function should look like. For instance underscore will pass (element, index, list) to the function for each item. It's up to you to write the function and decide what to do with those parameters.
For example from Lodash:
_.forEach([1, 2], function(value) {
    console.log(value);
 });

The iteratee is the anonymous function, that's only using the value parameter.


text:
Q: Is that possible to set PresentationsOptions on notifications when my app is on background? I know that we have willPresent notification method to be used when my app is in Foreground. And I'm looking for a similar way to set the presentation options on my notifications when my app is on Background.
Also I know that we have a method for background fetch results, but it does not offer a option to set the presentation option.

A: I resolved to post my on answer in case somebody needs it.
So, instead of send a push notification, I did send a silent push notification where content-available must be 1, and alert field should not be present on the aps payload. In this way, the silent notification will trigger a delegate method application(_:didReceiveRemoteNotification:fetchCompletionHandler:) where I do create a local notification, setting its fields according to my silent notifications user-info and schedule it to be displayed or not. This works for background and foreground.
follow this link for code details:
If the app gets force-quit buy de user, the silent notification will arrive as default behavior. But, no delegate method gets called.


text:
Q: How to access a variable of a function from an another function? I need a help with codeigniter, I have in controller in  public function index() this
$data['book'] = $this->db->query(*something*)->result();

and it's normally working but when I want to use it in other function. for example in public function bookshelf() it wrote me  "variable $data seems to be unused in it's scope" and it's not working
How do I use $data from bookshelf() function ?
edit: It's working now.

A: When setting and getting, Use with $this
$this->data['book'] = $this->db->query(*something*)->result();

A: create a search function
public function Search ($query){
        return $this->db->query($query)->result();
    }

use it anywhere
public function index(){
        $data['search'] = $this -> Search ("%query%");
    }


text:
Q: Node.js POST request not working My parameters in Node-Request aren't getting to its target...
I'm not finding any mistakes...
      var data = querystring.stringify({
      image: 'test',
      test: 'testitest'
  });

  var options = {
      host: 'www.visionalism.com',
      path: path,
      method: 'POST'
  };

var photo_req = http.request(options, function(response) {
    response.setEncoding('utf8');
    response.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});
  console.log(data);
photo_req.write(data);
photo_req.end();

At the other side, the POST array (php) is complete empty...
Am i missing anything?

A: solved the problem by adding headers.... bad mistake


text: Q: The whole nine yards What is the origin of the term "the whole nine yards"? I have read many explanations, including one that nine yards refers to the length of the belt of wing-mounted machine guns in US fighter aircraft. Thus to "give him the whole nine yards" meant that the pilot fired off a long burst.


text:
Q: Nativescript CLI says Android SDK not configured properly, but I don't know how to fix it I am developing a Nativescript app and would like to run it on my physical Android device (Huawei P10 lite) via USB.
I downloaded the Android SDK CLI tools and extracted it into my ~/Android/ directory and I've set my environment variable ANDROID_HOME to /home/<username>/Android. When I run tns run android I expect the app to launch on my phone, however it prints out:

✔ Your ANDROID_HOME environment variable is set and points to correct directory.
✔ Your adb from the Android SDK is correctly installed.
✔ A compatible Android SDK for compilation is found.
✔ Javac is installed and is configured properly.
✔ The Java Development Kit (JDK) is installed and is configured properly.
✔ Local builds for iOS can be executed only on a macOS system. To build for iOS on a different  operating system, you can use the NativeScript cloud infrastructure.
✖ WARNING: The Android SDK is not installed or is not configured properly.
You will not be able to run your apps in the native emulator. To be able to run apps
in the native Android emulator, verify that you have installed the latest Android SDK
and its dependencies as described in http://developer.android.com/sdk/index.html#Requirements

Your environment is not configured properly and you will not be able to execute local builds.

There is no indication of what exactly isn't configured properly. So I don't know what I should try next?
I'm running on Ubuntu 18.04.5. My ~/Android/ directory looks like

-rwxr--r-- android
drwxr-xr-x bin/
drwxr-xr-x build-tools/
-rwxr--r-- emulator
-rwxr--r-- emulator-check
-rw-r--r-- .knownPackages
drwxr-xr-x lib/
drwxr-xr-x licenses/
-rwxr--r-- mksdcard
-rwxr--r-- monitor
-rw-r--r-- NOTICE.txt
drwxr-xr-x platforms/
drwxr-xr-x platform-tools/
drwxr-xr-x proguard/
-rw-r--r-- source.properties
drwxr-xr-x support/

I've set up symlinks for adb -> /home/<username>/Android/platform-tools/adb and emulator -> /home/<username>/Android/platform-tools/emulator and placed the links inside the ~/.bin/ directory. This directory is checked when searching for terminal commands and I can successfully run them from any directory this way.

A: After some digging around, I figured out the problem. The downloaded Android CLI tools was extracted in my top level ~/Android/ directory. The CLI tools should actually be put in the ~/Android/tools/ directory. After I made this change, tns doctor found no issues and I could run tns run android successfully.
My ~/Android/ directory structure looks like this now:

build-tools/
.knownPackages
licenses/
platforms/
platform-tools/
tools/

The ~/Android/tools/ directory looks like this now:

android
bin/
emulator
emulator-check
lib/
mksdcard
monitor
NOTICE.txt
proguard/
source.properties
support/

Part of the android setup that I missed
It says

The archive you just extracted was the tools folder, so in this case it would be at: /usr/local/android/sdk/tools

Where /usr/local/android/sdk is ~/Android in my case.


text:
Q: Can someone explain what the ternary operator is doing in this code? I found this example C code from "The Audio Programming Book".
I understand basically what the code is doing.   It takes an array of values that represent the amplitude of series of sine waves and adds them together to create a complex wave.
I am OK with everything except the line with reads:
a  = amps ?  amps[i] : 1.f;

I know Ternary Operators are basically If/Else statement, but I cannot seem to figure out what this is doing exactly, because 'amps' is not defined earlier in the code.  It doesn't make sense that amps is reusing amps[], it seem that would be a no no.  I also haven't been able to find an example anywhere that matches up with this anywhere else.
But the code compiles, so I am completely baffled by what is it NOT wrong, and just what it is doing exactly.
If someone can explain what this is doing [is a traditional If/Else form] I would greatly appreciate it.
float* TableGEN::fourier_table(int harms, float *amps, int length, float phase)
{
   float a;
   float *table = new float[length+2];
   double w;
   phase *= (float)pi*2;

   memset(table, 0, (length+2)*sizeof(float) );

   for(int i=0; i < harms; i++)
      for(int n=0; n < length+2; n++)
      {
           a  = amps ?  amps[i] : 1.f;
           w = (i+1)*(n*2*pi/length);
           table[n] += (float) (a*cos(w+phase));
      }

   normalise_table(table, length , 1.0f );
   return table;
}

Thanks
Stan

A: It seems it's checking if amps is true and/or is set to something, and if it is, then grab the given index of it, else, return a float of 1.
So
if (amps)
{
   a = amps[i];
}
else
{
   a = 1.f;
}

Which is wonky/odd to be honest. It should really be checking if amps[i] is set, and then grab it. If not, then default to 1.f


text:
Q: Virtual Machine Manager - Automate Repetitive Launch Steps Each time I launch Virtual Machine Manager, I have to run this command before any virtual machines can be run successfully:
sudo virsh net-start default

On a Debian 11 desktop, how can I configure Virtual Machine Manager so that this is accomplished by merely launching the application?

A: You need to tell libvirt that the "default" network should be automatically started when libvirtd is started.
sudo virsh net-autostart default

If "default" hasn't already been started, you'll still need to start it manually one last time but the next time you reboot, "default" will be auto-started along with libvirtd.
FYI, virsh has built-in help, e.g.:
# virsh help network
 Networking (help keyword 'network'):
    net-autostart                  autostart a network
    net-create                     create a network from an XML file
    net-define                     define an inactive persistent virtual network or modify an existing persistent one from an XML file
    net-destroy                    destroy (stop) a network
    net-dhcp-leases                print lease info for a given network
    net-dumpxml                    network information in XML
    net-edit                       edit XML configuration for a network
    net-event                      Network Events
    net-info                       network information
    net-list                       list networks
    net-name                       convert a network UUID to network name
    net-start                      start a (previously defined) inactive network
    net-undefine                   undefine a persistent network
    net-update                     update parts of an existing network's configuration
    net-uuid                       convert a network name to network UUID
    net-port-list                  list network ports
    net-port-create                create a network port from an XML file
    net-port-dumpxml               network port information in XML
    net-port-delete                delete the specified network port

# virsh help net-autostart
  NAME
    net-autostart - autostart a network

  SYNOPSIS
    net-autostart <network> [--disable]

  DESCRIPTION
    Configure a network to be automatically started at boot.

  OPTIONS
    [--network] <string>  network name or uuid
    --disable        disable autostarting


text:
Q: Magento 2 Filter admin grid with custom columns I have a custom table that is assigned to multiple store so i do have another table for their relationship. my problem now is i want to filter my custom table by store in the admin grid. i was able to display it by manipulating my data provider. but my filter is not working because mui/index/render is trying filtering store_id in the main_table which does not exist.
i getting an error in the exeption.log "Unknown column 'store_id' in 'where clause', query was: SELECT COUNT(*) FROM my_table AS main_table WHERE (store_id = '1')"
DataProvider.php
 public function __construct(
    $name,
    $primaryFieldName,
    $requestFieldName,
    \My\Module\Model\ResourceModel\faqs\Collection $faqsCollection,
    \Magento\Framework\App\RequestInterface $request,
    \My\Module\Helper\Resource $resourceHelper,
    array $meta = [],
    array $data = []
){
    $this->collection = $faqsCollection;
    $this->request = $request;
    $this->resourceHelper = $resourceHelper;
    parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
}

public function getData()
{
    if (isset($this->loadedData)) {
        return $this->loadedData;
    }

    $faqsId = $this->request->getParam('faqs_id');
    if($faqsId){ //form data. please dont mind this part
        $faqsCollection = $this->collection->addFieldToFilter('faqs_id', $faqsId);
        foreach ($faqsCollection as $faqs){
            $this->loadedData[$faqs->getId()] = $faqs->getData();
        }
    } else { //grid data. here is where i manipulate the data for the grid
        $faqsCollection = $this->collection->toArray();
        $this->loadedData['totalRecords'] = $faqsCollection['totalRecords'];
        foreach ($faqsCollection['items'] as $faqs){
            //this returns an array of store from the relationship table [1,2,3,4]
            $faqs['store_id'] = $this->resourceHelper->getTopicStores($faqs['topic_id']);
            $this->loadedData['items'][] = $faqs;
        }
    }

    return $this->loadedData;
}

then in my faqs_grid.xml ui_component
<dataSource name="faqs_grid_data_source" component="Magento_Ui/js/grid/provider">
    <settings>
        <storageConfig>
            <param name="indexField" xsi:type="string">faqs_id</param>
        </storageConfig>
        <updateUrl path="mui/index/render"/>
    </settings>
    <aclResource>My_Module::faq</aclResource>
    <dataProvider class="My\Module\Model\faqs\DataProvider" name="faqs_grid_data_source">
        <settings>
            <requestFieldName>faqs_id</requestFieldName>
            <primaryFieldName>faqs_id</primaryFieldName>
        </settings>
    </dataProvider>
</dataSource>

<listingToolbar name="listing_top">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="sticky" xsi:type="boolean">true</item>
        </item>
    </argument>
    <columnsControls name="columns_controls"/>
    <filters name="listing_filters">
        <argument name="data" xsi:type="array">
            <item name="observers" xsi:type="array">
                <item name="column" xsi:type="string">column</item>
            </item>
        </argument>
        <settings>
            <templates>
                <filters>
                    <select>
                        <param name="template" xsi:type="string">ui/grid/filters/elements/ui-select</param>
                        <param name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</param>
                    </select>
                </filters>
            </templates>
        </settings>
        <filterSelect name="store_id" provider="${ $.parentName }">
            <settings>
                <captionValue>0</captionValue>
                <options class="Magento\Cms\Ui\Component\Listing\Column\Cms\Options"/>
                Store View
                <dataScope>store_id</dataScope>
                <imports>
                    <link name="visible">componentType = column, index = ${ $.index }:visible</link>
                </imports>
            </settings>
        </filterSelect>
    </filters>
    <paging name="listing_paging"/>
</listingToolbar>

<columns name="faq_listing_columns">
    <column name="store_id" class="Magento\Store\Ui\Component\Listing\Column\Store">
        <settings>
            Store View
            <bodyTmpl>ui/grid/cells/html</bodyTmpl>
            <sortable>false</sortable>
        </settings>
    </column>

the displaying is working properly. but i need to find a way to filter it by store_id.


text:
Q: AWS Lambda Publish Messages to SNS in cross region I have a Lambda function (east-us-1) that needs to publish messages to SNS topics in both (east-us-1) & (eu-central-1) regions. Is this possible?
Here is my code snippet. Can someone help on how can I achieve this?
I am surprised to see that the boto3 client documentation says "You can publish messages only to topics and endpoints in the same Amazon Web Services Region"
Link Here:
from __future__ import print_function

import json
import urllib
import boto3

print('Loading message function...')

def send_to_sns(message, context):

    # This function receives JSON input with three fields: the ARN of an SNS topic,
    # a string with the subject of the message, and a string with the body of the message.
    # The message is then sent to the SNS topic.
    #
    # Example:
    #   {
    #       "topic": "arn:aws:sns:REGION:123456789012:MySNSTopic",
    #       "subject": "This is the subject of the message.",
    #       "message": "This is the body of the message."
    #   }

    sns = boto3.client('sns')
    sns.publish(
        TopicArn=message['topic'],
        Subject=message['subject'],
        Message=message['body']
    )

    return ('Sent a message to an Amazon SNS topic.')

My code throws the following error when SNS is in different region
{
    "response": {
        "stackTrace": [
            [
                "/var/task/lambda_function.py",
                28,
                "send_to_sns",
                "Message=message['body']"
            ],
            [
                "/var/runtime/botocore/client.py",
                357,
                "_api_call",
                "return self._make_api_call(operation_name, kwargs)"
            ],
            [
                "/var/runtime/botocore/client.py",
                676,
                "_make_api_call",
                "raise error_class(parsed_response, operation_name)"
            ]
        ],
        "errorType": "InvalidParameterException",
        "errorMessage": "An error occurred (InvalidParameter) when calling the Publish operation: Invalid parameter: TopicArn"
    }
}

A: you are facing this issue because of region conflict with below code you can check
your current region
my_session = boto3.session.Session()
my_region = my_session.region_name

and to solve your problem just do this i am assuming you are connected to us-east-1 and your sns is present in us-east-2 region
sns = boto3.client('sns',region_name='us-east-2')


text:
Q: Como adicionar itens vindo de um JSON, em uma base de dados? Explicando:
Tenho as seguintes classes para trabalhar, uma que é a chegada e o retorno do JSON e outras, entities data, segue abaixo:
UsuarioExperimentoResult:
public class UsuarioExperimentoResult
{
    public string nome_usuario_experimento { get; set; }
    public string telefone_experimento { get; set; }
    public string email_experimento { get; set; }
    public string Id { get; internal set; }
    public List<EnderecoExperimento> endereco_expermento { get; set; }

}

Entity Data:
public class QuemAvisarExperimento : EntityData
{
    public string id_usuario_experimento_quem_avisar { get; set; }
    public string id_endereco_experimento_quem_avisar { get; set; }
    public string nome_experimento_quem_avisar { get; set; }
    public string telefone_experimento_quem_avisar { get; set; }
}

public class EnderecoExperimento : EntityData
{
    public string id_usuario_experimento { get; set; }
    public string nome_endereco_experimento { get; set; }
    public string destino_experimento { get; set; }
    public double lat_endereco_experimento { get; set; }
    public double lng_endereco_experimento { get; set; }
}

public class UsuarioExperimento : EntityData
{
    public string nome_usuario_experimento { get; set; }
    public string telefone_experimento { get; set; }
    public string email_experimento { get; set; }

}

Então, eu recebo o JSON e adiciono o usuário, crio um ID para ele e feito isso, devo adicionar os itens que vieram na lista do tipo EnderecoExperimento. Como eu posso fazer isso, adicionar item a item, na base de dados e relacionado ao ID do usuárioi criado anteriormente?
Segue aqui, o método que criei mas, não tem dado certo:
private HttpResponseMessage operacaoPost(UsuarioExperimentoResult usuarioExperimentoResult)
{
    mContext context = new mContext();
    if (usuarioExperimentoResult != null)
    {
        // Adding User
        UsuarioExperimento usuario = new UsuarioExperimento
        {
            Id = Guid.NewGuid().ToString(), //id para novo cadastro
            nome_usuario_experimento = usuarioExperimentoResult.nome_usuario_experimento,
            telefone_experimento = usuarioExperimentoResult.telefone_experimento,
            email_experimento = usuarioExperimentoResult.email_experimento
        };

        context.UsuarioExperimentoDB.Add(usuario);

        // Adding Address
        if (usuarioExperimentoResult.endereco_expermento != null)
        {
            List<EnderecoExperimento> enderecoExperimentos = new List<EnderecoExperimento>();
            enderecoExperimentos = usuarioExperimentoResult.endereco_expermento;
            foreach (var end in usuarioExperimentoResult.endereco_expermento)
            {
                //gerar um id para cada endereço
                end.Id = Guid.NewGuid().ToString();

            }

        }
        // Saving the changes
        context.SaveChanges();
        return this.Request.CreateResponse(HttpStatusCode.OK, RequestResponseUtils.createResponseBody(usuario));
    }
    else
    {
        return this.Request.CreateResponse(HttpStatusCode.BadRequest, "404");
    }
}

Obrigado!
Edit:
json:
{
    "dados":{"nome_usuario_experimento":"teste",
             "telefone_experimento":"0123456789",
             "email_experimento":"teste@teste",
             "endereco_expermento":[{"nome_endereco_experimento":"nome1",
                                      "destino_experimento":"destino1"
             }]
            }
}


text:
Q: Is this operator aliasing? I don't understand what does mean typedef void (Testable::*bool_type)() const;
applied to operator
Is such code
class Testable {
    typedef void (Testable::*bool_type)() const;

public:

    operator bool_type() const {
     ...
    }
};

equivalent to
class Testable {

public:

    void operator ()() const {
     ...
    }
};

?

A: class Testable {
    typedef void (Testable::*bool_type)() const;

public:

    operator bool_type() const {
     ...
    }
};

… defines an implicit conversion to bool_type, which is an innaccessible pointer to member type.
This is a C++03 technique to provide implicit conversion to bool while avoiding unintended implicit conversions, in particular for function call overload resolution. The returned member pointer converts to bool but not to any type that could conceivably be used for a function argument. In contrast, a pure bool result would convert to e.g. int, and a void* result, as used by C++03 iostreams, would match a void* formal argument.
With C++11 and later you would instead use explicit, like this:
explicit operator bool() const { return whatever; }

But better, define a named conversion function, e.g.
auto is_empty() const -> bool { return whatever; }

That was generally better also in C++03. :-)

Regarding "is such code equivalent to…", no, it's not.


text:
Q: Get text layer of a PDF as is and pass it to another PDF Good afternoon , I have a problem in my project, this is PDF compression , the process is as follows:
Extract images from a PDF
Hang OCR
Compression Stock
OCR + Merge image and convert PDF per page
Combine all the generated pdf with OCR, OCR PDFcon one out as a final product.
The size of my original file is 11 MB and 4.2 MB compressed .
The whole process works perfectly , but the problem that I have is the speed in the OCR process . I was checking on the web, and I saw a way to circumvent that process, which is getting the text layer of the original PDF and pass it to the final PDF is compressed , try some codes like delete all images of the PDF and be alone with the text layer , and insert my compressed images, but the problem compared to the normal process provided above , the weight of the file is increased by more than 4.2 MB , which is not convenient for me.
When seeking another solution I found that the handle PDF operators which were handled with PDFBox through the PDFStreamParser , PDStream , COSDictionary .
Operators are TJ , TW , TZ , TC ... etc. .
My question is if anyone knows pass TJ operate , which is the one that contains the text of a PDF to another , to see if the text layer of the original PDF can be passed to the final PDF is compressed without me 4.2MB high to raise the weight, the idea is not to spend other operators because these can increase the weight of the final PDF or am I mistaken ?
If you have any other solution that would help me would be very grateful ? .
Sorry if my English is bad , if anyone knows Spanish tells me to express myself better .
thanks

A: You could use our open source tool pdf2json to get the text layer from your pdf. Just make sure you pass "-hidden" as a parameter to the tool when using it if you want to get text from OCR scanned documents. It supports exporting your data to JSON and XML. Have a look at it here:
http://code.google.com/p/pdf2json/


text:
Q: Passing Functor with state as parameter in c++ I'm trying to implement a simple callback using Functor objects. I have a Caller class with print(string) function which invokes the callback passing the input string. In the callback, I'm collecting all the strings, and print it later in printEverything method. But even though callbacks are happening (as verified by output), but nothing gets printed in printEverything method.
class Callback {
public:
  Callback() {
    cout << "constructing Callback..." << std::endl;
  }

  void operator()(std::string data) {
    cout << "Adding record in callback: " << data << std::endl;
    records.push_back(data);
  }

  void printEverything() {
    cout << "Printing everything: " << std::endl;
    for(auto a : records) {
      cout << a;
    }
  }

private:
  std::vector<string> records;
};

class Caller {
public:
  template <typename Func>
  Caller(Func&& func) : cb_ (func){
  }

  void print(std::string str) {
    cb_(str);
    cout << "Printing in caller: " << str << std::endl;
  }

private:
  std::function<void(std::string)> cb_;
};

int main(int argc, char **argv) {
  Callback callback;
  Caller caller(callback);

  caller.print("Hello");
  caller.print("World");

  callback.printEverything(); // This doesn't print any records
}

Output:
constructing Callback...
Adding record in callback: Hello
Printing in caller: Hello
Adding record in callback: World
Printing in caller: World
Printing everything:

It seems, the callbacks are happening on a different object than what I have in main scope. Any ideas what's going wrong here?

A: std::function copies (or moves if you moved into it) the function you pass to it (see its constructor). Ergo, the callbacks are happening on a different object than callback.
If you want to pass a reference to the function, use std::ref – it has an operator():
int main() {
  Callback callback;
  // Be careful with lifetime management. `caller` must not outlast `callback`
  Caller caller(std::ref(callback));

  caller.print("Hello");
  caller.print("World");

  callback.printEverything();
}

Live on Wandbox


text:
Q: Error: Command failed: cscript.exe //Nologo We are using npm-regedit module to read/write registry in Windows. We are using it in an electron app. Normally when we run the application it works fine but when we set the app to run automatically at startup the regedit module fails. We get the following error on reading "HKCU/SOFTWARE":
Error: Command failed: cscript.exe //Nologo D:\CodeLathe\Workspace\cl-fc-client\clouddrive2service\ui\dist_electron\win-unpacked\resources\app.asar\vbs\regList.wsf A HKCU\SOFTWARE

A: copy the VBS folder (Store the directory of.wsf files) in the regedit package to your own directory.
Then customize the VBS directory :regedit.setExternalVBSLocation('./common/vbs');


text:
Q: Convert GNU awk command to default macOS awk command Given a file containing many lines such as, e.g.:
Z|X|20210903|07:00:00|S|33|27.71||

With wanted output of, e.g.:
Z|X|20210903|07:00:00|S|33|27.71|||03-09-2021 07:00:00

This GNU awk command works:
gawk -F'|' '{dt = gensub(/(....)(..)(..)/,"\\3-\\2-\\1",1,$3); print $0"|"dt,$4}' infile > outfile

However, I need this to work under macOS with the version of awk that is installed by default, and it produces the following error:
awk: calling undefined function gensub
 input record number 1, file
 source line number 1

I'm assuming the default version of awk in macOS is too old and doesn't support the gensub function.
Note that I have tried numerous other string functions to no avail. awk programming is not in my area of expertise and I derived at the GNU awk command above thru a fair amount of googling, but my google-fu was unsuccessful in trying to get something to work with macOS awk.
Can the above GNU awk command be rewritten to work with the default version of awk in, e.g., macOS Catalina and if so how?

A: Would you please try the following:
awk -F'|' '{dt=substr($3,7,2) "-" substr($3,5,2) "-" substr($3,1,4); print $0 "|" dt, $4}' infile > outfile

A: Using perl instead of gawk:
$ perl -lne '
   my @F = split /[|]/, $_, -1;
   my $dt = ($F[2] =~ s/(....)(..)(..)/$3-$2-$1/r);
   print join("|", @F, "$dt $F[3]")' <<<"Z|X|20210903|07:00:00|S|33|27.71||"
Z|X|20210903|07:00:00|S|33|27.71|||03-09-2021 07:00:00


text:
Q: Deezer Rest API - Add Track to Playlist doesn't work? I have an Android application integrated with the deezer rest API, and I need to add a track to a playlist.
My application already has Oauth login flow, when I execute the following request:
http://api.deezer.com/user/me?access_token=AJSDH44H5R7SS7SDHDUHFSUDUSUSASDA766

Works fine!
Playlist actions, I trying send this request as:
POST
http://api.deezer.com/playlist/777006545/tracks?access_token=AJSDH44H5R7SS7SDHDUHFSUDUSUSASDA766&songs=2312333,12312

GET
http://api.deezer.com/playlist/777006545/tracks?access_token=AJSDH44H5R7SS7SDHDUHFSUDUSUSASDA766&songs=2312333,12312&request_method=post

Callback error:
{
    "error": {
    "type": "OAuthException",
    "message": "An active access token must be used to query information about the current user",
    "code": 200
    }
}

But the token works for other requests. What's the right way to do this, anyone know?

A: Have you checked this page?
https://developers.deezer.com/api/playlist#actions ?
It seems you already have found this one:
https://developers.deezer.com/api/actions-post
Here is what I would test:

*

*POST only.

*Check that your access token has the manage_library permission.

*Check that the owner of the playlist is the same that the user of the access_token.
It worked for me with:
http://api.deezer.com/playlist/<playlist_id>/tracks?access_token=<access_token>&request_method=post&songs=<track_id>


text:
Q: Merge Multiple Objects from Fetch request I'm trying trying to merge multiple objects that come from an API and group them by their id and values but any changes will only apply to the single object as opposed to all of them.
My latest attempt:
let carIds = [7, 78, 34, 59];

let url = "";
carIds.map(id => {
  url = `https://example.com/api/reports?carId=${id}`;

  fetch(url)
    .then(response => response.json())
    .then(data => carData(data))
    .catch(error => console.error(error));
});

const carData = data => {
  const reports = data.cars[0].car.car_makes;

  let result = reports.reduce(function(r, a) {
    r[a.car_make_id] = r[a.car_make_id] || [];
    r[a.car_make_id].push(a.car_model);
    return r;
  }, {});
};

The results I get from the API is similar to this (no commas included in the API response):
{"id":1,"car_make":[{"car_make_id":"7","model_year":2000,"car_model":"Viper"}]}
{"id":2,"car_make":[{"car_make_id":"7","model_year":1997,"car_model":"Elantra"}]}
{"id":3,"car_make":[{"car_make_id":"7","model_year":2011,"car_model":"Yukon"}]}
{"id":4,"car_make":[{"car_make_id":"7","model_year":1996,"car_model":"Suburban 2500"}]}
{"id":5,"car_make":[{"car_make_id":"7","model_year":1995,"car_model":"G-Series G10"}]}

Where the car_make_id are the same but the car_model are different.
The expected output should be:
{
  car_make_id: 7,
  values: ['Viper', 'Elantra', 'Yukon', etc...]
}

But the actual output is:
{
  7: ['Viper']
}
{
  7: ['Elantra']
}
{
  7: ['Yukon']
}
{
  7: ['Suburban 2500']
}

Any suggestions on how to implement this? Thanks in advance.

A: Below should work:

let result = reports.reduce(function(r, a) {
    if(r["car_make_id"] != a.car_make_id){
      r["car_make_id"] = a.car_make_id;
      r["values"] = [];
    }
    r["values"].push(a.car_model);
    return r;
  }, {});


text:
Q: Difference between 'join' and 'merge'? Suppose one wants to make polygons A and B, and their respective attributes to be one unique polygon C. What is this GIS operation called?
Is there any difference in GIS terminology about "joining" and "merging" geometries? Or does the terminology expand to different concepts besides geometries?

As an example, I could not find the answer reading tag wikis in GIS SE.
Currently, the excerpt and wiki of merge says:

In the context of GIS, merge typically refers to either

*

*combining two or more geometries into a new, single geometry

*combining the records of two different tables into a single table (similar to append)

*combining multiple raster files (stacked or adjacent) into one.

A specific type or method of merging is dissolve.

And the excerpt of joins states:

The process of connecting two or more datasets based on a common attribute or spatial location.

"Connecting two or more datasets based on a common attribute" seems to be the same as the second bullet in the merge wiki.

A: When to use join:

*

*When there is a one to one relationship between two distinct tables or geometrics (based on join field or spatial relation)

*Used to append new field/columns to table (result = table has same number of rows, and more columns)

http://resources.arcgis.com/en/help/main/10.2/index.html#//005s0000002q000000
When to use merge:

*

*To combine one to many tables with similar database schema

*Used to combine additional rows to destination table (result = table has more rows, and potentially more columns)

http://resources.arcgis.com/en/help/main/10.2/index.html#//001700000055000000
The bullets you listed are correct, joins are for adding additional information such fields or columns to an existing table, and merge is for creating a new table that has the combination of rows from table A, B, C..etc.