text:
Q: which of these mysql queries is more efficient, using left join or not i have a following sql query
$select_query_1 = SELECT * FROM user_module_comments WHERE useid = '$hash' ORDER BY id DESC LIMIT 0, 25
  while($table = mysql_fetch_array($select_query_1)){
    $user_moid = $table['canvas'];
    $user_xtract_canvas = mysql_query("SELECT mcanvas FROM user_module WHERE uid = '$user_moid' LIMIT 1");
    $selected = mysql_fetch_array($user_xtract_canvas);
    $user_canvas_extract = $selected['mcanvas']; // this is what i need
  }

OR this sql query
$select_query = SELECT user_module_comments.useid, user_module.mcanvas FROM user_module_comments LEFT JOIN user_module ON user_module.uid = user_module_comments.useid WHERE useid = '$hash' ORDER BY user_module_comments.id DESC LIMIT 0, 25

which of these queries is more efficient
thank

A: The JOIN is likely to be far, far faster than doing related queries in a loop.  In general it is almost always faster to do one query than to do n queries.  I only say "almost always" because I'm sure someone can come up with a use case where the opposite may be true.
There is a lot of overhead involved with MySQL compiling the SQL statement over and over in the loop, executing it, and fetching a rowset.  Using the single statement eliminates all of that overhead.
You should install Xdebug and actually profile these statements in PHP to find out how long they take to execute.


text:
Q: Rails - generate "flash" like modal from controller I am confusing about how to make a popup windows (modal) to tell the user when something is happened after a controller action. This should be something like the flash[:notice/alert] function that use in redirect_to or render.
I have found a gem called 'server-generated-popup' but I don't really understand how to use it or whether it suits my case or not.
I have also tried to use magnific-popup and bootstrap-popup, but they seems to more likely generate popup/modal by user's actions (click a button, click a link). I have tried to use them by render :template to create a modal but with no luck.
What I want to do is really the same as flash[:notice/alert], but replace it to a modal that no user inputs are needed. What should I do? My thought is:

*

*Create a new flash type by add_flash_types :modal

*replace the behavior of it with some code to bootstrap modal (should be the easier than magnificent popup?)

*call it in render or redirect_to
But how to do the step two?
Thanks.

A: Can you try doing
render js: 'alert("popup")'

This way you can trigger modal popup from the server
Another way is to render the flash yourself. In your application layout you can do something like this:
<% flash.each do |k, v| %>
   <% if k == :mocal_alert %>

   <% else %>
      <# how ever you are rendering the default flashes %>
      <div id="<%= k %>"><%= v %>

   <% end %>
<% end %>

Obviously replace alert("popup") with something nicer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to implement dynamic intercept url pattern i.e from database in spring security 3.0.5 I am new to spring security so not getting how to proceed for making the Url's to be authenticated should come from database.
What things to be added in applicationContext-security.xml and what custom java classes will be needed?
Please help me with example.
Thanks

A: I got the same issue with you. The following links would be helpful.
http://static.springsource.org/spring-security/site/faq.html#faq-dynamic-url-metadata
http://forum.springsource.org/showthread.php?112799-How-to-dynamically-decide-lt-intercept-url-gt-access-attribute-value-in-Spring-Security
How to dynamically decide <intercept-url> access attribute value in Spring Security?


text:
Q: ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller I've tried variations in the code below i.e. switching from stage to this.stage or even root.stage, but no luck.
The full error I get is:
    ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/setChildIndex()
at flash.display::Stage/setChildIndex()
at Banner/next_image_loaded()

package {
    import flash.display.*;
    import flash.events.*;
    import flash.net.*;
    import flash.utils.*;
    import gs.*;
    import gs.easing.*;

public class Banner extends MovieClip
{
    var xml_url:URLRequest;
    var xml_loader:URLLoader;
    var img_loader:Loader;
    var img_data:Array;
    var img:Bitmap;
    var new_img:Bitmap;
    var strapline:strap;
    var banner:bottom_banner;
    var button:tech_button;
    var current_image:Number = -1;
    var done:Boolean = false;

    public function Banner()
    {
        this.xml_url = new URLRequest("Banner.xml");
        this.xml_loader = new URLLoader(this.xml_url);
        this.xml_loader.addEventListener(Event.COMPLETE, this.xml_loaded);
        this.xml_loader.addEventListener(IOErrorEvent.IO_ERROR, this.err);
        return;
    }// end function

    private function xml_loaded(event:Event)
    {
        this.img_data = new Array();
        var _loc_2:* = new XML(event.target.data);
        var _loc_3:* = 0;
        while (_loc_3 < _loc_2.image.length())
        {

            this.img_data.push(_loc_2.image[_loc_3]);
            _loc_3 = _loc_3 + 1;
        }
        this.img_data = this.randomise_array(this.img_data);
        this.next_content();
        return;
    }// end function

    private function randomise_array(param1:Array) : Array
    {
        var _loc_2:* = new Array();
        while (param1.length > 0)
        {

            _loc_2.push(param1.splice(Math.floor(Math.random() * param1.length), 1));
        }
        return _loc_2;
    }// end function

    private function next_content()
    {
        if (this.current_image == (this.img_data.length - 1))
        {
            this.current_image = 0;
        }
        else
        {
            var _loc_2:* = this.current_image + 1;
           this.current_image = _loc_2;
        }
        this.img_loader = new Loader();
        this.img_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.next_image_loaded);
        this.img_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, this.err);
        this.img_loader.load(new URLRequest(this.img_data[this.current_image]));
        return;
    }// end function

    private function next_image_loaded(event:Event)
    {
        var _loc_2:Number = 0;
        this.new_img = event.target.content;
        stage.addChild(this.new_img);
        if (this.strapline)
        {
            stage.setChildIndex(this.strapline, (stage.numChildren - 1));
        }
        if (this.banner)
        {
            stage.setChildIndex(this.banner, (stage.numChildren - 1));
        }
        if (this.button)
        {
            stage.setChildIndex(this.button, (stage.numChildren - 1));
        }
        if (this.current_image == 0 && this.done != true)
        {
            this.button = new tech_button();
            this.button.x = 28;
            this.button.y = 257;
            //stage.addChild(this.button);
            var _loc_3:Boolean = true;
            this.button.buttonMode = true;
            this.button.useHandCursor = _loc_3;
            this.button.addEventListener(MouseEvent.CLICK, this.goToTechPage);
            TweenLite.from(this.button, 0.5, {alpha:0, delay:1.5});
            this.banner = new bottom_banner();
            this.banner.x = 0;
            this.banner.y = stage.stageHeight - 40;
            stage.addChild(this.banner);
            this.strapline = new strap();
            this.strapline.x = 232;
            this.strapline.y = 195;
            stage.addChild(this.strapline);
            TweenLite.from(this.strapline, 1, {x:stage.stageWidth, ease:Expo.easeOut, delay:0.75, onComplete:this.fade_strap});
            this.done = true;
        }
        else
        {
            _loc_2 = 0.75;
        }
        TweenLite.from(this.new_img, 1, {autoAlpha:0, ease:Expo.easeOut, onComplete:this.swap_clips, delay:_loc_2});
        return;
    }// end function

    private function goToTechPage(event:MouseEvent) : void
    {
        navigateToURL(new URLRequest("report.htm"), "_self");
        return;
    }// end function

    private function fade_strap()
    {
        TweenLite.to(this.strapline.bg_mc, 1.5, {alpha:0.85});
        return;
    }// end function

    private function remove_strap()
    {
        this.strapline.parent.removeChild(this.strapline);
        this.strapline = null;
        return;
    }// end function

    private function swap_clips()
    {
        if (this.img)
        {
            stage.removeChild(this.img);
        }
        this.img = this.new_img;
        this.new_img = null;
        setTimeout(this.next_content, 6500);
        return;
    }// end function

    private function err(event:IOErrorEvent)
    {
        if (this.img_data)
        {
            this.next_content();
        }
        return;
    }// end function

}

A: //stage.addChild(this.button);

it seems 'button' is not added to the stage (in the next_image_loaded() method), therefore
if (this.button)
{
    stage.setChildIndex(this.button, (stage.numChildren - 1));
}

throws an error, although 'button' may exist (!= null), it was not added to the stage
try with if-statements as follow:
if(button != null && button.stage != null)

EDIT: as Vesper already pointed out in the meanwhile

A: This is a lot of code for someone to have to read through, you can narrow down where the error is occurring using trace("trace 1") at key points in your code (change the number each time). When you execute your code the output window will show your traces ie:
trace 1
trace 2
trace 3
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller

This tells you the error occurred some time after the third trace.  The error you get tells you it is happening in the next_image_loaded function so try running a few traces in there and update your post with the results.


text:
Q: how to include glyphicons in bootstrap 3 I've not used any of the bootstrap frameworks before. I want to include some of the glyphicons in bootstrap 3 on my page. From what I understand they should be included in a bootstrap.css file which I've added to my page. When I've looked in the bootstrap.css file however I don't see any reference to them ? Although its a large file I may have missed something.
I have noticed that when I opened the  dist folder downloaded from bootstrap 3 there is a separate folder fonts that contains files named:
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
glyphicons-halflings-regular.woff

It Seems like this is where the glyphicons are however I don't know how to attach these to my site? How do I attach the glyphicons to my page ?
Thanks for any help in advance
The code below shows the attached bootstrap.css file:
<!DOCTYPE html>

    <title>Bootstrap example</title>
    <meta name="viewport" content="width=divice-width, initial-scale=1.0">

    <link href="bootstrap.css" rel="stylesheet" media="screen">

and here is the part of the html code showing where the glyphicons should be:

           Home

 Top
           Destinations

             About Us

A: I think  your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.
Bootstrap requires a specific file structure to work.  I see from your code you have this:
<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.
But first, let me recommend you setup your folder structure like so:
/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.
You then include your Bootstrap file like so:
<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.
The first and second are relative to your file's current directory.  The second one is just more explicit by saying "here" (./) first then css folder (/css).
The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.
So, why do this?
Bootstrap.css has this specific line for Glyphfonts:
@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.
The URL address is relative to the location of the CSS file.  So, if your CSS file is at the same location like this:
/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.
So, let's say the actual location of these files are:
C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:
C:\fonts

but your folder is actually in:
C:\www\fonts

So see if that helps.  You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.
When you get that fixed, your HTML should simply be:

Note, you need both classes.  The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.


text:
Q: Kernel panic - not syncing when using Ubuntu USB live I'm in serious need of some help.
I had ubuntu 15.04 on a dual boot with Windows 8. And then I wanted to install 16.04 and because I had some space issues, I decided to get 16.04 on a live USB and then boot through that. I used a something called UEFI USB boot instead of changing boot preferences for bios and ended up simply deleting the Linux partition (I knew then that's not the way to remove ubuntu but I thought I have a live USB to access my hard drive in any case).
Obviously now, normal boot would lead to grub rescue prompt.
I again boot through UEFI USB and started to install Ubuntu, somewhere in between a prompt mentioned that I'm using a UEFI system and if I continue I won't be able to use any OS installed on a BIOS system. So I did a hard reboot by cutting of the power and then change the preference in BIOS to boot from USB first.
And now my problem began. No matter what I do, try to install Ubuntu  or try Ubuntu without installing or a disk check ( these are the three out of four options that you get on booting from a live USB), I always get the same error screen.
"Kernel panic - not syncing : VFS: unable to mount root fa on unknown block (1,0) and around 10-15 more lines.
I am literally stuck at this.
Help me out.


text:
Q: How to pass multiple data to controller? These are two select box. When i select both product and warranty value then it should pass to the controller.So how should i pass ?
<select id="products">
    <option value="1">Mobile</option>
     <option value="2">Laptop</option>
</select>

<select id="warrant">
    <option value="1">1 Years</option>
     <option value="2">2 years</option>
     <option value="3">3 years</option>
</select>

This is my Script file
$('#products').change(function () {
     var product_id=$(this).val();
})
$('#warrant').change(function () {
     var warrant_id=$(this).val();
})

I want to pass those warrant_id and product_id in Controller in below Code So How can i pass ?
<script>
fetch('http://127.0.0.1:8000/api/productChart'+{
  warrant_id,product_id
})
    .then(response => response.json())
    .then(data => {
            this.sales = data.sales;
            this.start = data.start;
            this.to = data.end;
        });
 </script>

This is my route
Route::get('/productChart','Controller@productChart');

A: You can use formData to send / pass your variable data to your backend in post request using fetch API.
Define both the variable (product_id / warrant_id) as global to be accessible and assign their value back to the variables and then use formData.append method to add data to your formData to be able to send it your laravel backend.
Also, if you have more data to send you can simply append more values to your formData.

var product_id
var warrant_id

$('#products').change(function() {
  product_id = $(this).val();
})
$('#warrant').change(function() {
  warrant_id = $(this).val();
})

function callFetch() {
  var formData = new FormData(); //initialize form Data
  formData.append('product_id', product_id); //append product_id
  formData.append('warrant_id', warrant_id);//append warrant_id

  //Post Request
  fetch('http://127.0.0.1:8000/api/productChart', {
      body: formData,
      method: "post"
    })
    .then(response => response.json())
    .then(data => {
      //do something with data
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="products">
  <option value="1">Mobile</option>
  <option value="2">Laptop</option>
</select>

<select id="warrant">
  <option value="1">1 Years</option>
  <option value="2">2 years</option>
  <option value="3">3 years</option>
</select>

<button onclick="callFetch()">
 Post Data
</button>


text:
Q: how to show message box in windows store app when wcf data service update record successfully? I have a Windows Store app. I am using WCF data service and I want to give friendly message to user that we are done with updating record.
This is my function where updating is done.
I want to put message that "Update successfully".
private void ModfityJobsAsynchCallBack(IAsyncResult synchresult)
{
    try
    {
        dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                _context.EndSaveChanges(synchresult);
                this.IsDataLoaded = false;
            });
    }
    catch (Exception ex)
    {
        MessageDialog msgDialog = new MessageDialog("Error while updating data");
        msgDialog.ShowAsync();
    }
}

A: after the line saying this.IsDataLoaded = false;
the anonymous function you pass in to be executed async will be executed in different thread. your Try{}Catch{} here only catches errors in putting this function in UI thread's queue and not it's execution result.
private void ModfityJobsAsynchCallBack(IAsyncResult synchresult)
{
    try
    {
        dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                try
                {
                     _context.EndSaveChanges(synchresult);
                     this.IsDataLoaded = false;
                     await Windows.UI.Popups.MessageDialog("Success").ShowAsync();
                }
                catch(Exception ex)
                {
                      await Windows.UI.Popups.MessageDialog("Fail").ShowAsync();
                }
            });
    }
    catch (Exception ex)
    {
        MessageDialog msgDialog = new MessageDialog("Error while updating data");
        msgDialog.ShowAsync();
    }
}


text:
Q: (How) can I use an array of strings as identifiers in C++? I'm working on this project where I need to parse a text file that contains a two-column table consisting of names on the left and values on the right.
Now, I need to write those to specific places in a control table, which are identified using hexadecimal addresses; in a header file that I can't edit, they have been defined as such:
#define HARRY_POTTER 0x3A

There's then a writing function that takes an address and a value and writes it into a storage place (this function is also out of my control). So, calling this
write(0x3A, 7);

Would have the same result as calling this
write(HARRY_POTTER, 7);

Because of that definition in the header file.
Now, I've got the parsing down, which basically gives me the left column, the name, as a string (so, "HARRY_POTTER", for example), and the right column, the value, as an integer.
What I'm wondering is if there's any way to use this string, "HARRY_POTTER" as the identifier in the write function; essentially converting the string into an identifier, so that I could just loop through my entire array of parsed values and it would automatically write them to the address that matches the string/ the name in the left column.
Is this possible? If yes, how?

A: No, it's not possible as you ask. The reason is because the string that you read from the file is only known at run-time, while preprocessing occurs at compile-time, so HARRY_POTTER must already have been replaced. In fact, no identifiers at all exist after the program has been compiled.
What you may want it to introduce a mapping from std::strings to the constants that you have defined. For example:
std::unordered_map<std::string, int> mapping = {{"HARRY_POTTER", HARRY_POTTER},
                                                {"RON_WEASLEY", RON_WEASLEY}};

The constants will be replaced at compile-time, of course, so this is just equivalent to:
std::unordered_map<std::string, int> mapping = {{"HARRY_POTTER", 0x3A},
                                                {"RON_WEASLEY", 0x7C}};

Then you can call write with:
write(mapping.at(key), 7);

Where key is a string with a value like "HARRY_POTTER".

A: (This answer fits way better in a comment, but I am still working up the reputation...)
I agree with Joseph that the way to go is an std::unordered_map in C++11 or a std::map in C++03.
I only wanted to add that you can make the code much more maintainable and easier to write by a bit of macro-magic in this case.
/* The stringify macro converts x to "x" at compile-time. */
#define _stringify(x) # x
#define stringify(x) _stringify(x)

/* Macro easing the assignment of { "String", value } */
#define STR_VAL(x) { stringify(x), (x) }

/* Now you can write the assignment code as follows */
std::unordered_map<std::string, int> mapping = {
    STR_VAL(HARRY_POTTER),
    STR_VAL(RON_WEASLEY),
    STR_VAL(ALBUS_BRIAN_WULFRIC_PERCIVAL_DUMBLEDORE)
};

This means that if the value of #define HARRY_POTTER ever changes your mapping code will be automatically updated when you recompile.


text:
Q: Any way to get MAC address from local network devices on android using flutter? having studied quite a lot of links, I realized that Google and Apple have blocked some methods (ARP, etc.) for obtaining a MAC address.
But how can this be done now, while studying Google play, I came across several applications that still receive MAC addresses on android 13.
How can this be done?
I looked through a lot of information but did not find anything working.


text:
Q: My SanDisk USB flash drive shows that 43GB is used when I just copied a 10GB folder after formatting I recently bought a SanDisk 128GB USB flash drive.
And after formatting the USB flash drive in exFAT format, I copied a folder whose capacity is around 10GB. There are lots of small files in it, so it took some time.
However, when I see in the Windows Explorer after copying the folder, it says that around 43GB of the storage is occupied and now only 70GB of the storage is free to use.
What is happening and how should I deal with it? Is my USB flash drive physically broken?
It is still weird because when I copied a single file with 7 GB capacity, it showed the remaining capacity correctly at around 110 GB available..

A: Why is this happening?
Because you're storing a lot of tiny files.
Filesystems have a minimum file size that they can store. For NTFS filesystems, it's usually 4KB. For exFAT, it can be much larger. That's called the block or cluster size. Files that are smaller than this size will still use up the minimum size, so a 1KB file might use 4KB of disk space. A 3KB file would also use 4KB of disk space. If you have a 5KB file, it'll use 8KB of disk space.
You can imagine it like a grid of holes. Each hole can hold a certain amount of data. Files are spread across as many holes as necessary to hold all the file's data, but holes can't have data from more than one file. So, if a file's data doesn't completely fill a hole, some of that space is wasted. No other file can use it that hole so the unused space is unavailable.
What can you do about it?
In your case, you have a lot of files that don't fill the holes, so there's lots of wasted space. If you were to put all the files into a ZIP file, then all that data would be contained in a single file and it would use a lot less space on the drive.
Some USB drives are formatted as exFAT by default, so alternatively, if you're just using this drive to copy files between Windows computers (or just for storage), you could try reformatting the drive as NTFS (but copy all the files off first, obviously!) to try to get a smaller cluster size.

A: You already answered your own question: There are lots of small files in it
Every file on an exFAT volume takes at least one blocksize. So a file of a single byte in size takes at least 4K - a size amplification of 1:4096. You are seing a size amplification of 4.3, which is very plausible with lots of small files.
You can check this hypothesis by packing the files with WinRAR and the zero compression settings, then copy this file to the USB stick.

A: As the other answer suggested, use an archiver, but I'll recommend using 7z instead of WinRAR because it's free, and also you can avoid installing any third-party archivers if you use Windows' built-in "Send to > Compressed (zipped) folder" option when you right-click files and folder. It's faster than 7z but it archives slightly slower.
In case you need to store mostly JPEG images or something else that doesn't compress at all, you should benefit from using 7z and picking the "no compression" option explicitly.
Using .zip archive format over .rar or .7z is important because Windows supports browsing them as if it was just any other folder (albeit with some limitations).
If you are okay with not being able to browse files like that on the flash drive, you can use another format, but the important part about the files not taking so much space is having a single archive file instead of all the original files separately.

A: When formatting as exFAT, you almost surely chose some large allocation unit (block size) like 128k or 512k. Reformat with the standard 4k allocation units and the problem should go away.


text:
Q: JDBC-to-ODBC bridge gone. How to connect to SQL Server now in case of Windows Authentication? Connecting to our corporate SQL servers using JDBC never worked for me, perhaps related to the Windows Authentication method that is necessary in our network. However, I found out that configuring the connection using the ODBC tool on Windows and using the JDBC-to-ODBC bridge together with a configuration in DatabaseExplorer  worked for me.
I'm currently moving my stuff to a newer 64 bit VDI (old one was 32 bit) and changing Mathematica version from 10.3 to 11.01 and found that the ODBC route doesn't work for me anymore. I get an error: JDBC::classnotfound sun.jdbc.odbc.jdbcOdbcDriver.
Some googling learns me that in Java 8 the whole JDBC-to-ODBC bridge was removed and it looks like Mathematica 11 runs on Java 8, so that might explain it.
Anyone got a solution to this problem? JDBC on its own (that is, without the bridge to ODBC) still does not work for me either.

A: Following Rolf Mertig's tip I examined the merits of Microsoft's latest JDBC driver (not included in Mathematica 11). It worked, but it was quite a trip. The itenary can be found below. Note that you'll need to have evaluated Needs["DatabaseLink`"] first for a few functions below to work.
First, I downloaded Microsofts newest JDCB driver (not the jTDS one) from this download page.

Download the Microsoft JDBC Driver 6.0, 4.2, 4.1, or 4.0 for SQL
  Server, a Type 4 JDBC driver that provides database connectivity
  through the standard JDBC application program interfaces (APIs)
  available in Java Platform, Enterprise Editions.

We need enu\sqljdbc_6.0.7728.100_enu.exe from the download selections.
This zipped package contains the following drivers:

*

*Sqljdbc.jar requires a JRE of 5 and supports the JDBC 3.0 API

*Sqljdbc4.jar requires a JRE of 6 and supports the JDBC 4.0 API

*Sqljdbc41.jar requires a JRE of 7 and supports the JDBC 4.1 API

*Sqljdbc42.jar requires a JRE of 8 and supports the JDBC 4.2 API
Since Mathematica 11 uses Java 8 we need Sqljdbc42.jar.
Double clicking the installer unpacks the files to a folder. The location is unimportant as we will just be copying two files from it.
Locate sqljdbc42.jar in subfolder sqljdbc_6.0\enu. Also pick up sqljdbc_auth.dll from sqljdbc_6.0\enu\auth\x64\sqljdbc_auth.dll for 64 bits PCs (which I tried) or sqljdbc_6.0\enu\auth\x86 for 32 bits PCs (which I haven't tried).
The first file should be copied to one of the following three folders:

*

*$InstallationDirectory/SystemFiles/Links/DatabaseLink/Java

*$UserBaseDirectory/Applications/Oracle/Java

*$BaseDirectory/Applications/Oracle/Java
where the $names are Mathematica variables indicating a base directory. Replace them with the result of evaluating that variable. I used the second one.
sqljdbc_auth.dll can be copied to the same directory or to C:\Windows\System32. Both locations seem to work.
Next a driver resource file is necessary. This file provides some details on the driver, among which the class name (I needed quite some googling before I found the correct one) and the exact calling protocol (this differs from the jTDS one).
JDBCDriver[
 "Name" -> "Microsoft SQL Server (MS6 driver)",
 "Driver" -> "com.microsoft.sqlserver.jdbc.SQLServerDriver",
 "Protocol" -> "jdbc:sqlserver://",
 "Description" -> "Microsoft SQL Server using Microsoft's jdbc 6.0 driver",
 "Location" -> "C:\\Users\\vriessc\\AppData\\Roaming\\Mathematica\\DatabaseResources\\sqljdbc6.m"
]

This file should be located in one of the folders you get upon executing:
DatabaseResourcesPath[]

{
  {"C:\\Program Files\\Wolfram Research\\Mathematica\\11.0\\SystemFiles\\Links\\DatabaseLink\\DatabaseResources", "DatabaseLink"},
  {"C:\\Users\\vriessc\\AppData\\Roaming\\Mathematica\\DatabaseResources", None},
  {"C:\\ProgramData\\Mathematica\\DatabaseResources", None}
}

The first result contains similar (standard) resource files, but it is chained to the version 11 directory which I don't like. I choose the second one, which holds my own predefined connection defintions.
The resource file has extension ".m" but it should not be edited with Mathematica because it adds a header to the file which is invisible in Mathematica itself and causes the resource to be skipped by DatabaseLink. Use a plain tekst editor for this. Note that the file contains a link to its own location, so make sure to make that it matches its actual location.
With this file in place, and with the kernel restarted, a connection can now be made using:
conn =
  OpenSQLConnection[
    JDBC["Microsoft SQL Server (MS6 driver)", "ServerName"],
   "Properties" -> {"integratedSecurity" -> "true"},
   "Catalog" -> "DatabaseName"
  ]

The "integratedSecurity" -> "true" part is very important. It makes Windows Authentication work for me (note the lack of credentials in the call?). This didn't work with the old jTDS drivers, so this is really why the new JDCB drivers are necessary.
A last, optional step, would be to make a resource file that makes the above a named connection. Previously, I had been using DatabaseExplorer for that goal, but for some reason I got weird results in this case. So I just copied an existing connection file and modified it appropriately in a text editor.
SQLConnection[
  JDBC["Microsoft SQL Server (MS6 driver)", "ServerName"],
  "Location" -> "C:\\Users\\vriessc\\AppData\\Roaming\\Mathematica\\DatabaseResources\\MyArbitraryConnectionName.m",
 "Name" -> "MyArbitraryConnectionName",
 "Catalog" -> "DatabaseName",
 "Description" -> "My descripion",
 "Password" -> "",
 "Properties" -> {"integratedSecurity" -> "true"},
 "ReadOnly" -> Automatic,
 "RelativePath" -> False,
 "TransactionIsolationLevel" -> Automatic,
 "UseConnectionPool" -> Automatic,
 "Username" -> ""
]

The connection can now be opened using the simple:
conn = OpenSQLConnection["MyArbitraryConnectionName"]

A: Yes you are right, JDBC-to-ODBC support is gone as Mathematica uses java8.
However 11.0.1 mathematica comes with a support for using open source JDBC driver which can be used to connect Microsoft Access DB without relying on JDBC-to-ODBC bridge.
e.g.
In[32]:= << DatabaseLink`

In[34]:= $Version

Out[34]= "11.0.1 for Mac OS X x86 (64-bit) (September 21, 2016)"

In[36]:= JDBCDrivers["Microsoft Access(UCanAccess)"]

Out[36]:JDBCDriver["Name" -> "Microsoft Access(UCanAccess)",
"Driver" -> "net.ucanaccess.jdbc.UcanaccessDriver",
 "Protocol" -> "jdbc:ucanaccess://", "Version" -> 3.1,
 "Description" -> "Open-source Java JDBC driver implementation that allows Java \developers and JDBC client programs to read/write Microsoft Access databases.",
 "Location" ->"/Applications/Mathematica11.0.1.app/Contents/SystemFiles/Links/DatabaseLink/DatabaseResources/accessjdbc.m"]

In[37]:= conn =
 OpenSQLConnection[
 JDBC["Microsoft Access(UCanAccess)",
  "/Users/damanjits/databaselink/Tests/AccessDB.accdb"]];

In[38]:= SQLCreateTable[conn, SQLTable["TEST"],
 SQLColumn["id", "DataTypeName" -> "integer", "PrimaryKey" -> True]]

Out[38]= 0

In[39]:= SQLTables[conn]

Out[39]= {SQLTable["TEST", "TableType" -> "TABLE"]}

There is a small section in documentation which describes about this driver at DatabaseLink/tutorial/DatabaseReference.

A: I am not sure this will be helpful, as I am running Mathematica 9, but maybe the issue is the same, as move from 32 bit to 64 bit.
I use this code as I move from Windows 32 bit to Windows 64 bit, working with Microsoft SQL-Server:
Needs["DatabaseLink`"];
openConn[]:=Block[
  {},
  If[$System==="Microsoft Windows (64-bit)",
    Return[OpenSQLConnection[JDBC["Microsoft SQL Server(jTDS)",
      "SERVERNAME/DATABASENAME"],
      "Username"->"USERNAME",
      "Password"->"PASSWORD"]]];
  If[$System==="Microsoft Windows (32-bit)",
    Return[OpenSQLConnection[JDBC["ODBC(DSN)",
      "DRIVER={SQL Server};"<>
        "SERVER=SERVERNAME;"<>
        "DATABASE=DATABASENAME"],
      "Username"->"USERNAME",
      "Password"->"PASSWORD"]]];
  Null
]


text:
Q: Culture is not supported when deserializing file I'm trying to deserialize a file that was serialized from a system with a foreign culture.
I am getting the following error, but I can't seem to get around it.
Any pointers appreciated.

Culture is not supported. Parameter name: culture 3072 (0x0c00) is an
invalid culture identifier.

Even trying to set the culture to any country does not change the error that culture 3072 is invalid.
var file = "C:\\myfile.blb"
CultureInfo ci = new CultureInfo("el-GR"); //Adding or removing this line does NOT change the error.
var fs = new FileStream(file, FileMode.Open);
try
{
    var format = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    DataSet ds = format.Deserialize(fs) as DataSet;  //Exception thrown on THIS line
    ....
}
catch (Exception ex)
{
    throw ex;
}


text:
Q: A non-null value must be returned since the return type 'int' What am i trying to do is to sort my list by price .I am getting this error.
How can i fix this.Thanks in advanced
    sortAll(List<BookModel> books) {
    books.sort((a, b) {
      a.price.compareTo(b.price);
    },);
    print((books));
  }
}

A: The compareTo is not returning anything. Try this instead:
books.sort((a, b) {
  return a.price.compareTo(b.price); // note the RETURN
},);

Or this:
books.sort((a, b) => a.price.compareTo(b.price) ); // implicit RETURN


text:
Q: Загрузка изображения и привязка У меня есть код для загрузки изображения в Image, привязка работает, но в рантайме выдает ошибку(не исключение, т.к. приложение не падает): Cannot convert '<null>' from type '<null>' to type 'System.Windows.Media.ImageSource' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null). Из-за этой ошибки загруженная картинка не показывается, хотя в коде для загрузки реализовал интерфейс INotifyPropertyChanged в качестве отдельного метода в отдельном классе, который вызывается в сеттере свойства, привязанного к Image.
Разметка изображения:
<Image Source="{Binding _AvatarPath}" Margin="53,56,981,558"/>
Класс для загрузки изображения C#:
internal class ProfileEditor : INotifyPropertyChangedImp
{
    private readonly INotifyPropertyChangedImp propchange = new INotifyPropertyChangedImp();

    public static Uri? AvatarPath;
    public Uri? _AvatarPath
    {
        get { return AvatarPath; }
        set
        {
            AvatarPath = value;
            propchange.NotifyPropertyChanged("_AvatarPath");
        }
    }

    public static void ChangeAvatar()
    {
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                         "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                         "Portable Network Graphic (*.png)|*.png";
        fDialog.CheckFileExists = true;
        if (fDialog.ShowDialog() == true)
        {
            var uri = new Uri(fDialog.FileName);
            AvatarPath = uri;
        }
    }
}

Класс, реализующий интерфейс INotifyPropertyChanged:
internal class INotifyPropertyChangedImp : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler? PropertyChanged;

    internal void NotifyPropertyChanged([CallerMemberName] string? propname = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
        }
    }
}

Изначально, метод для загрузки картинки в Image в разметке был в файле xaml.cs, позже я решил его перенести в отдельный класс.
Собственно, у меня есть несколько вопросов:

*

*Можно ли таким образом реализовывать интерфейс INotifyPropertyChanged? Возможно я его просто неправильно реализовал, подскажите пожалуйста.

*Какой лучше метод привязки здесь использовать? Возможно я и привязку неправильно сделал.

*Как все-таки избавиться от ошибки, описанной выше(Cannot convert '<null>' from type '<null>' to type 'System.Windows.Media.ImageSource' for 'en-US' culture with default conversions; consider using Converter property of Binding. NotSupportedException:'System.NotSupportedException: ImageSourceConverter cannot convert from (null).). Честно, первый раз сталкиваюсь с этим, и понятия не имею что здесь нужно делать.

*Может ли быть все это из-за того, что в свойстве AvatarPath используется nullable?(прошу, поправьте если не так это называется) после типа данных?
Буду рад любой помощи, спасибо!


text:
Q: Snakemake using a rule in a loop I'm trying to use Snakemake rules within a loop so that the rule takes the output of the previous iteration as input. Is that possible and if yes how can I do that?
Here is my example

*

*Setup the test data

mkdir -p test
echo "SampleA" > test/SampleA.txt
echo "SampleB" > test/SampleB.txt

*Snakemake

SAMPLES = ["SampleA", "SampleB"]

rule all:
    input:
        # Output of the final loop
        expand("loop3/{sample}.txt", sample = SAMPLES)

#### LOOP ####
for i in list(range(1, 4)):
    # Setup prefix for input
    if i == 1:
        prefix = "test"
    else:
        prefix = "loop%s" % str(i-1)

    # Setup prefix for output
    opref =  "loop%s" % str(i)

    # Rule
    rule loop_rule:
        input:
            prefix+"/{sample}.txt"
        output:
            prefix+"/{sample}.txt"
            #expand("loop{i}/{sample}.txt", i = i, sample = wildcards.sample)
        params:
            add=prefix
        shell:
            "awk '{{print $0, {params.add}}}' {input} > {output}"

Trying to run the example yields the ERROR CreateRuleException in line 26 of /Users/fabiangrammes/Desktop/Projects/snake_loop/Snakefile:
The name loop_rule is already used by another rule. If anyone spots an option to get that thing to work it would be great!
Thanks !

A: I think this is a nice opportunity to use recursive programming. Rather than explicitly including conditionals for every iteration, write a single rule that transitions from iteration (n-1) to n.  So, something along these lines:
SAMPLES = ["SampleA", "SampleB"]

rule all:
    input:
        expand("loop3/{sample}.txt", sample=SAMPLES)

def recurse_sample(wcs):
    n = int(wcs.n)
    if n == 1:
        return "test/%s.txt" % wcs.sample
    elif n > 1:
        return "loop%d/%s.txt" % (n-1, wcs.sample)
    else:
        raise ValueError("loop numbers must be 1 or greater: received %s" % wcs.n)

rule loop_n:
    input: recurse_sample
    output: "loop{n}/{sample}.txt"
    wildcard_constraints:
        sample="[^/]+",
        n="[0-9]+"
    shell:
        """
        awk -v loop='loop{wildcards.n}' '{{print $0, loop}}' {input} > {output}
        """

As @RussHyde said, you need to be proactive about ensuring no infinite loops are triggered. To this end, we ensure all cases are covered in recurse_sample and use wildcard_constraints to make sure the matching is precise.

A: My understanding is that your rules are converted to python code before they are ran and that all the raw python code present in your Snakefile is ran sequentially during this process. Think of it as your snakemake rules being evaluated as python functions.
But there's a constraint that any rule can only be evaluated to a function once.
You can have if/else expressions and differentially evaluate a rule (once) based on config values etc, but you can't evaluate a rule multiple times.
I'm not really sure how to rewrite your Snakefile to achieve what you want. Is there a real example that you could give where looping constructs appear to be required?
--- Edit
For fixed number of iterations, it may be possible to use an input-function to run the rule several times. (I would caution against doing this though, be extremely careful to disallow infinite loops)
SAMPLES = ["SampleA", "SampleB"]

rule all:
    input:
        # Output of the final loop
        expand("loop3/{sample}.txt", sample = SAMPLES)

def looper_input(wildcards):
    # could be written more cleanly with a dictionary
    if (wildcards["prefix"] == "loop0"):
        input = "test/{}.txt".format(wildcards["sample"])
    else if (wildcards["prefix"] == "loop1"):
        input = "loop0/{}.txt".format(wildcards["sample"])
    ...
    return input

rule looper:
    input:
            looper_input
    output:
            "{prefix}/{sample}.txt"
    params:
            # ? should this be add="{prefix}" ?
            add=prefix
    shell:
            "awk '{{print $0, {params.add}}}' {input} > {output}"


text:
Q: Error installing Social Engine I've got a problem trying to install Social Engine. Upload all files, set directory permissions, but when I enter my domain, I get a:
Not Found

The requested URL /install/install was not found on this server.

It's something related to the .htaccess files in root and install directory, 'cause removing them I do begin the installation process BUT with long URLs, this way:
/install/index.php/install
And that's something that would end up with all long URLS, instead of short ones that google use to index, for example. My ISP has safe_mode OFF, and mod_rewrite ON, so I'm just kinda lost...

A: .htaccess :
# $Id: .htaccess 7539 2010-10-04 04:41:38Z john $

<IfModule mod_rewrite.c>
  Options +FollowSymLinks
  RewriteEngine On

  # Get rid of index.php
  RewriteCond %{REQUEST_URI} /index\.php
  RewriteRule (.*) index.php?rewrite=2 [L,QSA]

  # Rewrite all directory-looking urls
  RewriteCond %{REQUEST_URI} /$
  RewriteRule (.*) index.php?rewrite=1 [L,QSA]

  # Try to route missing files
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} public\/ [OR]
  RewriteCond %{REQUEST_FILENAME} \.(jpg|gif|png|ico|flv|htm|html|php|css|js)$
  RewriteRule . - [L]

  # If the file doesn't exist, rewrite to index
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?rewrite=1 [L,QSA]

</IfModule>

# sends requests /index.php/path/to/module/ to "index.php"
# AcceptPathInfo On

# @todo This may not be effective in some cases
FileETag Size

A: Had the same issue running SocialEngine on Vagrant (using https://box.scotch.io/) and fixed it by clearing the .htaccess file under /install/.


text:
Q: NextJS issue reading items already in local storage On logging into my NextJS application, I am saving some user data to local storage.
I am trying to render this into a small component which always displays the users name. The issue i am getting is that it is only sometimes showing and other times it is displaying as null ... It seems when i log in, it displays as null, but when i reload the page it works.
This is what I have;
import { useEffect } from 'react';

export default function ProfileDisplay() {
    useEffect(async () => {
        const userName = JSON.parse(localStorage.getItem('profile'));
        console.log(userName);
    }, []);

    return (

            {userName}

    )
}

A: It is probably coming as null initially because on your server side there is no "localStorage" object. And since you are calling useEffect with empty dependency array , it will not fire when username changes. So you should declare username outside the useEffect and put it in dependency array for listening to changes.
export default function ProfileDisplay() {
  const userName = JSON.parse(localStorage.getItem('profile')); // moved it outside the useEffect
  useEffect(() => {
    if(userName)
      console.log(userName); // do stuff with username

}, [userName]); // it will fire when username changes

return (

        {userName}

)
}

A: You can put the userName variable in state and update it in your useEffect once its value is retrieved from localStorage.
import { useEffect, useState } from 'react';

export default function ProfileDisplay() {
    const [userName, setUserName] = useState('')

    useEffect(() => {
        const profile = JSON.parse(localStorage.getItem('profile'));
        setUserName(profile);
    }, []);

    return (

{userName}

    )
}


text:
Q: ngx-translate doesn't display translation in server mode but renders HTML My angular app renders server side with universal, I get the translations in the browser but in the source code it only renders the HTML output and not the translations.

{{ 'PAGES.LANDING.HOW_2' | translate }}

  <app-root _nghost-sc0="" ng-version="8.2.14"><app-header _ngcontent-sc0="" _nghost-sc1="">

<svg _ngcontent-sc1="" class="hamburger_svg" fill="none" height="40" viewBox="0 0 32 40" width="32" xmlns="http://www.w3.org/2000/svg"><path _ngcontent-sc1="" d="M4.12799 25.6001C4.12799 26.8161 5.15199 27.8721 6.36799 27.8721C7.58399 27.8721 8.60799 26.8481 8.60799 25.6001C8.60799 24.3841 7.58399 23.3281 6.36799 23.3281C5.15199 23.3601 4.12799 24.3841 4.12799 25.6001Z" fill="#A1A2B2"></path><path _ngcontent-sc1="" d="M4.12799 16C4.12799 17.216 5.15199 18.272 6.36799 18.272C7.58399 18.272 8.60799 17.248 8.60799 16C8.60799 14.784 7.58399 13.728 6.36799 13.728C5.15199 13.76 4.12799 14.784 4.12799 16Z" fill="#A1A2B2"></path><path _ngcontent-sc1="" d="M4.12799 6.40017C4.12799 7.61617 5.15199 8.67217 6.36799 8.67217C7.58399 8.67217 8.60799 7.64817 8.60799 6.40017C8.60799 5.18417 7.58399 4.12817 6.36799 4.12817C5.15199 4.16017 4.12799 5.18417 4.12799 6.40017Z" fill="#A1A2B2"></path><path _ngcontent-sc1="" d="M26.528 8.67217H12.672C11.424 8.67217 10.4 7.64817 10.4 6.40017C10.4 5.15217 11.424 4.12817 12.672 4.12817H26.528C27.776 4.12817 28.8 5.15217 28.8 6.40017C28.8 7.64817 27.776 8.67217 26.528 8.67217Z" fill="#A1A2B2"></path><path _ngcontent-sc1="" d="M26.528 18.272H12.672C11.424 18.272 10.4 17.248 10.4 16C10.4 14.752 11.424 13.728 12.672 13.728H26.528C27.776 13.728 28.8 14.752 28.8 16C28.8 17.248 27.776 18.272 26.528 18.272Z" fill="#A1A2B2"></path><path _ngcontent-sc1="" d="M26.528 27.8721H12.672C11.424 27.8721 10.4 26.8481 10.4 25.6001C10.4 24.3521 11.424 23.3281 12.672 23.3281H26.528C27.776 23.3281 28.8 24.3521 28.8 25.6001C28.8 26.8481 27.776 27.8721 26.528 27.8721Z" fill="#A1A2B2"></path></svg><

My text is translated in the browser but not in the source code which I need for SEO purpose.
I get the following error when I build npm run build:ssr && npm run serve:ssr

ERROR TypeError: Cannot read property 'LANDING' of undefined
at /Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:88705:46
at Array.forEach (<anonymous>)
at TranslatePipe../src/app/pipes/translate.pipe.ts.TranslatePipe.transform (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:88705:14)
at Object.updateRenderer (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:84252:1172)
at Object.updateRenderer (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:34047:70)
at checkAndUpdateView (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:33703:14)
at callViewAction (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:33939:21)
at execComponentViewsAction (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:33881:13)
at checkAndUpdateView (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:33704:5)
at callViewAction (/Users/dev/Desktop/pinploylive/pinploy-web/dist/server.js:33939:21)

packackge.json
 "@ngx-translate/core": "^11.0.1",
"@ngx-translate/http-loader": "^4.0.0",

This is my Translate.pipe.ts
   @Pipe({ name: 'translate', pure: false })
export class TranslatePipe implements PipeTransform {

  constructor(private translate: TranslateService, @Inject(PLATFORM_ID) private platformId: object) {}
  transform(key: any): any {
    if (isPlatformBrowser(this.platformId)) {
     const keys = key.split('.');
     let res = this.translate.data;
     keys.forEach(k => { res = res[k]; });
     return res || key;
    }
  }
}

A: Make sure that the PAGES variable is defined before using it, e.g.

{{ 'PAGES.LANDING.HOW_2' | translate }}

Otherwise, you can use the safe operator to avoid errors

{{ 'PAGES?.LANDING.HOW_2' | translate }}


text:
Q: Playing Saved Videos in Documents Dictionary With AVPlayer i have saved a 1mb big buck bunny onto my documents folder, and i tried to load and play it with my AVPlayer,for this i used this code
 NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
             NSString* foofile = [documentsPath stringByAppendingPathComponent:string]; // string is file name

        NSURL *url = [NSURL URLWithString:foofile];
         NSLog(@" exsits %@ :",foofile);

        AVPlayer*player1 = [AVPlayer playerWithURL:url];
        AVPlayerViewController *Controller = [[AVPlayerViewController alloc] init];
        Controller.player = player1;
        [player1 play];
        [self presentViewController:Controller animated:YES completion:nil];

but instead of the player i am getting this
simulator screenshot
EDIT
File URL looks something like this

/Users/usrname/Library/Developer/CoreSimulator/Devices/4453818A-0617-479B-B98C-3FC544A24D00/data/Containers/Data/Application/D7449628-0A67-4294-9471-98F5596FE596/Documents/tt1823672.mp4

A: Formatting comment was killing me, so I just post as answer.
As I remembered, if you want to play some local files, the prefix of the url usually is file://....
But if you create url directly, prefix might will be http://.. .
So you might want to change your code
[NSURL URLWithString:foofile]
to
[NSURL fileURLWithPath:foofile];
so.. url should had a prefix of file://.., and should be target to local files.


text:
Q: Change column visibility table pysimplegui A previous question asked about hiding a column in a pysimplegui table here. Using the same code can I update the visible map to change the current visibility (flip them both). I changed the update line to include visible_column_map, but that fails the update (I know it doesn't really flip but just wanted quick example). Is there a way to do this or do I need two different tables?
import PySimpleGUI as sg

headings = ['President', 'Date of Birth']
data = [
    ['Ronald Reagan', 'February 6'],
    ['Abraham Lincoln', 'February 12'],
    ['George Washington', 'February 22'],
    ['Andrew Jackson', 'March 15'],
    ['Thomas Jefferson', 'April 13'],
    ['Harry Truman', 'May 8'],
    ['John F. Kennedy', 'May 29'],
    ['George H. W. Bush', 'June 12'],
    ['George W. Bush', 'July 6'],
    ['John Quincy Adams', 'July 11'],
    ['Garrett Walker', 'July 18'],
    ['Bill Clinton', 'August 19'],
    ['Jimmy Carter', 'October 1'],
    ['John Adams', 'October 30'],
    ['Theodore Roosevelt', 'October 27'],
    ['Frank Underwood', 'November 5'],
    ['Woodrow Wilson', 'December 28'],
]

sg.theme('DarkBlue3')
sg.set_options(("Courier New", 12))

layout = [
    [sg.Table(data, headings=headings, visible_column_map=[True, False], justification='left', select_mode=sg.TABLE_SELECT_MODE_BROWSE, enable_events=True, key='President')],
    [sg.Text('', size=(22, 1), key='Birthday')],
]
window = sg.Window("Title", layout, finalize=True)

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'President':
        index = values[event][0]
        window['Birthday'].update(visible_column_map=(False, True)

window.close()

A: There's no option to update visible_column_map of sg.Table, and it looks you update it with wrong element window['Birthday'] which is a sg.Label.
Tkinter code required here, button Change added to generate event to update it.
import PySimpleGUI as sg

headings = ['President', 'Date of Birth']
data = [
    ['Ronald Reagan', 'February 6'],
    ['Abraham Lincoln', 'February 12'],
    ['George Washington', 'February 22'],
    ['Andrew Jackson', 'March 15'],
    ['Thomas Jefferson', 'April 13'],
    ['Harry Truman', 'May 8'],
    ['John F. Kennedy', 'May 29'],
    ['George H. W. Bush', 'June 12'],
    ['George W. Bush', 'July 6'],
    ['John Quincy Adams', 'July 11'],
    ['Garrett Walker', 'July 18'],
    ['Bill Clinton', 'August 19'],
    ['Jimmy Carter', 'October 1'],
    ['John Adams', 'October 30'],
    ['Theodore Roosevelt', 'October 27'],
    ['Frank Underwood', 'November 5'],
    ['Woodrow Wilson', 'December 28'],
]

sg.theme('DarkBlue3')
sg.set_options(("Courier New", 12))

layout = [
    [sg.Button('Change')],
    [sg.Table(data, headings=headings, visible_column_map=[True, False],
        justification='left', select_mode=sg.TABLE_SELECT_MODE_BROWSE,
        enable_events=True, metadata=False, key='President')],
    [sg.Text('', size=(22, 1), key='Birthday')],
]
window = sg.Window("Title", layout, finalize=True)
president = window['President']

while True:
    event, values = window.read()
    if event == sg.WINDOW_CLOSED:
        break
    elif event == 'President':
        index = values[event][0]
        window['Birthday'].update(value=f'Birthday: {data[index][1]}')
    elif event == 'Change':
        show = president.metadata = not president.metadata
        displaycolumns = ['President', 'Date of Birth'] if show else ['President']
        president.Widget.configure(displaycolumns=displaycolumns)

window.close()


text:
Q: Change cells value assignment to range and array assignment to improve performance I am reviewing legacy VBA code to improve performance.
I want to change cells assignment to a range and array assignment.
How can I transform the cell references to a range?
Sheets("Model").Activate
YearRange = Range("C7:EZ7").value

loopvar = 1
Do While YearRange(1, loopvar) <> "" And Right(Trim(YearRange(1, loopvar)), 1) <> "E"
    strValue = Trim(YearRange(1, loopvar))
    Year = CInt(strValue)

    GetSpecificData Year, RptPe, RptAvg

    If (RptPe <> 0) Then Cells(508, loopvar + 2).value = RptPe
    If (RptAvg <> 0) Then Cells(509, loopvar + 2).value = RptAvg

    loopvar = loopvar + 1
Loop

The cells assignment are about 15. I put two for reference. Usually there are 30 or more years, so running this piece of code usually takes about 20 or more seconds.
I had a similar loop in another place, but instead of cells used range, and I was able to create a array and then assign the array to the range and reduce the times to less than one second.
GetSpecificData gets the data from a year and populates the variables with the data, the time it takes to do this is negligible.
The bottleneck seems to be the assignment of the data to the cell.

A: Difficult to say what might be cause with so limited information.
But what may be the culprit is the automatic recalculation in XL? Your sheet now recalculates the entire sheet after each Cells(508, loopvar + 2).value = RptPe this may likely be the cause for slow execution.
Maybe you could decorate the While ... Loop with Application.Calculation = xlCalculationManual like below. Though ensure some errorhandling as otherwise your application get's 'stuck' in a non-calculating mode if an error occurs or the code breaks.
Sub Something()
    On Error GoTo ErrorExit
    Application.Calculation = xlCalculationManual

    Sheets("Model").Activate
    YearRange = Range("C7:EZ7").Value

    loopvar = 1
    Do While YearRange(1, loopvar) <> "" And Right(Trim(YearRange(1, loopvar)), 1) <> "E"
        strValue = Trim(YearRange(1, loopvar))
        Year = CInt(strValue)

        GetSpecificData Year, RptPe, RptAvg

        If (RptPe <> 0) Then Cells(508, loopvar + 2).Value = RptPe
        If (RptAvg <> 0) Then Cells(509, loopvar + 2).Value = RptAvg

        loopvar = loopvar + 1
    Loop

ErrorExit:
    Application.Calculation = xlCalculationAutomatic

End Sub


text:
Q: In the vector space, $V =\{f :\mathbb R \longrightarrow\mathbb R\}$, prove that the set $\{\cos 2x, \sin 6x, x^3\}$ is linearly independent. In the vector space, $V = \{f : \mathbb R \longrightarrow\mathbb R\}$, prove that the set $\{\cos{2x},\sin{6x},x^3\}$ is linearly independent.
I've started with $a\cos{2x} + b\sin{6x} + cx^3=0$, trying to prove that $a=b=c=0$
I know when I let $x=0$ I find $a=0$ but I'm unsure where to go from there.
My guess is that the set is linearly dependent.

A: You did well when you started with the equality $a\cos(2x)+b\sin(6x)+cx^3=0$. Now, taking $x=0$, you deduce right away that $a=0$. So, now you just have $b\sin(6x)+cx^3=0$. Take $x=\pi$. Then you deduce that $c=0$. And, of course, the only $b$ for which $b\sin(6x)$ is the null function is $b=0$.

A: The method in the other answers, choosing specific values of $x$ in order to deduce one at a time that $a$, $b$, and $c$ are all $0$, works just fine and has the virtue of working directly with the definition of linear independence. I'm writing this answer just to provide two alternative perspectives:

First, you can look at the three functions in order, and ask of each whether it is a linear combination of the previous functions: is it "redundant"? In other words, we're trying to check that the dimension of the vector subspace they generate increases by one.
For the first, $\cos(2x)$, it's not identically zero so it generates a dimension-one subspace by itself. (It's not a linear combination of the zero functions before it in the list.)
For the second, $\sin(6x)$, it's not always zero when $\cos(2x)$ is zero, so it can't be a multiple of $\cos(2x)$. So $\cos(2x)$ and $\sin(6x)$ generate a two-dimensional subspace.
Finally, is $x^3$ a linear combination of $\cos(2x)$ and $\sin(6x)$? No: one reason is that $\cos(2x)$ and $\sin(6x)$ are both periodic and repeat every $2\pi$ units, so every linear combination is too, while $x^3$ is not. Another reason is that $\cos(2x)$ and $\sin(6x)$ are both bounded, so every linear combination of them is too, but $x^3$ is not. So $\cos(2x)$, $\sin(6x)$, and $x^3$ together generate a three-dimensional subspace, and they must all be linearly independent.

A determinantal perspective is that for smooth functions $f$, $g$, and $h$, if they have some relation $af(x)+bg(x)+ch(x)=0$, then their derivatives have the same relation $af'(x)+bg'(x)+ch'(x)=0$, and so do their second derivatives $af''(x)+bg''(x)+ch''(x)=0$. That means the matrix equation
$$ \begin{pmatrix} f(x) & g(x) & h(x)\\f'(x) & g'(x) & h'(x) \\ f''(x) & g''(x) & h''(x) \end{pmatrix}\begin{pmatrix} a\\ b\\ c\end{pmatrix} = \begin{pmatrix} 0\\0\\0\end{pmatrix} $$
holds identically, so if $a$, $b$, and $c$ aren't all zero then that $3\times 3$ matrix has nontrivial kernel and must have determinant $0$ identically.
This determinant is called the Wronskian of $f$, $g$, and $h$. If you calculate it for $\cos(2x)$, $\sin(6x)$, and $x^3$ you get one, single, complicated function that you only have to check is nonzero in one place to know that they are linearly independent. This technique is especially helpful to show that you've found a basis for all the solutions to a degree-$n$ differential equation, which is known to be $n$-dimensional, so if you have $n$ linearly independent solutions then they must form a basis.

A: Consider
$$\forall x\in \Bbb{R}, a\cos{2x}+b\sin{6x}+cx^3=0$$
As you pointed out by letting $x=0$ you get $a=0$. With $x=\pi$ you get $c\pi^3=0$ i.e $c=0$ (Keep in mind $a=0$)
Now take $x=\pi/12$ you get $b=0$ (Keep in mind $a=c=0$)

A: Assume if possible they are linearly dependent. Now it is obvious that $\sin 6x$ and $\cos 2x$ are linearly independent (cause otherwise, $\sin 6x$ would have been equal to a constant times $\cos 2x$, for all $x$, which is certainly not the case). Now if {$x^3, \sin 6x, \cos x$} are linearly dependent, then for all $x, x^3$ can be represented as a linear combination of $\sin 6x$ and $\cos 2x$. But it is clear that a linear combination of $\sin 6x$ and $\cos 2x$ is again sinusoidal and can not be equal to $x^3$, thus we have arrived at a contradiction.


text:
Q: Solving equations recursively  I am looking at the solution of the following question and wondering how is f(7) equal to 247  in line 1 ?

Given a recursive formula in (1), find the value of f(7)
f(n) =  (2f(n − 1) + n if n > 0
         and 0 if n = 0

1.f(7) = 2f(6) + 7 = 247
2.f(6) = 2f(5) + 6 = 120
3.f(5) = 2f(4) + 5 = 57
4.f(4) = 2f(3) + 4 = 26
5.f(3) = 2f(2) + 3 = 11
6.f(2) = 2f(1) + 2 = 4
7.f(1) = 2f(0) + 1 = 1
8.f(0) = 0

A: I'm going to spell out what I think Mufasa means in their comment. First you write:
$$f(7) = 2\;f(6)+7$$
But you don't know what $f(6)$ is. So you try to compute that:
$$f(6) = 2\;f(5) + 6$$
But you don't know what $f(5)$ is either. So you want to compute that, which requires you to work out $f(4)$, which requires $f(3)$, which requires $f(2)$, which requires $f(1)$. But that last one we can do:
$$f(1) = 2\;f(0) + 1 = 2(0) + 1 = 1$$
Now we can backchain:
$$\begin{eqnarray*}
f(1) &=& 1\\
f(2) &=& 2\;f(1)+2 = 2(1)+2 = 4\\
&\vdots&\\
f(7) &=& 2\;f(6)+7 = 2(120)+7 = 247
\end{eqnarray*}$$


text:
Q: How to translate an advanced SQL statement with LEFT OUTER JOIN to LINQ? I have a similar SQL statement as shown in this example. For the following table
CREATE TABLE [docs] (
  [id] int NOT NULL,
  [rev] int NOT NULL,
  [content] varchar(200) NOT NULL,
  PRIMARY KEY ([id],[rev])
) ;

and the following data
INSERT INTO [docs] ([id], [rev], [content]) VALUES
  (1, 1, 'The earth is flat'),
  (2, 1, 'One hundred angels can dance on the head of a pin'),
  (1, 2, 'The earth is flat and rests on a bull``s horn'),
  (1, 3, 'The earth is like a ball.');

the SQL statement
SELECT d1.*
    FROM docs AS d1
    LEFT OUTER JOIN docs AS d2
    ON (d1.id = d2.id AND d1.rev < d2.rev)
    WHERE d2.id is null
    ORDER BY id;

shows only rows with maximum rev value for each id:
id  rev content
1   3   The earth is like a ball.
2   1   One hundred angels can dance on the head of a pin

My question:
How can I translate this statement to LINQ-to-SQL? The problem in my point of view are the AND and the < in the ON clause.

A: I tried to apply @NetMage's recipe but I got stuck at the < condition:
   using (MyDataContext context = new MyDataContext())
    {
        var query =
            from d1 in context.docs
            join d2 in context.docs on d1.id equals d2.id into jrv
            from x in jrv.Where(x => /* ??? */).DefaultIfEmpty()
            where x equals null
            select x;
        return query.ToArray();
    }

The lambda expression in Where should be a comparison between d1.rev and d2.rev. How can I do that?

A: In general, it is best to translate a SQL LEFT JOIN...WHERE ... = null into an EXISTS which in LINQ is Any:
var ans = from d1 in docs
          join d2 in docs on d1.id equals d2.id into d2j
          where !d2j.Any(d2 => d1.rev < d2.rev)
          orderby d1.id
          select d1;

But, of course, you can translate it into an explicit LINQ null test:
using (MyDataContext context = new MyDataContext()) {
    var query =
        from d1 in context.docs
        join d2 in context.docs on d1.id equals d2.id into d2j
        from d2 in d2j.Where(d2_2 => d1.rev < d2_2.rev).DefaultIfEmpty()
        where d2 == null
        select d1;
    return query.ToArray();
}


text:
Q: Preencher Spinner e ListView - Fragment Estou desenvolvendo uma aplicação com Fragment. Tenho dois fragments, onde em um existe uma ListView e no outro uma Spinner.
A ListView e a Spinner é populada com dados que vem do banco de dados.
Durante a depuração percebi que quando chega no método setAdapter: listView.setAdapter(adapter) ou spinner.setAdapter(adapter) é gerado um erro e entra no bloco Catch(Exception).
O erro que dá é o seguinte:
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

Já acompanhei a depuração, os dados estão vindo do banco de dados, tá tudo correto mais para nesta linha do catch(Execption).
Nos dois casos (preenchimento de Spinner e ListView) o erro é mesmo.
Segue o código do OnCreateView:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View mae = inflater.inflate(R.layout.fragment_usar_produto, container, false);
    spProduto = (Spinner)mae.findViewById(R.id.spProduto);
    npQuantidade = (NumberPicker)mae.findViewById(R.id.npQuantidade);

    npQuantidade.setMinValue(0);
    npQuantidade.setMaxValue(1000);
    npQuantidade.setValue(30);
    npQuantidade.setWrapSelectorWheel(false);

    preencherSpinner();

    btAtualizar = (Button)mae.findViewById(R.id.btAtualizar);
    btAtualizar.setOnClickListener(atualizar);

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_usar_produto, container, false);
}

Agora ó código do método para preencher o Spinner
   public void preencherSpinner()
{
    StringBuilder sql = new StringBuilder();
    sql.append("SELECT * FROM validade ORDER BY produto");

    Validade val = new Validade();

    cursorProdutos = val.listarProduto(getActivity().getBaseContext());

    ArrayList<String> listaProdutos = new ArrayList<String>();

    if (cursorProdutos.moveToFirst()) {
        do {
            listaProdutos.add(cursorProdutos.getString(1));
        } while (cursorProdutos.moveToNext());
    }

    try
    {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_list_item_1,listaProdutos);

        spProduto.setAdapter(adapter);
    }
    catch (Exception ex)
    {
        Log.d("exceção", ex.getMessage());
    }

}


text:
Q: Issues with Creating Vertex and Edges in Titan Graph Database I am trying to create vertex and edges in Titan graph database (Titan1.0.0)..
gremlin> graph = TitanFactory.open('titan-1.0.0-hadoop1/conf/titan-cassandra-es.properties')

gremlin> t1 = graph.addVertex(label, "Testbed", "Name", "testbed1","Status","A","TId",101)
==>v[1228816568]

gremlin> r2= graph.addVertex(label, "Router", "RStatus","F","RId",1002, "TId", 101)
==>v[3686424680]

gremlin> t1.addEdge("tbConRtr", r2)
==>e[kblqtz-kblsxk-d6vp-1oysvhk][1228816568-tbConRtr->3686424680]

Questions:
1) Why is the vertex number returned here are not sequence and it is some random number? For addEdge step also it is creating edge with some random value (kblqtz-kblsxk-d6vp-1oysvhk)
e[kblqtz-kblsxk-d6vp-1oysvhk][1228816568-tbConRtr->3686424680]

2) I want my TId value should be unique
I have tried the following and got Error Msg:
gremlin> mgmt.buildIndex("TId",Vertex.class).addKey(TId).unique().buildCompositeIndex();
No such property: TId for class: groovysh_evaluate

How can I create a unique property value in Titan database?
Kindly help me to resolve this.

A: *

*Vertex ids and edge ids are generated and assigned by Titan. If you want to have your own identifier, you should define a property and index it.

*The error No such property: TId indicates that you are trying to use a variable TId that has not been initialized. You should define the vertex property before trying to index it
gremlin> graph = TitanFactory.open('conf/titan-cassandra-es.properties')
==>standardtitangraph[cassandrathrift:[127.0.0.1]]
gremlin> mgmt = graph.openManagement()
==>com.thinkaurelius.titan.graphdb.database.management.ManagementSystem@4b97b3d2
gremlin> TId = mgmt.makePropertyKey("TId").dataType(Integer.class).cardinality(Cardinality.SINGLE).make()
==>TId
gremlin> mgmt.buildIndex("TId",Vertex.class).addKey(TId).unique().buildCompositeIndex()
==>TId
gremlin> mgmt.commit()
==>null
gremlin> t1 = graph.addVertex(label, "Testbed", "Name", "testbed1","Status","A","TId",101)
==>v[4200]
gremlin> r2= graph.addVertex(label, "Router", "RStatus","F","RId",1002, "TId", 101)
Adding this property for key [TId] and value [101] violates a uniqueness constraint [TId]

Please refer to the Titan documentation on schema and data modeling and also indexing for better performance.


text:
Q: Firebase Database setValue: or removeValue failed: permission_denied iOS I'm trying to write data to Firebase Database but I keep receiving the following error when my saved button is pressed.

2016-12-02 11:09:42.548 StartupNow[1482:60415] [FirebaseDatabase] setValue: or removeValue: at /test/-KY-VpLZWbp4vjF3BpMk failed: permission_denied

Things I've tried:
I've made sure my .read and .write rules were set to true in my console, reconnected my savedButtonPressed button, and wrote the Firebase reference in a function and called it in my savedButtonPressed() method.
Extra Resource Here is the tutorial I'm following along. https://youtu.be/F42CzqIBxHQ?t=4m14s
var ref: FIRDatabaseReference?

override func viewDidLoad() {
    super.viewDidLoad()

    ref = FIRDatabase.database().reference()

}

@IBAction func saveButtonPressed() {
   // TODO: Post data to Firebase

    firebaseChild()
    print("********************************")
    print("********************************")

}

func firebaseChild () {
    ref?.child("Test").childByAutoId().setValue("Hello Firebase")

}

A: I have solved the same issue after trying to use every resource. The only solution is that
Go to fireBase Console -->select your project -->Go to database -->select the Rules("Show in the mid next to the  Data")-->make the make both option true
{
    "rules": {
        ".read": true,
        ".write": true
    }

this will be work perfectly

A: I had a similar issue. It was resolved by resetting the read / write rules for the database. If you changed your rules try reseting them to the default.
Warning: These rules allow anyone to read and write to your database!
Default Rules for Real-time Database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Default Rules for Cloud Firestore
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

A: FreddieOh and I chatted over Slack, and the problem was that the database that was listed in the GoogleService-info.plist file didn't match up with the one he was editing. (It looks like maybe in this case, he had deleted and recreated the project in the Firebase console, but hadn't updated the plist file.)
If you find yourself in the same situation where you've set your read and write access to true and are still getting permission denied errors, open up your GoogleService-info.plist file and look at the entry for  DATABASE_URL. Then go to the Firebase Database in your project, look at the top of the data tab, and confirm that the URL listed there is the same as the one in your plist file.
I suppose the other thing to check for would be that you updated your database rules to allow global access but forgot to click the Publish button. That... may have happened to me at one point. :)

A: Go to your Firebase console, and perform following steps which is identify in image.
Please lookup image and follow these steps. If you are beginner and facing problem in image. I make little video about error.
Video Solution :
https://youtu.be/FcQCPqckvqo
Image Solution

A: Make sure to select real time database and edit the rule then publish .


text:
Q: Cannot read property of "amount" from the request body I am building REST APIs in Nodejs using AWS. I am expecting a response on Postman saying that the
"
Your Bid Must Be Higher than ${auction.highestBid.amount}

"
But instead, I get an Internal Server Error on Postman and the error on AWS Cloudwatch looks like:
enter image description here.
However, I am sending a request on Postman as:
enter image description here
Please help!!
I am Expecting the response as:
Your bid must be higher than
${auction.highestBid.amount}

The patch request body looks like:
enter image description here
While the create Request looks like:
enter image description here
//placeBid.js

const AWS = require('aws-sdk');
const createError = require('http-errors');
const {getAuctionById} = require('./getAuction');

const dynamodb = new AWS.DynamoDB.DocumentClient();
async function placeBid(req) {

  const { id } = req.pathParameters;
  const { amount } = JSON.parse(req.body);
  const auction = getAuctionById(id);
  if(amount <= auction.highestBid.amount)
  throw new createError.Forbidden(`Your Bid Must Be Higher than ${auction.highestBid.amount}`);

  const params = {
    TableName: 'AuctionsTable',
    Key : {id},
    UpdateExpression : 'set highestBid.amount = :amount',
    ExpressionAttributeValues: {
      ':amount' : amount
    },
    ReturnValues : 'ALL_NEW'
  }

  let updatedAuction;
  try {
    const result = await dynamodb.update(params).promise();
    updatedAuction = result.Attributes;
  } catch (error) {
    console.error(error);
    throw new createError.InternalServerError(error);
  }

  return{
    statusCode : 200,
    body : JSON.stringify(updatedAuction)
  }
}

module.exports.handler = placeBid;

//getAuction.js
const AWS = require('aws-sdk');
    const createError = require('http-errors');

    const dynamodb = new AWS.DynamoDB.DocumentClient();

    module.exports.getAuctionById = async(id) => {
      let auction;
      try {
        const result = await dynamodb.get({
          TableName : 'AuctionsTable',
          Key : {id}
        }).promise()
        auction = result.Item;

      } catch (error) {
        console.error(error);
        throw new createError.InternalServerError(error);
      }
      if(!auction){
        throw new createError.NotFound(`Auction with ID ${id} not found`);
      }
      return auction;
    }

    async function getAuction(req) {
      const { id } = req.pathParameters;
      const auction = await getAuctionById(id);
      return{
        statusCode : 200,
        body : JSON.stringify(auction)
      }
    }

    module.exports.handler = getAuction

A: You're throwing an error without catching it
throw new createError.Forbidden(`Your Bid Must Be Higher than ${auction.highestBid.amount}`);, so your Lambda crashes and returns 500 error. That's expected behavior.
Just return a valid response instead
return {
    statusCode : 400,
    body : `Your Bid Must Be Higher than ${auction.highestBid.amount}`
  }

A: getAuctionById is async. It returns a Promise. You have to await it before using its value:
const auction = await getAuctionById(id);

A: If you want to see an example of writing a REST API that uses the AWS SDK for JavaScript (v3) that can invoke AWS Services and return data, see this example in the AWS Code Catelog. Once you successfully build the REST API, you can use Postman to sent requests and view the responses.
This example performs these tasks:

*

*Integrate a React.js web application with AWS services.The React app uses the Rest API (you can also use Postman to view the responses)

*List, add, and update items in an Aurora table.

*Send an email report of filtered work items by using Amazon SES.

*Deploy and manage example resources with the included AWS CloudFormation script.

https://docs.aws.amazon.com/code-library/latest/ug/aurora_example_cross_RDSDataTracker_section.html


text:
Q: Issues detecting textboxes that get generated via a template I am trying to record UI tests for an Aurelia App. I am using Telerik Test Studio and it has issues detecting the textboxes that get generated via a template.
If I use straight HTML in the template e.g.
<input type="text" name="firstname">

That is easily detected and recorded and playback of the test can enter info into that field
In a template if I have textboxes resembling
<textbox name="patientLastName" size="small" editing.bind="editing" if.bind="!demographics.lastName.hidden" required.bind="demographics.lastName.required" label.bind="demographics.lastName.name" value.bind="patient.details.lastName"></textbox>

The template works but I get html resembling
<input class="form-control au-target" type="text" value.bind="value" disabled.bind="!editing" au-target-id="143">

This doesn't appear to be outputting any html attributes/properties that Test Studio can latch onto. How would I alter a textbox so that it is detectable by Test Studio?

A: Could it be that Telerik Test Studio inspects the page too early and that it cannot find elements that are dynamically added? Replace if.bind by show.bind to see if it works.


text:
Q: laravel nova confirm box is there a way to display a confirm box in laravel/ laravel nova if the user changes a certain field?
for example, he changes the field name in the update form, when pressing save a query should come up, you have changed the field name, are you sure?
Thanks for your help


text:
Q: Derivatives using the chain rules I am having problems correctly solving the given question, in which I must solve for $V$, $\frac{dl}{dt}$ for cm/h and m/h, $l$ and the rate of change:
A cubical block of ice is melting in such a way that each edge decreases steadily by 5.5 cm every hour. At what rate is its volume decreasing when each edge is 10 meters long?
My solution is:
$V = l^3\\
\frac{dl}{dt} = 5.5_{cm/h} = 0.055_{m/h} \\
\frac{dV}{dt} = 16.50_{m^3/h}$
where $\frac{dV}{dt} = 3(l)^2 \frac{dr}{dt} \\
 = 3(l)^2 (0.055) \\
= 16.50$
Please notify me on any missteps I have made as this is the incorrect solution to the given problem.

A: The answer (and $\frac{dl}{dt}$) should be negative.  Remember, the sides and volume are decreasing, so the derivatives should be negative.


text:
Q: Creating an Android Bitmap from an Amazon S3 object with BitmapFactory? I have an image in the S3 server stored with the .bmp extension and retrieve the object with a call to getObject(). I then instantiate an InputStream with a call to getObjectContent(). I'm trying to create a bitmap object by passing the inputStream to BitmapFactory's decodeStream() method. As stated in the docs, it is returning null (instead of a Bitmap) presumably because the inputStream "cannot be used to decode a bitmap". Any ideas on why this is happening? Alternatively, ideas on other ways to download a photo from S3 would be greatly appreciated. Thanks so much!
GetObjectRequest getPhoto = new GetObjectRequest(MainActivity.USERS_BUCKET_NAME, finalList.get(i));
S3Object photoObject = s3.getObject(getPhoto);
InputStream inputStream = photoObject.getObjectContent();
//process inputStream
Bitmap bmp = BitmapFactory.decodeStream(inputStream); //this is returning null
//close inputStream
try {
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

A: I fixed the problem by using the Apache Commons IOUtils library - I converted the inputstream into a byte array with IOUtils.toByteArray(inputStream) and passed that into BitmapFactory.decodeByteArray(); it no longer returns null.


text:
Q: Type error occurred: list indices must be integers Im trying to load a json file and loop through the dictionary to get the key values of my choice, after that I will be saving those values in an excel sheet using pandas dataframe. But when I run load the document, I'm getting the error
TypeError: list indices must be integers or slices, not str
Below is my entire code in order to achieve that,
import json
import pandas as pd
import requests

URLs = ['http://httpbin.org/ip',
'http://httpbin.org/user-agent',
'http://httpbin.org/headers']

json_list = []
for url in URLs:
    data = requests.get(url)
    resolvedwo = data.json()
    json_list.append(resolvedwo)

    with open('resolvedworesolution.json', 'w+') as f:
        json.dump(json_list, f, sort_keys=True, indent = 4)
with open('C:\\Users\\resolvedworesolution.json', encoding='utf-8') as f:
    data = json.load(f)
columns = ['Title', 'Status']
df_ = pd.DataFrame(columns=columns)
for ib in data['documents']:
    tit = ib['title']
    stat = ib['status']
print(tit, stat)
df_ = df_.append(pd.Series([tit, stat], index=df_.columns), ignore_index=True)
df_.to_excel('C:\\Users\\resolved_wo_resolution.xls', index=False)

Note: The URLs mentioned above is for example only. The URL which I am using is the Internal, so I can't share it here. Thus the URL will return the JSON data looks like below.
EDITED json:
[
    {
        "documents": [
            {
                "title": [Sample Title 1],
                "status": [true]
            },
            {
                "title": [Sample  Title 2],
                "status": [false]
            }
        ]
    }
]
    [
    {
        "documents": [
            {
                "title": [Sample Title 1],
                "status": [true]
            },
            {
                "title": [Sample  Title 2],
                "status": [false]
            }
        ]
    }
]
    [
    {
        "documents": [
            {
                "title": [Sample Title 1],
                "status": [true]
            },
            {
                "title": [Sample  Title 2],
                "status": [false]
            }
        ]
    }
]

A: The origin of your issue is here
for ib in data['documents']:

Your data is a list. So you can't use a string as an index into it.
You have a few options. if you know the list is always one entry (it will break for 0 entries), or if you only care about the first entry
for ib in data[0]['documents']:
    # etc...

If you want to process all entries use a loop
for d in data:
    for ib in d['documents']:
        # etc...

When you have errors like this, please post the full traceback error. If we dont have this information we need to run the code ourselves and it takes longer.
e.g.
Traceback (most recent call last):
  File "pdcrash4.py", line 21, in <module>
    for ib in data['documents']:
TypeError: list indices must be integers or slices, not str


text:
Q: How to get the Service URL of a deployed bot application in Microsoft Bot framework?
I am using DirectLine API to send message to the bot, I need the service URL of the Published Bot to perform a post request for the load test as mentioned in the steps here https://blog.botframework.com/2017/06/19/Load-Testing-A-Bot/
This is the code, can anyone point where I am going wrong
private static async Task<Chat> TalkToTheBot(string Message)
        {
            Chat objChat = null;
            // Connect to the DirectLine service
            try
            {
                DirectLineClient client = new DirectLineClient(directLineSecret);

                Conversation conversation = await client.Conversations.StartConversationAsync();

                string watermark = null;

                Activity reply = new Activity
                {
                    From = new ChannelAccount("User1", "User Name"),
                    Text = "Hello",
                    Type = ActivityTypes.Message,
                };

                //await client.Conversations.PostActivityAsync(conversation.ConversationId, reply.CreateReply(text: Message, locale: "en-US"), CancellationToken.None);
                await client.Conversations.PostActivityAsync(conversation.ConversationId,reply , CancellationToken.None);

                // Get the response as a Chat object
                objChat = await ReadBotMessagesAsync(client, conversation.ConversationId, watermark);
            }
            catch (Exception e)
            {

                throw;
            }
            // Return the response as a Chat object
            return objChat;
        }

        private static async Task<Chat> ReadBotMessagesAsync(DirectLineClient client, string conversationId, string watermark)
        {
            // Create an Instance of the Chat object
            Chat objChat = new Chat();

            // We want to keep waiting until a message is received
            bool messageReceived = false;

            while (!messageReceived)
            {
                // Get any messages related to the conversation since the last watermark
                ActivitySet messages = await client.Conversations.GetActivitiesAsync(conversationId, watermark, CancellationToken.None);

                // Set the watermark to the message received
                watermark = messages?.Watermark;
                // Get all the messages
                var messagesFromBotText = from message in messages.Activities
                                          where message.From.Id == botId
                                          select message;
                // Loop through each message
                foreach (var message in messagesFromBotText)
                {
                    // We have Text
                    if (message.Text != null)
                    {
                        // Set the text response
                        // to the message text
                        objChat.ChatResponse
                            += " "
                            + message.Text.Replace("\n\n", "<br />");
                    }
                }
                // Mark messageReceived so we can break
                // out of the loop
                messageReceived = true;
            }
            // Set watermark on the Chat object that will be
            // returned
            objChat.watermark = watermark;
            // Return a response as a Chat object
            return objChat;
        }

A: Per the article,

The serviceUrl property here is critical to note, and needs to be set
  to the endpoint of your message sink/client.

and:

In order to test your bot, you'll need to create a custom UI/message
  sink to send and receive messages to your bot. This message sink will
  effectively act like a channel and accept HTTP POST messages with
  JSON-serialized bot framework activities.

Which basically means that you will have to build a "message client" and the url of that client is the one that you will have to provide in the serviceUrl of your request.


text:
Q: Javascript: Convert a String to Regular Expression I want to convert a string that looks like a regular expression...into a regular expression.
The reason I want to do this is because I am dynamically building a list of keywords to be used in a regular expression. For example, with file extensions I would be supplying a list of acceptable extensions that I want to include in the regex.
var extList = ['jpg','gif','jpg'];

var exp = /^.*\.(extList)$/;

Thanks, any help is appreciated

A: You'll want to use the RegExp constructor:
var extList = ['jpg','gif','jpg'];
var reg = new RegExp('^.*\\.(' + extList.join('|') + ')$', 'i');

MDC - RegExp

A: var extList = "jpg gif png".split(' ');
var exp = new RegExp( "\\.(?:"+extList.join("|")+")$", "i" );

Note that:

*

*You need to double-escape backslashes (once for the string, once for the regexp)

*You can supply flags to the regex (such as case-insensitive) as strings

*You don't need to anchor your particular regex to the start of the string, right?

*I turned your parens into a non-capturing group, (?:...), under the assumption that you don't need to capture what the extension is.

Oh, and your original list of extensions contains 'jpg' twice :)

A: You can use the RegExp object:
var extList = ['jpg','gif','jpg'];

var exp = new RegExp("^.*\\.(" + extList.join("|") + ")$");


text:
Q: Format of 2013-04-09T10:00:00Z in php I'm looking for the date() format that will give me a date like this:
2013-04-09T10:00:00Z

Is there something simpler than just using the format 'Y-m-d ...'?

A: date("c");

may be what you search? The suffix you can change yourself with explode etc.

A: The date format 'c' (ISO 8601) used with gmdate() (for UTC time) comes very close:
2013-04-09T10:00:00+00:00

You just need to modify it by replacing the trailing +00:00 with Z (for Zulu):
echo substr_replace(gmdate('c'), 'Z', -6);

The alternative is simply this:
echo gmdate('Y-m-d\TH:i:s\Z');