text:
Q: Google Chart with slicer returns: One or more participants failed to draw()× I'm a little bit lost with Google Charts's DateRangeFilter. Upon drawing the dashboard, I'm getting the error message "One or more participants failed to draw()×". I'm not quite sure why this is happening, but my hunch says it is due to the Date object. The jsonHRData date rows looks like "Date {Sat Feb 15 2014 15:17:33 GMT+0100 (CET)}". Initially my JSON returned ISO formatted dates, which I converted to the JavaScript date format using this approach.
Note that the slicer itself is drawn, but not the ColumnChart itself. Every time I slice, the error message repeats itself.
function drawDashboard() {
  var jsonHRData = $.ajax({
      url: "heartrate.json",
      dataType:"json",
      async: false,
      converters: {
        "text json": function (data) {
            return $.parseJSON(data, true);
        }
       },
      success: function (data) {
        console.log(data);
       }
      }).responseJSON;

  // Create a dashboard.
  var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard_div'));

  // Create a range slider, passing some options
 var dateRangeSlider = new google.visualization.ControlWrapper({
    'controlType': 'DateRangeFilter',
    'containerId': 'filter_div',
    'options': {
        'filterColumnLabel' : 'Date'

    }
});

  // Create our data table out of JSON data loaded from server.
  var HRdata = new google.visualization.DataTable(jsonHRData);

  // Instantiate and draw our chart, passing in some options.
  var heartrateChart = new google.visualization.ChartWrapper({
    'chartType': 'ColumnChart',
    'containerId': 'heartrate_container',
    'options': {
        'width': 400,
        'height': 240,
        'colors': '#f3b49f'
    }
});

// Establish dependencies, declaring that 'filter' drives 'heartrateChart',
// so that the column chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind(dateRangeSlider, heartrateChart);

// Draw the dasbhoard
dashboard.draw(HRdata);
}

My JSON looks as follows:
{"cols":[{"id":"Date","label":"Date","type":"date"},{"id":"Average Heartrate","label":"Average Heartrate","type":"number"}],"rows":[{"c":[{"v":"2014-02-15T14:17:33Z"},{"v":158.4}]},{"c":[{"v":"2014-02-13T18:32:33Z"},{"v":170.7}]},{"c":[{"v":"2014-02-10T18:59:20Z"},{"v":161.7}]},{"c":[{"v":"2014-02-08T14:05:21Z"},{"v":171.1}]},{"c":[{"v":"2014-02-06T18:16:06Z"},{"v":168.4}]}]}

Many thanks!

A: The resolution was to place my ChartWrapper DIV container (here heartrate_container) outside of the ControlWrapper filter DIV container. It seemed Google Chart API was unable to find the respective element. Placing the ChartWrapper DIV outside the filter_div, as shown in the example below would solve the issue.

Hence, the below would not work:


text:
Q: MS Access 2000 to MS Access 2007 migration I have application in MS Access 2000.
It is connected to Oracle 9.2.06 database.
I have to migrate the application to MS Access 2007 and Oracle 11G.
I've created a blank .accdb file and imported all the objects from MS Access 2000 (.mdb) file, except the linked tables
While Linking MS Access 2007 with Oracle 11G database tables, i'm getting an error saying
"ODBC--call failed"
I've checked for Machine DSN, System DSN and its configured well alongwith ODBC Drivers.
Also, when i launch the application i'm getting an error as below:
"Error while connecting to '%Oracle database SID%'"
Could you please help me to resolve this issue.

A: Have you re-created all your ODBC links on your computer (in Administrator panel)?  The ODBC is going to be different from Oracle 9.2 to 11.

A: you may need to import and reference libraries being used - check the Visual Basic Editor and confirm that all applicable libraries have been brought in.
The previously linked tables may have the credentials saved, or may not - you will have to check the properties of the linked table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create step by step annotated programming tutorial  in LaTeX? (question inspired by How to create a crossword puzzle in LaTeX? and provided solutions)
How to make in most comfortable way in LaTeX (I use pdfLaTeX, but I am open for LuaTeX solutions) annotated, step by step, programming tutorials?
Preferably from annotated sourcecode? Or in other way, by less effort than typing each slide by slide.
I means questions and answers tutorial in form of presentation (I don't know if beamer is the only solution for presentations, but I've heard it's popular one).
Here is an example how such presentation would look like:
*-------------------------------------------*
|      How to implement Main function?      |
|                                           |
|                                           |
| (1)?                                      |
|                                           |
|                                           |
|                                           |
|                                           |
|    (2)?                                   |
| (1)                                       |
|                                           |
| (1) ... ?                                 |
| (2) ... ?                                 |
*-------------------------------------------*

*-------------------------------------------*
|              Main function                |
|                                           |
|                                           |
| int main(){ (1)                           |
|                                           |
|                                           |
|                                           |
|                                           |
|    return 0; (2)                          |
| } (1)                                     |
|                                           |
| (1) ...                                   |
| (2) ...                                   |
*-------------------------------------------*

*-------------------------------------------*
|        How to perform Computation?        |
|                                           |
|                                           |
| int main(){                               |
|    (3)?                                   |
|                                           |
|    (4)?                                   |
|                                           |
|    return 0;                              |
| }                                         |
|                                           |
| (3) ...?                                  |
| (4) ...?                                  |
*-------------------------------------------*

*-------------------------------------------*
|              Computation                  |
|                                           |
|                                           |
| int main(){                               |
|    long a,b,c; (3)                        |
|                                           |
|    c = a * b; (4)                         |
|                                           |
|    return 0;                              |
| }                                         |
|                                           |
| (3) ...                                   |
| (4) ...                                   |
*-------------------------------------------*

*-------------------------------------------*
|            Input & Output  ?              |
|                                           |
| (5) ?                                     |
| int main(){                               |
|    long a,b,c;                            |
|    (6) ?                                  |
|    c = a * b;                             |
|    (6) ?                                  |
|    return 0;                              |
| }                                         |
|                                           |
| (5) ...?                                  |
| (6) ...?                                  |
*-------------------------------------------*

*-------------------------------------------*
|            Input & Output                 |
|                                           |
| #include <cstdio> (5)                     |
| int main(){                               |
|    long a,b,c;                            |
|    scanf("%ld%ld", &a, &b); (6)           |
|    c = a * b;                             |
|    printf("%ld\n", c); (6)                |
|    return 0;                              |
| }                                         |
|                                           |
| (5) ...                                   |
| (6) ...                                   |
*-------------------------------------------*

A: An interactive version with beamer may be constructed along the following lines:
\documentclass{beamer}

\begin{document}

\begin{frame}[fragile]%
\begin{semiverbatim}
\frametitle{Input \&\ Output}
\#include <cstdio>
\only<1>{(1)?}\only<2->{int main() \{}
   \only<3>{(3)?}\only<4->{long a,b,c;}
   \only<4>{(4)?}\only<5->{std::scanf("\%ld\%ld", \&a, \&b);}
   \only<5>{(5)?}\only<6->{c = a * b;}
   \only<6>{(6)?}\only<7->{std::printf("\%ld\textbackslash n", c);}
   \only<2>{(2)?}\only<3->{return 0;}
 \}
\end{semiverbatim}
\end{frame}

\end{document}


text:
Q: Pagination in PHP using For Loop echo "
";
                for ($b=1;$b<=$a;$b++)
                {

                    ?>
<a href = "pbycategories.php?page=<?php echo $b; ?>"><?php echo $b; ?>
<?php

                }

                echo "
";

    ul.pagination {
display: inline-block;
padding: 0;
margin: 0;

}

ul.pagination li {display: inline;}

ul.pagination li a {
color: black;
float: left;
padding: 8px 16px;
text-decoration: none;
transition: background-color .3s;
border: 1px solid #ddd;

}

 .pagination li:first-child a {
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
}

.pagination li:last-child a {
border-top-right-radius: 5px;
    border-bottom-right-radius: 5px;
}

ul.pagination li a.active {
background-color: #4CAF50;
color: white;
border: 1px solid #4CAF50;
}

ul.pagination li a:hover:not(.active) {background-color: #ddd;}

I need help in for loops .. my pagination looks like this
1      -----         2         -----     3     -----           4
5       -------          6      -----             7      -----          8


text:
Q: Accessing a vector from dput structure I am trying to iterate over a list in R and have hit a roadblock...
The goal is to write this data out to a data.frame which I will then write to an Excel spreadsheet (seems to be by and far the easiest way to create an Excel spreadsheet from R using the xlsx library) with each Tab1, Tab2, etc corresponding to a sheet in a workbook.
Using
dput(MyRObject,file="", control=c("useSource"))

in R I have a structure that looks like this (not cleaned up per an SO suggestion)....
list(tab1 = list(PData = c(0.8, 0.9, 0.95, 0.995, 0.24661,
0.17913, 0.13058, 0.04435, 0.579631613406504, 0.993273399970982,
1.38978824245787, 2.35062458463194), NData = c(0.8, 0.9, 0.95,
0.995, 0.75339, 0.82087, 0.86942, 0.95565, 0.579631613406505,
0.993273399970982, 1.38978824245787, 2.35062458463194)), tab2 = list(
    PData = c(0.8, 0.9, 0.95, 0.995, 0.2, 0.14286, 0.1029,
    0.03423, 0.8496, 1.28071636787584, 1.65931628110111, 2.48854182345497
    ), NData = c(0.8, 0.9, 0.95, 0.995, 0.8, 0.85714, 0.8971,
    0.96577, 0.849600000000001, 1.28071636787583, 1.65931628110111,
    2.48854182345497)), tab3 = list(PData = c(0.8, 0.9, 0.95,
0.995, 0.14286, 0.1, 0.07104, 0.02308, 1.28071636787584, 1.6896,
2.01379602569623, 2.64732002458351), NData = c(0.8, 0.9, 0.95,
0.995, 0.85714, 0.9, 0.92896, 0.97692, 1.28071636787584, 1.6896,
2.01379602569622, 2.64732002458351)))

I'm trying to coerce each "Tab" into a data.frame so each tab in my spreadsheet looks like this..
Tab1's worksheet would look like this after formatting the vector to 3 columns
PData
Sensitivity Optimal Relative
0.8         0.24661    0.57963
0.9         0.17913    0.99327
0.95        0.13058    1.3898
0.995       0.04435    2.3506

NData
Sensitivity  Optimal   Relative
0.8          0.75339    0.57963
0.9          0.82087    0.99327
0.95         0.86942    1.3898
0.995        0.95565    2.3506

and so for Tab 2, Tab3...
I have gotten as far as partially iterating over it, like this......
using a function like this....
nametree(myListData)

nametree <- function(X, prefix = ""){
  if( is.list(X) )
    for( i in seq_along(X) ) {
      cat( prefix, names(X)[i], "\n", sep="" )
      nametree(X[[i]], paste0(prefix, "--->"))
    }
}

That gets me....
tab1
--->PData
--->NData
tab2
--->PData
--->NData

How do I access the vector for PData and NData from dput? I'm sure there's an easier way but my lack of R knowledge is making this difficult.


text:
Q: Powershell concatenate comboboxes Hello All and thank you for taking the time to read my post.
I am working in Powershell 5.0 with the AD Cmdlets module installed. I am having issues with Comboboxes concatenating. Specifically, I have 2 comboboxes where the first combobox looks at a given OU path in our AD tree and displays, via a drop down menu, the OUs underneath that OU. Sub OUs if you will. That return is represented by variable $OU which is then input into the next OU path in the next combobox. Basically I am adding $OU to the OU path of the first combobox and then the 2nd combobox displays the sub OUs.
I will submit the part of the code that is having errors, then the full code for your reference:
$Floor = @(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase 'OU=Desktops,OU=Workstations,OU=PMC,OU=facilities,DC=tenethealth,DC=net' -SearchScope OneLevel | Select-Object -ExpandProperty name)

$FloorDDB = New-Object System.Windows.Forms.ComboBox
$FloorDDB.location = New-Object system.drawing.size(20, 50)
$FloorDDB.size = New-Object system.drawing.size( 180, 20)
$FloorDDB.Height = 400
$FloorDDB.items.AddRange(@($Floor))

# I have tried convert.tostring as well as just using $OU=$FloorDDB.SelectedItem and
# $OU=$FloorDDB.Text
$OU = convert.tostring($FloorDDB.SelectedItem)
$FloorSelect = @(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase "OU=$OU,OU=Desktops,OU=Workstations,OU=PMC,OU=facilities,DC=tenethealth,DC=net" -SearchScope OneLevel | Select-Object -ExpandProperty name)

$DeptDDB = New-Object System.Windows.Forms.ComboBox
$DeptDDB.Location = New-Object System.Drawing.Size(20, 125)
$DeptDDB.size = New-Object System.Drawing.Size(180, 20)
$DeptDDB.Height = 400
$DeptDDB.items.Addrange(@($FloorSelect))

The first Combobox, $FloorDDB, works as it should. However, I get this error:

convert.tostring : The term 'convert.tostring' is not recognized as the name of a cmdlet, >
function, script file, or operable program. Check the spelling of the name, or if a path was
included, verify that the path is correct and try again.
At H:\Scripts\CurrentProject\Static2DHCP.ps1:32 char:7

*

*$OU = convert.tostring($FloorDDB.SelectedItem)

*
  ~~~~~~~~~~~~~~~~

*

*CategoryInfo          : ObjectNotFound: (convert.tostring:String) [], > CommandNotFoundException

*FullyQualifiedErrorId : CommandNotFoundException

If I take out the convert.tostring and replace with something more direct like $OU=$FloorDDB.text I get this error:

Get-ADOrganizationalUnit : The object name has bad syntax
At line:25 char:18

*

*... rSelect = @(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBa ...

*
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*

*CategoryInfo          : NotSpecified: (:) [Get-ADOrganizationalUnit], ADException

*FullyQualifiedErrorId : >
ActiveDirectoryServer:8335,Microsoft.ActiveDirectory.Management.Commands.GetADOrganizationalUnit

If I replace the $OU with the actual name everything works fine. So I know my syntax is good its just the variable concatenating is the problem.
Here is the full code:
### Purpose of this script is to read a list of PCs and change each PC in that list from static IP to DHCP. DNS server must remain.

# First task is to refer to a list or group. GUI will specify PCs to be target.

Add-type -AssemblyName System.windows.forms
Add-type -AssemblyName System.Drawing

$Form = New-Object System.Windows.Forms.Form
$Form.size = New-Object System.Drawing.size(400, 300)

$cancelButton = New-Object System.Windows.Forms.Button
$cancelButton.text = "Cancel"
$cancelButton.size = New-Object System.Drawing.size(80,50)
$cancelButton.location = New-object system.drawing.point(250, 150)
$cancelButton.add_click({$form.tag = $form.close()})

$button = New-Object System.Windows.Forms.Button
$button.location = New-Object system.drawing.size(250, 50)
$button.size = New-Object system.drawing.size(80, 50)
$button.text = "Confirm Selection"

$Floor = @(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase 'OU=Desktops,OU=Workstations,OU=PMC,OU=facilities,DC=tenethealth,DC=net' -SearchScope OneLevel | Select-Object -ExpandProperty name)

$FloorDDB = New-Object System.Windows.Forms.ComboBox
$FloorDDB.location = New-Object system.drawing.size(20, 50)
$FloorDDB.size = New-Object system.drawing.size( 180, 20)
$FloorDDB.Height = 400
$FloorDDB.items.AddRange(@($Floor))

$OU = convert.tostring($FloorDDB.SelectedItem)
$FloorSelect = @(Get-ADOrganizationalUnit -LDAPFilter '(name=*)' -SearchBase "OU=$OU,OU=Desktops,OU=Workstations,OU=PMC,OU=facilities,DC=tenethealth,DC=net" -SearchScope OneLevel | Select-Object -ExpandProperty name)

$DeptDDB = New-Object System.Windows.Forms.ComboBox
$DeptDDB.Location = New-Object System.Drawing.Size(20, 125)
$DeptDDB.size = New-Object System.Drawing.Size(180, 20)
$DeptDDB.Height = 400
$DeptDDB.items.Addrange(@($FloorSelect))

$PCTB= New-Object System.Windows.Forms.TextBox
$PCTB.location = New-Object system.drawing.size(20, 200)
$PCTB.size = New-Object System.Drawing.Size(180, 20)
$PCTB.Height = 400

$form.controls.add($cancelButton)
$form.controls.add($button)
$form.controls.add($FloorDDB)
$form.controls.add($deptDDB)
$Form.controls.add($PCTB)

#Commented until script is done to avoid annoying loss of network access
#Get-NetAdapter -Name Ethernet | Set-NetIPInterface -Dhcp Enabled

[void]$Form.ShowDialog()

In summation:
2 Comboboxes. 1st combobox has the user select a floor OU. The 2nd combobox references the first combobox and displays the departments OU located within that floor OU.
Thank you for your time. Apologize for the wall of text.


text:
Q: codeigniter cannot extends the My_Controller.php I have created MY_Controller.php in the core folder. I autoloaded all the libraries and model that i want in my website. And also put some data in the MY_Controller.php. but when I extend this controller by another controller the data cannot be extended in the second controller. This is MY_Controller.php code.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
   public $data;
   public function __contstruct()
    {
        parent::__construct();
        date_default_timezone_set('Asia/Karachi');
        $this->load->library(array('ion_auth', 'form_validation','form'));
        /*-Website Developer Information-*/

        $this->data['FullName']="Waqas Dev lover";
        $this->data['ShortName']="Dev Lover";
        $this->data['Mobile']="03049211134";
        $this->data['Version']="1.0.1";
        $this->data['Copyright']="Waqas Dev Lover";
        $this->data['Year']=date("Y");
        $this->data['DevelopedBy']="Waqas Dev Lover";
        $this->data['DevelopedByUrl']="http://www.facebook.com/xndltwaqas1";
        /* -End of Website Developer Information- */
        /*System Information */
        $this->data["SectionH1"]="Admin panel";
        /*End of System Information */

        /*User Information */
       $user_id =$this->session->userdata('user_id');
       //echo  =$this->ion_auth->logged_in();
       //exit;
        $this->data['user'] = $this->ion_auth->user($user_id)->row();
        //$this->get_user_groups($user_id);
        $this->data['group']=$this->ion_auth_model->get_users_groups($user_id)->result();
        //var_dump($this->data['group']);
        //exit();
        /*End User Information */
    }

     public function show($path,$data=NULL){
        if($data === NULL){
            $data = $this->data;
            var_dump($data); exit;
        }
        $this->load->view("template/header",$data);
        $this->load->view("template/sidebar",$data);
        $this->load->view($path,$data);
        $this->load->view("template/footer",$data);
    }
}
?>

And this is the Dashboard.php in which I want to extends the MY_Controller.php. But it Won't extends the Data in the Dashboard.php.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Dashboard extends MY_Controller{
    public function index(){
        $this->show("admin/home");
    }
}

A: You can already add, append or reset your $this->data from MY_Controller without the need to pass extra data array to show.
public function show($path)
{
    $this->load->view("template/header", $this->data);
    $this->load->view("template/sidebar", $this->data);
    $this->load->view($path, $this->data);
    $this->load->view("template/footer", $this->data);
}

and in your dashboard you can use it directly:
class Dashboard extends MY_Controller
{
    public function index()
    {
        $this->data['foo'] = 'bar';
        $this->show("admin/home");
    }
}

you can now access $foo in your dashboard view


text:
Q: Powershell - RegEx matching form elements by fullname via Get-Variable How can you use Get-Variable pipe to operate on specific WinForm objects that match a RegEx to the Fullname property? Attempts to use Where-Object {($_).GetType().FullName -match '^System\.Windows\.Forms'} fail.
In the example below ($TestButton).GetType().FullName does return System.Windows.Forms.Button. But referencing with ($_).GetType().FullName returns System.Management.Automation.PSVariable.
Why does this not work, does a near or equivalent exist?
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
Remove-Variable * -ErrorAction SilentlyContinue
$form                            = New-Object system.Windows.Forms.Form;
$form.ClientSize                 = New-Object System.Drawing.Point(100,100);
$form.text                       = "Form";
$TestButton                         = New-Object system.Windows.Forms.Button
$TestButton.text                    = "Test"
$TestButton.width                   = 85
$TestButton.height                  = 30
$TestButton.location                = New-Object System.Drawing.Point(0,0)
$TestButton.Font                    = New-Object System.Drawing.Font('Microsoft Sans Serif',12)

($TestButton).GetType().FullName # This gives output
Get-Variable |
#Where-Object {($_).GetType().FullName -match '^System\.Windows\.Forms'} | # Line disabled for debugging only.
Foreach-Object{
                    $form.controls.Add($_) # Not working - obvious why due to output below - nothing matches...
                    ($_).GetType().FullName# due to System.Management.Automation.PSVariable
}
$form.controls.AddRange(@($TestButton)) # Works as expected.
[void]$form.ShowDialog()

A: You could use
Get-Variable | where {$_.Value -is [system.windows.forms.button]}

or
Get-Variable | where {$_.Value.gettype().fullname -match 'system\.windows\.forms'}

A: It does work, just as intended. You're just working with different object types.
$TestButton is an object of type System.Windows.Forms.Button
When you run Get-Variable, it returns objects of type System.Management.Automation.PSVariable
if you run Get-Variable -Name TestButton You'll see that by default, it returns Name and a value field. This is the name of the variable, and the value of said variable.
What I assume you're looking to do, is extract the value of that variable, and get the type of the actual value. You would do this like this
(Get-Variable -Name TestButton | % Value).GetType().Fullname

So for your Get-Variable pipe
Get-Variable |
  Where-Object {$_.value -is [System.Windows.Forms.Button]} |
  Foreach-Object{
    $form.controls.Add($_.value)
  }


text:
Q: SQL Server / C# : Filter for System.Date - results only entries at 00:00:00 I have a connected SQL Server database in Visual Studio and am displaying its content in a grid. I created a dropdown menu with the column names as selectable options and a text field to filter for specific content, e.g., DropDown = "Start" - Textfield = 14.03.2015 = Filter Column "Start" for each entry that contains "14.03.2015" - and display it in the Grid.
I'm basically done with that part. The only problem left that I'm facing is whenever I enter a date - e.g., 14.03.2015 it only displays dates which start at 00:00:00 - the other entries that do not start at 00:00:00 are ignored and I can't figure out how to modify this to work properly.
The Grid looks like this: http://abload.de/img/untitled123yqkyn.png
And I am using the following C# code to filter:
protected void Button1_Click(object sender, EventArgs e)
{
    string FilterExpression = string.Empty;

    if (DropDownList1.SelectedValue.ToString().Equals("Start"))
    {
        FilterExpression = string.Format("Start  = '{0}'", TextBox1.Text);
    }
    else if (DropDownList1.SelectedValue.ToString().Equals("End"))
    {
        FilterExpression = string.Format("End  = '{0}'", TextBox1.Text);
    }
    else if (DropDownList1.SelectedValue.ToString().Equals("Creation Time"))
    {
        FilterExpression = string.Format("DateTimeCreated = '{0}'", TextBox1.Text);
    }
    else if (DropDownList1.SelectedValue.ToString().Equals("Last Modified"))
    {
        FilterExpression = string.Format("LastModifiedTime = '{0}'", TextBox1.Text);
    }
    else
    {
        FilterExpression = string.Concat(DropDownList1.SelectedValue, " Like '%{0}%'");
    }

    SqlDataSource1.FilterParameters.Clear();
    SqlDataSource1.FilterParameters.Add(new ControlParameter(DropDownList1.SelectedValue, "TextBox1", "Text"));
    SqlDataSource1.FilterExpression = FilterExpression;
}

This is my Grid:

        Organizer
        Room
        Creation Time
        Start
        End
        Last Modified

    <asp:TextBox ID="TextBox1" runat="server" Width="315px"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px"/>
    <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Reset Search" Width="100px"/>

    <asp:GridView ID="GridView1" runat="server" BorderColor="#F9F9F9" BorderStyle="Solid" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" AllowSorting="True"  pagesize="1000" AllowPaging="True" HorizontalAlign="Center">
    <AlternatingRowStyle BackColor="White"/>

        <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" ItemStyle-HorizontalAlign="Center"/>
        <asp:BoundField DataField="Organizer" HeaderText="Organizer" SortExpression="Organizer" ConvertEmptyStringToNull="False" HtmlEncode="False" HtmlEncodeFormatString="False" InsertVisible="False"/>
        <asp:BoundField DataField="Room" HeaderText="Room" SortExpression="Room"/>
        <asp:BoundField DataField="DateTimeCreated" HeaderText="Creation Time" SortExpression="DateTimeCreated"/>
        <asp:BoundField DataField="Start" HeaderText="Start" SortExpression="Start" />
        <asp:BoundField DataField="End" HeaderText="End" SortExpression="End"/>
        <asp:BoundField DataField="LastModifiedTime" HeaderText="Last Modified" SortExpression="LastModifiedTime" />
        <asp:CheckBoxField DataField="Cancelled" HeaderText="Cancelled" SortExpression="Cancelled" ItemStyle-HorizontalAlign="Center" />
        </Columns>

    <EditRowStyle BackColor="#2461BF"/>
    <FooterStyle BackColor="#E1000F" Font-Bold="True" ForeColor="White"/>
    <HeaderStyle BackColor="#E1000F" Font-Bold="True" ForeColor="White" Font-Underline="false"/>
    <PagerStyle BackColor="#E1000F" ForeColor="White" HorizontalAlign="Center"/>
    <RowStyle BackColor="#F9F9F9"/>
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333"/>
    </asp:GridView>

    <asp:SqlDataSource ID="xyz" runat="server" ConnectionString="<%$ ConnectionStrings:VCConnectionString %>" SelectCommand="SELECT * FROM [xyz]"></asp:SqlDataSource>

Please excuse the quality of the code, I'm completely new to C# and for that matter programming in itself. I hope that there is someone able to help me.

A: What happens if you change all of the filters to use 'LIKE':
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
    FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text);
}

Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date.
Update
Or perhaps you could try this...
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
    FilterExpression = string.Format("Start >= '{0} 0:00:00' AND Start <= '{1} 23:59:59'", TextBox1.Text, TextBox1.Text);
}

Update 2
... Or if you really want to make sure you get all records from that final second of 23:59:59, you could use this (I think)...
if (DropDownList1.SelectedValue.ToString().Equals("Start"))
{
    FilterExpression = string.Format("Start >= '{0} 0:00:00' AND Start < DATEADD(day,1,'{1}')", TextBox1.Text, TextBox1.Text);
}

Notice that the version looks for records less than your given date "plus one day".
Personally, I would use the "Update 1" script, and compare the dates against 23:59:59, even though, yes, it would ignore records created in that final second of the day (eg at 23:59:59.403).

A: The problem is due to the fact you're filtering on a datetime value; if you set only the date part the system interprets it as at midnight. Try to pass also the time value and it will work.
EDIT:
The problem is due the conversion from string and datetime:
   else
    {
        FilterExpression = string.Concat(DropDownList1.SelectedValue, " Like '%{0}%'");
    }

Perhaps changing your logic to use the value as a dateime should work.
In the folowing example the first doesn't work, the second one does:
SELECT *
FROM [Events]
WHERE EventDate LIKE '%2012-06-08%'
SELECT *
FROM [Events]
WHERE EventDate >= '2012-06-08' AND EventDate <= '2012-06-08 23:59:59'


text:
Q: Fill an array with different classes which all inherit from the same class My situation looks something like this:
class Parent;

class Child1 : public Parent;
class Child2 : public Parent;

class ChildOfChild1 : public Child1;

std::vector<std::vector<Parent>> matrix;

I want to be able to contain all the classes within this one matrix but I am not sure of the best way to do it.
Right now if left as it is every Child I add to the matrix just gets converted into a Parent with all the methods and variables not contained in the Parent removed.
I know something like this should be possible in Java which is also strictly typed so I thought I might ask if it is also possible in C++.

A: I think it is a duplicate of this question
The thing you want to use is called Object Slicing
Try this:
std::vector<std::vector<Parent*>> matrix


text:
Q: Translating data with xml I have a small data about some movies as an example
title:The matrix
year: 1999
directors: Andy and Lana Watchowski
writers:Andy and Lana Watchowski
stars: Keanu reeves, carrie fisher
title: star wars
year: 1977
director: George Lucas
writer: George Lucas
stars: mark Hamill, harrison ford
how to translate this into xml??

A: The general idea is in root element  and then attributes and elements in several repetitive groups:
<?xml version="1.0"?>
<movies>
    <movie title="The Matrix" year="1999"/>
        <directors>
            <director>...</director>
            <director>...</director>
            ...
        </directors>
        <stars>
            <star>...</star>
        </stars>
        <writers>
            ...
        </writers>
    </movie>

    <movie title=... year=.../>
        <directors>
            <director>...</director>
            <director>...</director>
            ...
        </directors>
        <stars>
            <star>...</star>
        </stars>
        <writers>
            ...
        </writers>
    </movie>
<movies>

A: Just wrap the whole thing in some tags and thats XML!
<data>
title:The matrix

year: 1999

directors: Andy and Lana Watchowski

writers:Andy and Lana Watchowski

stars: Keanu reeves, carrie fisher

title: star wars

year: 1977

director: George Lucas

writer: George Lucas

stars: mark Hamill, harrison ford
</data>


text:
Q: Cannot change UI in runOnUiThread I want change TextView  content to the result of calculation in thread, but crashing when execution. Here's my code.
new Thread(new Runnable() {
        public void run() {
            while (i < 5) {
               i++;
            }
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    TextView txv = (TextView) getView().findViewById(R.id.txvone);
                    Log.d("123","i = "+ i);
                    txv.setText(i);//CRASH!!!
                }
            });
        }
}).start();

A: You need to pass a String type to the setText() method. When you pass an integer type, it performs a lookup to the R(see : R) file for a string resource with the specified ID. Since the ID does not match any item in your strings.xml file, the exception thrown is ResourceNotFoundException.
Like Sree said, try the code below, it is guaranteed to work.
txv.setText(String.valueOf(i)));

A: In the documentation it says setText(int resid).
So, the int valu, you pass for this method should be a resource id (one from the R.string static member). It's a bit annoying, but I think, Android Studio warns you about the @ResourceId annotation on the prameter.
If you'd like to set the text to 5, you should do the String.valueOf(5) method call, as suggested in the comments.


text:
Q: how to speed up my python code, pandas library I am new to Python and I wrote a python code to process excel files. Here's my code
files=os.listdir("XXX")
os.chdir("XXX")

def getDF(xl, sh):
    print(sh)
    test= xl.parse(sh)
    test2=test.iloc[:, (list(range(8))+ list(range(8,len(test.columns),5))) + list(range(9,len(test.columns),5))]
    num=list((range(1440)))
    aCN = [str(x)+'w' for x in num]
    bCN = [str(x)+'r' for x in num]
    test2.columns=["a", "b", "c", "d", "e", "f", "g" , 'h']+aCN + bCN
    return(test2)

def prepareOneFile(path):
    fn = path
    xl = pd.ExcelFile(fn)
    newDF=[getDF(xl, x ) for x in xl.sheet_names]
    df = pd.concat(newDF)
    print(fn)
    return(df)

app_list= [prepareOneFile(x) for x in files]

The code runs very slow, I can I speed it up? Many thanks11

A: Your code isn't easy to read, but I don't think you can do much in terms of efficiency. The fn = path is unnecessary if you change the following line to xl = pd.ExcelFile(path), that saves you one extra step. You could delete the prints, they take up a (very small) amount of time.
Other than that you could have a look at using a VBA script to convert your Excel to CSV files. pd.read_csv is faster than reading from excel. I suppose this is your best option. That's all I can give you. Maybe someone wiser will come along and give you a better answer.


text:
Q: jQuery Dialog theme not being applied I'm using jquery-1.4.2.min.js and jquery-ui-1.8.1.custom.min.js.  According to Firebug, both minimized scripts have been loaded. They both appear in the dropdown list on Firebug's Scripts tab.
The dialog is launching, but there's no background and so the text below it shows through, and there's no "window" stuff at all, no titlebar, no X button.  Just the floating/draggable text with a -close- link at the top left corner.
I was under the impression from reading these pages
 http://jqueryui.com/demos/dialog/
 http://jqueryui.com/themeroller/

that the UI theme-driven appearance would be automatically applied to the dialog when it was invoked using this barebones call:
 $('#dialog').dialog()

I would be grateful for suggestions on how to troubleshoot this. Thanks

A: You need to make sure you include the link to the jQuery ui theme
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>


text:
Q: How to use System.TriggerOperation Enum There is a new feature provided by Salesforce that allows using TriggerOperation enum. I cannot find any example how to use this approach compared to traditional trigger. For example, how can I replace this code:
trigger TriggerName on ObjectName (before delete, before insert, before update,
                                   after delete, after insert, after update) {

    if (Trigger.isBefore) {
       if (Trigger.isInsert) { // do something }
       if (Trigger.isUpdate { // do something }
    } else {
       if (Trigger.isInsert) { // do something }
       if (Trigger.isUpdate { // do something }
    }
}

Thanks.

A: Answer from salesforce.stackexchange.com
According to Summer 18 Apex developer guide, 7 new Enum values are introduced in System.TriggerOperation class.
AFTER_DELETE
AFTER_INSERT
AFTER_UNDELETE
AFTER_UPDATE
BEFORE_DELETE
BEFORE_INSERT
BEFORE_UPDATE

Similarly, a new variable is added in Trigger class named as operationType, which stores the context enum it is executing in.
Thus your trigger using switch case will be like :
 trigger AccountTrigger on Account (before delete, before insert, before update,
                                    after delete, after insert, after update) {

    switch on Trigger.operationType {
        when AFTER_INSERT{
            //do after insert stuff
        }
        when AFTER_UPDATE{
            //Do after update stuff
        }

    }
}

there is no fall-through. After the code block is executed for a >particular when block, the switch statement exits

Switch statement
My addition
you can also do the following
 trigger AccountTrigger on Account (before delete, before insert, before update,
                                    after delete, after insert, after update) {
    if (Trigger.operationType == TriggerOperation.AFTER_INSERT) {
        // do after insert stuff
    }
}

And finally very personal IMHO - that's just a kind of syntactic sugar which give no profit for someone who use a good trigger architecture


text:
Q: Read files from repo on Github pages I have a project where I need to be able to read text files that are on the assets folder of my repo.
I've never used Github Pages before and don't have much experience working with hosting services, for the deployment and hosting of this project I've followed this guide: https://angular.io/guide/deployment and It's worked, no problem.
When working on this project locally I was fetching the files like so:
fetch('/assets/texts/instrucciones.txt')
And I guess thats where the problem could be, does it make sense or could it be something else


text:
Q: How do I loop through 2d arrays in c++? I am trying to figure out how to loop through a 2d array horizontally vertically, diagonally and sub diagonally  to see if the array is equal to a char.if the array is equal to the char then a bool should return true, but my problem is the bool randomly returns true. the bool only returns true if the char is equal to array at a certain column and row. Here i am hard coding it in but i want to do it with for loops.
Let me know if you need any more info or if something needs to be explained
if (mCard[0][0] == '*' && mCard[0][1] == '*'&& mCard[0][2] == '*'&& mCard[0][3] == '*' && mCard[0][4] == '*') {

    CheckBingo = true;
}
if (mCard[1][0] == '*' && mCard[1][1] == '*'&& mCard[1][2] == '*'&& mCard[1][3] == '*' && mCard[1][4] == '*') {

    CheckBingo = true;
}
if (mCard[2][0] == '*' && mCard[2][1] == '*'&& mCard[2][2] == '*'&& mCard[2][3] == '*' && mCard[2][4] == '*') {

    CheckBingo = true;
}
if (mCard[3][0] == '*' && mCard[3][1] == '*'&& mCard[3][2] == '*'&& mCard[3][3] == '*' && mCard[3][4] == '*') {

    CheckBingo = true;
}
if (mCard[4][0] == '*' && mCard[4][1] == '*'&& mCard[4][2] == '*'&& mCard[4][3] == '*' && mCard[4][4] == '*') {

    CheckBingo = true;
}

if (mCard[0][0] == '*' && mCard[1][0] == '*'&& mCard[2][0] == '*'&& mCard[3][0] == '*' && mCard[4][0] == '*') {

    CheckBingo = true;
}
if (mCard[0][1] == '*' && mCard[1][1] == '*'&& mCard[2][1] == '*'&& mCard[3][1] == '*' && mCard[4][1] == '*') {

    CheckBingo = true;
}
if (mCard[0][2] == '*' && mCard[1][2] == '*'&& mCard[2][2] == '*'&& mCard[3][2] == '*' && mCard[4][2] == '*') {

    CheckBingo = true;
}
if (mCard[0][3] == '*' && mCard[1][3] == '*'&& mCard[2][3] == '*'&& mCard[3][3] == '*' && mCard[4][3] == '*') {

    CheckBingo = true;
}
if (mCard[0][4] == '*' && mCard[1][4] == '*'&& mCard[2][4] == '*'&& mCard[3][4] == '*' && mCard[4][4] == '*') {

    CheckBingo = true;
}

// checking for daigonal
if (mCard[0][0] == '*' && mCard[1][1] == '*'&& mCard[2][2] == '*'&& mCard[3][3] == '*' && mCard[4][4] == '*') {

    CheckBingo = true;
}
// checking for sub diagonal
if (mCard[4][0] == '*' && mCard[3][1] == '*'&& mCard[2][2] == '*'&& mCard[1][3] == '*' && mCard[0][4] == '*') {

    CheckBingo = true;
}

here I tried using for loops but it does int always return true if the array is equal to the char.
for(int row = 0; row < 5; row++) {
    for(int col = 0; col < 5; col++) {
        if(mCard[row][col] == '*') {
            CheckBingo = true;
        }
        else {
            CheckBingo = false;
            break;
        }
    }
}

for(int row = 0; row < 5; row++) {
    for(int col = 0; col < 5; col++) {
        if(mCard[col][row] == '*') {
            CheckBingo = true;
        }
        else {
            CheckBingo = false;
            break;
        }
    }
}

A:
mCard[col][row]
...

row and col have to be flipped.
You then start the loop assuming that match is set. If one of the cells is not matched, then match is false. See example below.
Make sure the values are initialized.
int main()
{
    char mCard[5][5] = {
    '*','x','*','*','*',
    '*','*','*','*','*',
    '*','*','*','*','*',
    '*','*','x','*','*',
    '*','*','*','*','*',
    };

    bool CheckBingo = true;
    for(int row = 0; row < 5; row++)
    {
        CheckBingo = true;
        for(int col = 0; col < 5 && CheckBingo; col++)
        {
            if(mCard[row][col] != '*')
                CheckBingo = false;
        }
        if(CheckBingo)
            cout << "bingo on row " << row << "\n";
    }

    bool match = true;
    for(int row = 0; row < 5 && match; row++)
        for(int col = 0; col < 5 && match; col++)
            if(mCard[row][col] != '*')
                match = false;
    if(match) cout << "bingo for all lines\n";

    match = true;
    for(int i = 0; i < 5 && match; i++)
        if(mCard[i][i] != '*')
            match = false;
    if(match) cout << "top-left to bottom-right match\n";

    match = true;
    for(int i = 0; i < 5 && match; i++)
        if(mCard[i][4-i] != '*')
            match = false;
    if(match) cout << "top-right to bottom-left match\n";

    return 0;
}


text:
Q: Looking for JDOM2 XPath examples I am using JDOM2 for the first time and I am looking for some XPATH based examples.
Ex: My XML looks as follows
<Root>
  <Parent id="1">
    <Child id="1" />
    <Child id="2" />
    <Child id="3" />
  </Parent>
  <Parent id="2">
    <Child id="1" />
    <Child id="2" />
    <Child id="3" />
  </Parent>
  <Parent id="3">
    <Child id="1" />
    <Child id="2" />
    <Child id="3" />
  </Parent>
</Root>

My background is .NET & XPATH traversing is very easier with System.XML
I am working on a (new to) Java application where I need to use XML. I am planning to use JDOM2. I want to use DOM parsing and not SAX.
I am looking for some examples on how to use XPATH with JDOM2.
Ex. How can I navigate to an element let's say "/Root/Parent[@id='2']/Child[@id='3']"
Can you guys give me some examples? I searched but I couldn't find one for JDOM2

A: Ok, found this https://github.com/hunterhacker/jdom/wiki/JDOM2-A-Primer and seem to be helpful

A: http://www.studytrails.com/java/xml/jdom2/java-xml-jdom2-xpath/
is an example of using JDOM2 and XPATH


text: Q: Bandwidth: voltage-source vs. current-source gate drivers Why do voltage-source gate drivers provide low-to-medium bandwidth that does not work well for wide band gap devices, while current-source gate drivers provide hundreds of MHz of bandwidth?


text:
Q: Como Ler e condicionar uma string em java eu preciso saber o seguinte:
Quero fazer um programa que Le um numero e em seguida eescreve o nome do numero:
Por exemplo:foi digitado o numero 29340, em seguida aparece: 2-Dois, 9-Nove, 3-Tres, 4-Quatro, 0-Zero.
Estou tentando fazer transformando para String pegando length e com string.equals, mas não estou conseguindo! Pois parece que ele le os números anteriores juntos com os seguintes... Se alguém puder me ajudar eu agradeço


text:
Q: Magento 2 Get order from quote id How would I get a order's info from a quote id?
if I have quote id of 253 and once I load that quote using..
$quote = $this->quoteFactory->create()->load("253");

How do i get the order which belongs to this?
This would happen after the order has been placed
I've tried this but it doesn't work.
$reserved_order_id = (int)$quote['reserved_order_id']); //01191
$order = $this->orderRepository->get($reserved_order_id);

however i get an error of The entity that was requested doesn't exist. Verify the entity and try again yet i know that order exists. perhaps i shouldn't use $quote['reserved_order_id']
Update
 $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $collection = $objectManager->create('Magento\Sales\Model\Order');
        $orderInfo = $collection->loadByIncrementId($order_id);
        $orderId = $orderInfo ->getId();
        $order = $this->orderRepository->get($orderId);

A: Try below code.
In Magento 2, you can use the \Magento\Sales\Api\OrderRepositoryInterface class to retrieve an order using a quote ID. Here's an example of how you can use this class to load an order by quote ID:
<?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

// Quote ID
$quoteId = 1;

// Load order by quote ID
$orderRepository = $obj->create('\Magento\Sales\Api\OrderRepositoryInterface');
$order = $orderRepository->getByQuoteId($quoteId);

// Use the order object
echo $order->getIncrementId();

You can also use \Magento\Quote\Model\QuoteFactory class to load the quote and then use getId() method to get the order Id.
<?php
use Magento\Quote\Model\QuoteFactory;

$quoteFactory = $this->quoteFactory->create();
$quote = $quoteFactory->load($quoteId);
$orderId = $quote->getReservedOrderId();

Let me know if any query.
THANKS.


text:
Q: getaddrinfo: in what way is AI_PASSIVE ignored if the nodename is specified? Quoting from the specs of getaddrinfo:

If the AI_PASSIVE flag is specified, the returned address information shall be suitable for use in binding a socket for accepting incoming connections for the specified service. In this case, if the nodename argument is null, then the IP address portion of the socket address structure shall be set to INADDR_ANY for an IPv4 address or IN6ADDR_ANY_INIT for an IPv6 address.

This makes sense. If you specify AI_PASSIVE, you can bind()/listen()/accept() on the returned address. If nodename is null, the returned address binds to all network interfaces so you can use any of the computer's IP addresses (e.g. ethernet LAN IP, Wi-Fi LAN IP, loopback address, etc.). Summary: use AI_PASSIVE on the server (for a TCP socket).
Continuing:

If the AI_PASSIVE flag is not specified, the returned address information shall be suitable for a call to connect() (for a connection-mode protocol) or for a call to connect(), sendto(), or sendmsg() (for a connectionless protocol). In this case, if the nodename argument is null, then the IP address portion of the socket address structure shall be set to the loopback address.

This also makes sense. If you don't specify AI_PASSIVE, you can connect()/sendto()/sendmsg() on the returned address. If nodename is null, you get the loopback address. Summary: don't use AI_PASSIVE on the client (for a TCP socket).
Continuing:

The AI_PASSIVE flag shall be ignored if the nodename argument is not null.

Huh? What does it even mean to ignore the AI_PASSIVE flag? From the first two quotes, it sounds like AI_PASSIVE is only used to determine whether you get addresses suitable for server/client use, and in both of those cases it sounds like a null nodename just gives you a INADDR_ANY address (for server) or loopback address (for client). What good does it do to ignore the AI_PASSIVE flag?
What does this last quote really mean? How does it affect the first two quotes?

A: The Linux manpage for gettaddrinfo(2) describes it slightly differently (and a bit more consistently):

If  the  AI_PASSIVE  flag  is specified in hints.ai_flags, and node is NULL, then the returned socket addresses will be suitable for bind(2)ing a socket that will  accept(2)  connections. The returned socket address will contain the "wildcard address" [...]. If node is not NULL, then the AI_PASSIVE flag is ignored.
If the AI_PASSIVE flag is not set in hints.ai_flags, then the returned socket addresses will be suitable for use with connect(2), sendto(2), or sendmsg(2).  If node is NULL, then the network address will be set to the loopback interface address [...].

Of course, the Linux manpage is not authoritative other than for Linux, but I offer it as a widely-used interpretation.  In particular, note that it specifies that you get a server socket only if AI_PASSIVE is given and node is NULL.  That still leaves some ambiguity as to what it means to "ignore" AI_PASSIVE, but I think it nevertheless points to the interpretation taken by Linux: you always get address info suitable for a client socket if node is not NULL.
You could perhaps rationalize it this way: "The AI_PASSIVE flag shall be ignored" should be interpreted as "if the AI_PASSIVE flag is set then that fact shall be ignored".  That is, it shall be handled as if the flag were not set.  I think that's additionally supported by the fact that this statement occurs in the same paragraph with the description of the behavior when AI_PASSIVE is set (in the official docs too, not just the Linux manpage).


text:
Q: Is it safe to run WindowsXP as a Virtual Machine? I know XP should not be used on a normal internet-facing PC. But if you run it within a sand-boxed VM that can't access the main PC, is that OK?
My use-case is I run a VPN within a VM, to RDP into a remote PC I work on. I do it through a VM so the VPN only affects that RDP so my regular web usage doesn't get routed through their network.
I have lots of XP licenses - and XP Mode in W7 - and none spare for other Windows versions. So I wondered if the XP VM is only used for RDP access, if this is 'safe' even if the OS did somehow get compromised (unlikely as I never browse the web from the VM)?

A: It should be safe for your host OS as XP will run in a sandbox so anything that happens will stay there but the guest OS would be vulnerable to attacks so always try to keep an antivirus running in the guest os just in case


text:
Q: swift convenience init and generic class I have a problem creating a convenience init method that then calls a designated init on a class with generic type parameters.  Here is the swift 3.1 XCode Version 8.3.2 (8E2002) playground
protocol A {
    var items: [String] { get set }
    func doSomething()
}

struct Section : A {
    var items: [String] = []

    func doSomething() {
        print("doSomething")
        items.forEach { print($0) }
    }
}

class DataSource<T: A> {
    var sections: [T]

    init(sections: [T]) {
        self.sections = sections
    }

    func process() {
        sections.forEach { $0.doSomething() }
    }

    convenience init() {
        var section = Section()
        section.items.append("Goodbye")
        section.items.append("Swift")

        self.init(sections: [section])
    }
}

/*: Client */
var section = Section()
section.items.append("Hello")
section.items.append("Swift")

let ds = DataSource(sections: [section])
ds.process()

If no convenience init exists, then the code beneath the /*: Client */ section compiles and executes without issue.  If I add in the convenience init I get the following compilation error:
cannot convert value of type '[Section]' to expected argument type '[_]'
        self.init(sections: [section])

I wouldn't think that this would be an issue since in the convenience init I am creating a Section struct which implements the protocol A which satisfies the generic constraint  on the DataSource class.  The convenience init is performing the same operations as the client code, yet it is unable to convert a [Section] into a [A].  Is this an initialization sequencing issue?

A: Generic placeholders are satisfied at the usage of the given generic type – therefore inside your convenience init, you cannot assume that T is a Section. It's an arbitrary concrete type that conforms to A.
For example, it would be perfectly legal for the caller to define a
struct SomeOtherSection : A {...}

and then call your convenience initialiser with T being  SomeOtherSection.
The solution in this case is simple, you can just add your convenience initialiser in an extension of DataSource, where T is constrained to being Section – therefore allowing you to call init(sections:) with a [Section]:
extension DataSource where T == Section {

    convenience init() {
        var section = Section()
        section.items.append("Goodbye")
        section.items.append("Swift")

        self.init(sections: [section])
    }
}

// ...

// compiler will infer that T == Section here.
let ds = DataSource()


text:
Q: What is the correct order to read these books? I'm a junior C# developer, I learned at home and now I got my first job :)
I want to buy these books. But what is the correct order to read these books?
Code Complete: A Practical Handbook of Software Construction
Clean Code: A Handbook of Agile Software Craftsmanship
Pragmatic Programmer

A: There is no "correct" order to reading these books.
They each focus on different aspects of software engineering.

*

*Clean Code - focuses on coding in the small. How to write classes and functions.

*Code Complete - focuses on the processes of software engineering.

*Pragmatic Programmer - focuses on working within a team producing software.

A: I agree with the answers of "no correct order", but I will offer a different spin...
Start and fully digest Code Complete.  It's the most basic, most comprehensive basis book.  Spend a LOT of time reading and re-reading it.  It should give you the most returns if you're a beginner.

A: I've read Pragmatic Programmer and I'm in the process of reading "Code Complete".
From my experience so far, I think that "Pragmatic Programmer" is a great place to start because it gives a high-level view of different coding issues.  I read it over the course of a week; as I read it, I was immediately enlightened of some better ways to solve problems I deal with every day.
"Code Complete" is longer and more exhaustive.

A: I only read "Clean Code", and it was very good. Uncle Bob tells you how to become a good Software Craftsman and how to write clean code that is maintainable even in years. So you maybe should read this book first :-) (I wish I had read it earlier).
If you want to get a bigger view (on dependencies between modules) I also can recommend his code-casts: http://www.cleancoders.com/

A: I'm also reading those books, here's my order:

*

*Clean Code

*Pragmatic Programer

*Code Complete

A: Congrats on getting your first job! And you really made good book choices!
These books are master pieces for every programmer to read at least once.
From my personal experience i would advice to read books interchangeably. It is a fact that you may get tired/bored from one book, and switching to related book will make you re-focus and behind the scene your brain will kick off to process the information. Thus, you may maximum benefit from this process.
Edit: as mentioned in comment, it is a kinda multi-threading solution to add up in efficiency :)
However, don't over-heat yourself. Having more than 3 books might be hard to deal at the same time.

A: These books have high merit.
Often times developers enter into the work knowing mostly what without much detail about why.  The three books you picked offer a lot to improve what you do as a programmer, and are good at providing descriptions to back up their prescriptions.
Reading these books will open you to a lot of ideas you might have never imagined.  Later, as you gain experience, you will get even more out of these books, relating what you have seen to what they describe.
Together, these books total over 1500 pages.  That's a lot of reading, and you are right to prioritize and map out a sequence.  I suggest you download the table of contents for all three and score the chapters in each by what you most need now for your job.  You could compare and contrast their advice on variable and class naming, but I think if your read about naming once, it would be enough.  Similarly, if your team or manager have guidelines, follow them.
Perhaps you can borrow these from a friend or library before buying them.  Or maybe even spending a few hours at your local bookstore.  If you time box your reading, threading through all three based on your priorities, taking notes on a blank piece of paper, you will find vocabulary and concepts you can apply at work today.
Pragmatic is a great description of the learning approach you want when using these books.  There is a lot of overlap between the three, and I think much has been revisited in web accessible sources.  There are many things you may find you need that are either not in these books, or are barely touched upon.  Consider adding more topics that go beyond the scope of these books:

*

*Programming language tutorials.

*Your organizations specific source control and build tools.

*Concepts and implementations of data structures in C#.

*Standard C# class libraries.

*Coding standards specific to your organization.

*Testing, probably with MS Test tools.

*UI / UX design guidelines for your platforms.

*Applicable design patterns which for C#, I would expect MVVM to be the most critical.

Another consideration I think might help is to consider the publication date, context, and goals of each book.  Oldest to newest: Pragmatic 1999, Code Complete 2nd Ed. 2004, Clean Code 2008.  Context: Pragmatic lists C, C++, Java in its index but not C#.  Code complete is Microsoft Press, written by an ex-Microsoft guy, and because you are working with a Microsoft language, there might be some affinity there, but the index has one entry for C# and it gets less love than Fortran on page 64.
The Robert Martin book is more steeped in the Agile approach than the other two, is the newest, and has some pretty great descriptions of naming, class design, and probably a lot more help with concurrency than the others.  It may be a little unfair, but the later books can talk about more stuff and newer stuff, and their context is generally more like what we do today.
Each of these books to some extent competes in a similar range of topics.  Kind of makes you want to ask, "What newer, broadly scoped programming books are competing in the same space?"


text:
Q: Manga about a noble's daughter, possibly an isekai The manga had only a few chapters currently translated to English when I first read it. That was earlier this year, so I assume it still has little translated chapters.
The setting is one of those medieval-looking settings in a world with swords (and probably magic too. Don't remember that for sure).
High chance it's an isekai manga, but I'm not 100% sure about that.
The main character is the daughter of some noble family. I remember her having light-colored hair.
In one of the first chapters, she beats someone else in a swordfight with relative ease.
At the moment, I can't recall much else. I will answer any questions if I'm able to.
Edit: I know for a fact that it was a manga. Not a manhwa or a manhua.

A:
Could you be thinking of It Seems My Body is Completely Invincible? It's an isekai manga that only had 4 chapters translated up until a couple months ago. The protagonist is the daughter of a duke and easily beats the child of her sword instructor in a mock fight in the first few chapters.

A: I Will Go and Disappear Obediently looks like a possibility.
The main character's hair seems to be white. She is the daughter of the king's protector and is called princess in the first chapters.  The manga is only a few chapters long, and was only 2-3 chapters long at the beginning of the year.
While i don't see a duel or fight that is easily won, there is a scene that has end of training for the day with the instructor saying the Main Character will beat him before long. She is being trained to protect the prince when she is older, like her father protects the king. The prince calls her his 'sword' and there are a few other mentions of her family being the King's "Sword".

A: Maybe 금발의 정령사, aka The Goldenhaired Elementalist?

I thought I was dead, but when I woke up, I was reincarnated as a nobleman's daughter?! The only thing I did in the seventeen years of my first life was studying. Now that I'm alive again, I won't live just to study! The second life of an ordinary middle school girl with a slightly strange personality, Jean, begins an unstoppable journey on this continent!

Found with a search for manga "nobleman's daughter". Just started being translated in January 2020. No swordfight yet in the first two chapters, though.


text:
Q: User input to search bash array folks--
I'm getting kinda stuck, here. I have a small script that will be incorporated into a larger script. This small piece is supposed to take a user input, and compare it to a list of stored variables. If the user input matches one of the listed variables, it should output the string that is that variable; or, if it matches none of the elements, then it should write the user input to a new variable.
For context, what I've done is I've defined a few variables as strings (in this case, the citation information for textbooks). As an example:
books=()

buffa7="Wilson, Buffa, Lou. Physics. Pearson, 7th edition, 2009. ISBN: 0321601831"
books=+("$buffa7")

giancoli6="Giancoli, Douglas C. Physics: Principles with Applications. Prentice Hall, 6th edition. ISBN: 0321736990"
books=+("$giancoli6")

My understanding of this code is that it will make an array, books, and take the variables $buffa7 and $giancoli6 and append them to the list. What I'd like to do is prompt a user for input on the source: if they input buffa7 or giancoli6, then the variable $source should be redefined to be the text assigned to the respective variable. If the user input does not match these, then the variable $source should be defined to be whatever the user input.
The problem I seem to be running into is that when the user inputs the source information, if they use buffa7, bash seems to think that if the actual string buffa7 is not in its list, then it doesn't have to do anything, and thinks that buffa7 is not in the list (which is true, because $buffa7 is). Any advice on how to proceed would be much appreciated!

A: This can be done using name references or variable indirection, but what you should do is use associative arrays. There's no need for variables for each entry, when an associative array will do for the whole lot.
declare -A books
books[buffa7]="Wilson, Buffa, Lou. Physics. Pearson, 7th edition, 2009. ISBN: 0321601831"
books[giancoli6]="Giancoli, Douglas C. Physics: Principles with Applications. Prentice Hall, 6th edition. ISBN: 0321736990"

Then:
read input
source=${books[$input]}   # set $source to entry from array
if [[ -z $source ]]       # if $source is empty after that
then                      # $input was not in array, so
    source=$input         # set $source to $input.
fi


text:
Q: Filter table, copy and paste into multiple existing workbooks I have a table that has data for multiple projects.
I need to filter the data (by project number), then copy and paste each project's data into separate existing workbooks ( I have a tab that contains file paths of the each workbook and project names.
I have managed to open the first project's workbook, copy and paste, save and close the workbook but excel throw an error after that.
I know there is an issue but not too sure how to fix it.
Can anyone help?
Below is a link to the files
enter link description here
Sub OpenProjects()

Dim N As String
Dim LAST As Integer
Dim TABLE As Range
Dim PNumber As String 'Project Number

LAST = Sheets("Projects").Cells(Rows.Count, "A").End(xlUp).Row

Set TABLE = Sheets("Projects").Range("A1:M" & LAST)

'Open files

Sheets("Unique Projects").Select

RowCount = Application.WorksheetFunction.CountA(Sheets("unique Projects").Range("B:B"))

For i = 2 To RowCount

N = Sheets("Unique projects").Cells(i, 2)

Workbooks.Open (N)

    'Back to original workbook

Workbooks("original.xlsm").Activate

For Each NUMBER In Sheets("Unique Projects").Range([A2], Cells(Rows.Count, "A").End(xlUp))

With TABLE
.AutoFilter
.AutoFilter Field:=1, Criteria1:=NUMBER.Value
.SpecialCells(xlCellTypeVisible).Copy Destination:=Workbooks(NUMBER & ".xlsm").Sheets("sheet1").Range("A1")

End With

Workbooks(NUMBER & ".xlsm").Save
Workbooks(NUMBER & ".xlsm").Close

Workbooks("Original").Activate

Next NUMBER

Next i
End Sub


text:
Q: comparing interval of date with SQL I'm working on a booking system . and I have a problem with my SQL request .
this is my table :
http://sardoukayoub.com/1.png
And this is my SQL request :
"SELECT * FROM (SELECT * FROM reservations WHERE ('2014-01-09' BETWEEN DateDebut AND DateFin ) OR ('2014-01-24' BETWEEN DateDebut AND DateFin ))AS A WHERE IdProduit = 320"

the result of my request with these two date get me this line :
http://sardoukayoub.com/2.png
I want to perform my request to get me 2 lines . in my case the idreservation=21 and 22 .

A: Seems you want to check if two periods overlap:
SELECT * FROM reservations
WHERE DateDebut <= '2014-01-29' AND DateFin >= '2014-01-12'
AND IdProduit = 320;

Btw, in Standard SQL there's an OVERLAPS operator :-)

A: The date
'2014-01-09'

u selected in your statement is not between DateDebut and DateFin in the table where IdProduit=320
This should work fine
SELECT * FROM reservations
WHERE DateDebut <= '2014-01-29' AND DateFin >= '2014-01-12'
AND IdProduit = 320;"


text:
Q: Python3: Importing Function dependent on Matplotlib Good day! So I'm trying to have a frequently used function in its own file for organizational purposes, and would like to be able to import it when needed.
#Plotting fits image function
def plotfits(subsize,title,imgdata,color,cbarlabel):
    plt.subplot(subsize)
    plt.title(titSle)
    plt.imshow(imgdata, cmap=color)
    ibar1 = plt.colorbar()
    ibar1.set_label(cbarlabel)
    plt.gca().invert_yaxis()

Then when I try from plotfits import plotfits in my main file where I would like to use the function, I get this error.
Traceback (most recent call last):
  File "/home/jorge/python/heliotutorial/tut01_new.py", line 39, in <module>
    plotfits(221,'Intensity',imgdata1,'gray','Continuum Intensity')
  File "/home/jorge/python/heliotutorial/plotfits.py", line 4, in plotfits
    def plotfits(subsize,title,imgdata,color,cbarlabel):
NameError: name 'plt' is not defined

But I already have pyplot imported with import matplotlib.pyplot as plt. I thought maybe I would have to import pyplot inside the function again for it to work, as then it'd be defined inside the function:
def plotfits(subsize,title,imgdata,color,cbarlabel):
    import matplotlib.pyplot as plt
    ....

But this does not work, nor does having the import statement at the beginning of the file. What could be my mistake here? (Function does work if written and defined inside the main file)
Thank you in advance for the help!


text:
Q: GitHub Website/Windows app - how do you create "pull request" from single commit? Currently i'v forked some repo on github.
Changed something for my needs, pushed to my master branch, changed something related to core master branch.
Now i want to "pull request" these ( last ) commit only to core master branch, but when i create pull request it has 2 commits in it.
I need a solution, wich will allow me to "pull request" only 1 commit trought GitHub Website or GitHub for Windows app.
I'v read about git cherry pick, but these solution requires cmd/git atc.
But what i need: Website or Windows app to do that.


text:
Q: Get position relative to tag ignoring X&Z axis rotation For a drone application I'm trying to get the drone position in the tag frame reference, but ignoring the X & Z axis rotation.
The tag is positionned vertically, and I want to ignore rotation of Z and X axis
The goal is get the drone position that points forward the tag orthogonally the Y axis whatever the other orientation of other axis.
I'm a noob in rotation matrix, I really begin!
I'm using Java and April Tag V3, but it should be the same in AruCo Tags.
I'm trying this kind of things without success
//Pose in Camera Frame (rotMatrix & trans are raw data form April Tag)
Vector3D vectorPosCamFrame = new Vector3D(trans[0][0], trans[0][1], Math.abs(trans[0][2])); //Z axis can to be only positive
Rotation rotationTag = new Rotation(rotMatrix, 1);

//Determining rotation whtout Y Axis rotation
Vector3D vectorPosCamEstimateYAxisTmp = new Vector3D(0, 1, 0);
Vector3D vectorPosCamEstimateYAxisTmpRotated = rotationTag.applyTo(vectorPosCamEstimateYAxisTmp);
Rotation rotationWithoutYAxis = new Rotation(vectorPosCamEstimateYAxisTmp, vectorPosCamEstimateYAxisTmpRotated);

//Apply rotation to current position to get position in TAG Frame
Vector3D vectorPosTagFrame = rotationTag.applyTo(vectorPosCamFrame);
vectorPosTagFrame = rotationWithoutYAxis.applyInverseTo(vectorPosCamFrame);

Does any body can explain me what I'm doing wrong?


text:
Q: I am confused and I want to know the difference in both codes? I am learning web development, and I tried to do the exercise, but the answer given is different from mine. May, anyone please help me see what my mistake is.
Here is the code:
Given Answer:
// Setup
var contacts = [
  {
    "firstName": "Akira",
    "lastName": "Laine",
    "number": "0543236543",
    "likes": ["Pizza", "Coding", "Brownie Points"]
  },
  {
    "firstName": "Harry",
    "lastName": "Potter",
    "number": "0994372684",
    "likes": ["Hogwarts", "Magic", "Hagrid"]
  },
  {
    "firstName": "Sherlock",
    "lastName": "Holmes",
    "number": "0487345643",
    "likes": ["Intriguing Cases", "Violin"]
  },
  {
    "firstName": "Kristian",
    "lastName": "Vos",
    "number": "unknown",
    "likes": ["JavaScript", "Gaming", "Foxes"]
  }
];

function lookUpProfile(name, prop){
  // Only change code below this line
  for (let x = 0; x < contacts.length; x++) {
    if (contacts[x].firstName === name) {
      if (contacts[x].hasOwnProperty(prop)) {
        return contacts[x][prop];
      } else {
        return "No such property";
      }
    }
  }
  return "No such contact";
  // Only change code above this line
}

lookUpProfile("Kristian", "lastName");

My Answer:
function lookUpProfile(name, prop) {
  // Only change code below this line
  for (let i = 0; i < contacts.length; i++) {
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)) {
      return contacts[i][prop];
    } else if (!contacts[i].firstName) {
      return "No such contact";
    } else {
      return "No such property.";
    }
  }
  // Only change code above this line
}

Calling lookUpProfile("Kristian", "lastName") should return the string Vos.

A: given answer: loop all contacts, if no contact firstName match name, at last, return "No such contact".
however, you returned "No such contact" if the first contact in the loop not matching the name.

A: Your && statement has an else that follows it.
Therefore as soon as both statements aren't true (I.E the first example), the else statement that follows it will run, which returns, ending whatever loop the return is inside of.
Your correct example , with input ("Kristian", "lastName")
First example (Akira Laine) - Firstname is NOT Kristian, so loop continues
Second example (Harry Potter) - Firstname is NOT Kristian, so loop continues
Third example (Sherlock Holmes) - Firstname is NOT Kristian, so loop continues
Fourth Example (Kristian Vos) - FirstName IS Kristian, so loop checks if it has property
'lastname'.
It DOES have property last name, so return lastname.
Your example, with input ("Kristian", "lastname")
First example (Akira Laine) - Firstname is NOT Kristian, it DOES have a property 'lastname'.
Since it's a && statement, it still reads as false.
Therefore, the first else if is checked.
First name being present IS true, so the last else statement is run.
This returns "no such property".


text:
Q: Extract value from text field to support GROUP BY in SQL from Redshift table I have a Redshift table that essentially contains survey results that I'm trying to do some statistical analysis on (example data at end of question).  For the purposes of this question we can assume the table has three columns: response, date_submitted and meta_data
The response column contains a simple 1 or 0.  The timestamp is the datetime when the survey was submitted.  And the meta_data field is essentially a CSV text field with a list of key, value pairs.
Example row below
f1=v1, f2=v2, templateId=<someTemplateId>, ...

Most of this data I don't care about but the templateId is the value I want to pull out of meta_data.  I would like to use templateId to GROUP BY all my rows so I can get summary statistics for each templateId.  Long term this value should be extracted into its own column but given time constraints I am unable to update our data generating process for this and need to perform the analysis before that work can be done
Ultimatley the query I'd like to be able to do is
SELECT sum(response) FROM my_table GROUP BY <template_id>

Example Data
   reponse                    meta_data                  timestamp
0        0  f1=v1, f2=v2, templateId=77 2021-04-07 09:51:55.655793
1        0  f1=v1, f2=v2, templateId=55 2021-04-07 08:51:55.655793
2        1  f1=v1, f2=v2, templateId=77 2021-04-07 07:51:55.655793
3        1  f1=v1, f2=v2, templateId=77 2021-04-07 06:51:55.655793
4        1  f1=v1, f2=v2, templateId=66 2021-04-07 05:51:55.655793

To clarify the above... f1=v1, f2=v2, templateId=77 is the entry for meta_data in the first row

A: You should be able to use regexp_substr():
select t.*,
       regexp_substr(meta_data, 'template_id=([^ ]+) ', 1, 1, 'e') as template_id
from t;


text:
Q: Android App Icon Shortcut Rename Looking to change the name for an app (icon name) with established user base.
Are there any issues that I should foresee that users can face when they download the update?
Specifically worried about problems with launchers not updating the name of the icon properly of giving 'app does not exist or installed' message

A: The Android OS will read the manifest which will point to the icon and name to use for the app. It shouldn't cause an issue if your IDE does not complain and you won't hit the 'app does not exist or installed' because the package name will stay the same.
You can test this very easily by installing the old version, and then building (but not running) the new version with the change in app name and/or app shortcut image. Then simulate an update by going into command line or terminal and running
adb install -r MyApp.apk

This will update the app on your device with your new app name and/or app image but still keep the app database and store preferences - thus simulating an app update.


text:
Q: Insert data into exist excel file c# I have a exist excel file. It has style, ex : table, color,.....(like a below image)so, i want t insert data from datagridview into excel( row 5 and data exsit in a table).My code that works but data don't exist in table and last rows removed.
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(filePath);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.ActiveSheet;
for (int i = 0; i < dataGridView3.Rows.Count - 1; i++)
{
    for (int j = 0; j < dataGridView3.Columns.Count; j++)
    {
        worksheet.Cells[i + 4, j + 1] = dataGridView3.Rows[i].Cells[j].Value.ToString();
    }
}
app.Quit();

A: Please try the following code:
using Excel = Microsoft.Office.Interop.Excel;

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
string fileName = "YOUR_EXCEL_FILE";

xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(fileName);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

for (int i = 0; i < dataGridView3.Rows.Count - 1; i++)
{
    for (int j = 0; j < dataGridView3.Columns.Count; j++)
    {
        xlWorkSheet.Cells[i + 4, j + 1] = dataGridView3.Rows[i].Cells[j].Value.ToString();
    }
}

xlWorkBook.SaveAs(YOUR_PATH+ ".xlsx");
object misValue = System.Reflection.Missing.Value;
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
xlWorkSheet = null;
xlWorkBook = null;
xlApp = null;

Process.Start("" + YOUR_PATH + ".xlsx");


text: Q: Tools to test out SQL Server assemblies Are there any good tools to test out my SQL server assemblies?  I have two assemblies that get deployed to SQL Server 2005. The assemblies are created using VS 2008 and C#.Net. My web app makes request to a stored procedure that fires off the assemblies but sometimes it never returns. How do I test this?


text:
Q: entry.get() from a fonction I want to get the value of the entry when I press the button, but I can't find a way to do it because the entry is in a fonction.
I tried to put a global before the entry but it doesn't work
#coding:utf-8
from Tkinter import *
from random import *

def nb1():
    nb=randint(0,16)
    jeu(nb)

def checkansw():
    answ = entryansw.get()
    if answ == int(nb, 2):
        showinfo('Résultat','Bravo !')
    restart()
    else:
        showwarning('Résultat','Incorrect !')
entryansw.set('')

def jeu(nb):
    nb=format(nb, 'b')
    root.destroy()
    root2 = Tk()
    root2.title("Binary Game")
    root2.geometry("500x350+50+50")
    root2.resizable(width=False, height=False)
    root2['bg'] = 'black'
    entryansw = Entry(root2, width=5, font=("Courier New", 20),
justify=CENTER).pack(side=TOP, pady=30)
    boutonvalid = Button(root2, text="Valider",
highlightbackground="black", command=checkansw).pack()
root2.mainloop()

root = Tk()
root.geometry("500x350+50+50")
root.resizable(width=False, height=False)
root['bg'] = 'black'
choixdif = Label(root, pady=25, text="Veuillez choisir la
difficulté.", font =("Courier New", 18), bg="black",
fg="green").pack()
boutondif1 = Button(root, text="Facile", highlightbackground
="black", command=nb1).pack()
root.mainloop()

A: You can get value from Entry by setting a text variable
entryansw_textvariable = StringVar()

entryansw = Entry(root2, width=5, font=("Courier New", 20), justify=CENTER, textvariable=entryansw_textvariable).pack(side=TOP, pady=30)

answ = entryansw_textvariable.get()

you can get details here

A: There are two parts to your problem. First is dealing with the scope of your variables. Like you said, you can declare global for variable entryansw:
def checkansw():
    global entryansw
    answ = entryansw.get()
    ...

def jeu(nb):
    global entryansw
    ...

Alternatively, you can first define a placeholder at your main function, and append the widget created by your function to the placeholder:
from tkinter import *

widget = []

def checkansw():
    answ = widget[0].get()
    if answ == int(nb, 2):
        pass
    else:
        widget[0].set('')

def jeu(nb):
    ...
    entryansw = Entry(root2, width=5, font=("Courier New", 20),justify=CENTER).pack(side=TOP, pady=30)
    widget.append(entryansw)
    ....

And of course, you can define a class to handle this instead:
class JEU:
    def __init__(self):
        nb=randint(0,16)
        self.jeu(nb)

    def checkansw(self):
        answ = self.entryansw.get()
        if answ == int(nb, 2):
            pass
        else:
            self.entryansw.set('')

    def jeu(self,nb):
        nb=format(nb, 'b')
        root.destroy()
        root2 = Tk()
        root2.title("Binary Game")
        root2.geometry("500x350+50+50")
        root2.resizable(width=False, height=False)
        root2['bg'] = 'black'
        self.entryansw = Entry(root2, width=5, font=("Courier New", 20),justify=CENTER).pack(side=TOP, pady=30)
        boutonvalid = Button(root2, text="Valider",highlightbackground="black", command=self.checkansw).pack()
        root2.mainloop()

Any of the above will solve the scope problem, however it still won't work because of the below code:
entryansw = Entry(root2, width=5, font=("Courier New", 20),justify=CENTER).pack(side=TOP, pady=30)

When you pack it directly, the variable entryansw becomes a reference to the pack method which is a None-type object:
<class 'NoneType'>

To properly refer to entryansw, you should call the pack method separately:
entryansw = Entry(root2, width=5, font=("Courier New", 20),justify=CENTER)
entryansw.pack(side=TOP, pady=30)

Now the type of entryansw becomes a proper widget.
<class 'tkinter.Entry'>

Still, there are a couple more things to improve for your code still, e.g. using set for your entry widget, calling mainloop twice...


text:
Q: How to create with Cmake: POST BUILD EVENT for Visual Studio, Debugging Command and Debugging command arguments I'm trying to create the following "Post-Build Event" for Visual Studio in a CMakeLists.txt.
copy $(OutDir)$(TargetName)$(TargetExt) $(SDK_PATH)\bin\exmp.dll

I found this to use with my library (vibe_mdl):
add_custom_command(
    TARGET vibe_mdl
    POST_BUILD ...
)

but I can't find a way to have the string that I need to be populated to the Post Build event.
I also need to set the "Debugging Command" in "Configuration Properties" with $(SDK_PATH)\bin\bl_sim5.exe and the "Debugging Command Arguments" with -o (this one should be easy)
Any help is strongly appreciated!


text:
Q: Swift string format specifier equivalent to %@ I am writing a simple app with a form in Swift, I had the app written in Objective-C to populate an e-Mail with data from text fields in a view, I used the following code to do this:
NSString *messageBody = [NSString stringWithFormat:@"Name: %@ \nDate: %@", NameField.text, DateField.text];

I am trying to achieve the same thing in Swift, I have the following so far:
let messageBody = NSString(format: "Name: %@ \nDate: %@", NameField, DateField)

I am looking for swifts equivalent to "%@" to make the app look to the format of the string to find the data to place after "Name:".

A: Don't just port Obj-c to Swift. Swift has it's own way of doing things.
let message = "Name: \(nameField) \nDate:\(dateField)"

A: In Swift you use \(some_printable_object_or_string)
like
let string = "Name: \(NameField) \nDate: \(DateField)"

Or you can use ObjectiveC-style formatting
let string = String(format: "Name: %@ \nDate: %@", NameField, DateField)

A: use String Interpolation
    let firstName = "Hai"
    let date = NSDate()
    let messageBody = NSString(format: "Name: \(firstName) \n Date: \(date)")
    NSLog(messageBody as String)


text:
Q: How can I redact passwords in a Charles Proxy trace I need to document an HTTP authentication issue with a Charles Proxy trace but I want to redact the passwords in the resulting trace file.
Hand-editing the binary .chls file produced by the "Save" menu command results in a corrupted file, so that is not an option.

A: Instead of saving the trace to a .chls file, export it with the "File > Export..." menu command to an "XML Session File".

You can then edit the resulting XML file before handing it off, and the recipient will be able to import it into Charles with the "File > Import..." command and view it.


text:
Q: I cannot add a new Trigger to Google Script. UI Change this may be a stupid question but I used to be able to add Triggers in the Google UI but just recently, I am not able to do this anymore. Here is a screenshot. Can somebody help?
Thanks!


text:
Q: Detect if WM_MOUSEMOVE is caused by touch/pen I am experimenting with WM_TOUCH and want to detect if mouse events are synthesized from touch/pen events or due to an actual mouse event.
The official solution according to MSDN is to check if the result of GetMessageExtraInfo() has the upper 24 bits set to 0xFF515700.
This works. Most of the time. If I use one finger, all is well and good, but if I use more than one, releasing the last one causes a mouse move with GetMessageExtraInfo() == 0. Also, when the window loses focus via touch, up to 3 mouse move messages with GetMessageExtraInfo() == 0 are generated.
Is there a reliable way of disambiguating between mouse, touch and pen inputs?

A: The link you posted does show the only reliable way to discern between mouse messages generated by a physical mouse, and those synthesized in response to touch and pen input.
For completeness, here is the fully working code. The code relies on state that is valid only while handling a mouse message. Calling it at any other time has undefined behavior:
bool IsTouchEvent() {
    const LONG_PTR c_SIGNATURE_MASK = 0xFFFFFF00;
    const LONG_PTR c_MOUSEEVENTF_FROMTOUCH = 0xFF515700;

    LONG_PTR extraInfo = GetMessageExtraInfo();
    return ( ( extraInfo & c_SIGNATURE_MASK ) == c_MOUSEEVENTF_FROMTOUCH );
}

The additional WM_MOUSEMOVE messages you are observing, are an artifact of how the system implements its internal bookkeeping. For example, if a window is shown or hidden, the mouse cursor may be over a different window now, and needs to be recalculated. To do this, the system synthesizes an artificial WM_MOUSEMOVE message.
This effect is explained in Raymond Chen's blog: Why do I get spurious WM_MOUSEMOVE messages?.


text:
Q: My C program prints -39 on a new line and I can't figure out why I've been playing around and trying to experiment with C for my university class and I've found something that my program does even though I did not tell it to!
My full code:
#include <stdio.h>

int main(void) {
  int c;
  while ((c = getchar()) != EOF) {
    printf("%d\n", (c - '1'));
  }
 return 0;
}

The output of it looks like this:
7
6
-39

Now, can anyone tell me why that -39 is being printed?

A: Pretty clear if you look at this. First you entered 8 then 7 and then you entered \n (or pressed ENTER) which has ASCII value of 10. 10-49 (49 being the ascii value of '1') is -39 you have printed it.

A: because you input the 'enter' at the end so it subtract the ascii value of enter with ascii value of 1 .
The ascii value of enter is 10 & ascii of 1 is 49 so 10-49 is equal to 39 .


text:
Q: How to use suppressMessages() inside map() I made a function my_fun() which generates messages with the message() function. And also uses pb$tick() to track progress with progress::progress_bar.
I am running this function inside a purrr::map() call to iterate over a long list like: map(my_list, my_fun). So the message is displayed a over and over.
I would like to suppress the message like
map(my_list, suppressMessages(my_fun))
but it has no effect.
The call suppressMessages(map(my_list, my_fun)) works but that suppresses the progress_bar as well.
Is there a convenient way to remove the messages without removing the message()  calls from my_fun()?


text:
Q: Shared axis polar subplots using plotly I'm plotting different Scatterpolar charts using subplots. Yet I want them to all have the same range [0,1]. I've tried using radialaxis and update_layout. However only the first of the subplots changes. Is there a way I can modify all subplots?
lst = range(1,rows+1)
n_rows = list(itertools.chain.from_iterable(itertools.repeat(x, cols) for x in lst))

df_grouped = df.groupby('cluster').mean()
fig = make_subplots(rows=rows, cols=cols, specs=[[{'type': 'polar'}]*cols]*rows,
                    horizontal_spacing=0.05, vertical_spacing=0.06)

for col, (row, index) in enumerate(zip(n_rows, df_grouped.index.values)):
      fig.add_trace( go.Scatterpolar(name="Cluster "+str(int(index)),
                                     r=df_grouped.loc[df_grouped.index == index].values[0],
                                     theta=df_grouped.columns.values),
                    row, col%cols+1)

fig.update_traces(fill='toself')
fig.update_layout(polar=dict(radialaxis=dict(range=[0, 1])),
                  legend=dict(x=0.20,y=1.15), legend_orientation="h",
                  height=800, width=900,
                  margin=dict(l=5, r=5, t=5, b=5)                    )

p = plot(fig, output_type='div')

displayHTML(p)

Thanks in advance.

A: Yes: each polar subplot has its own key in layout so you'll want to do something like update_layout(polar=dict(...), polar2=dict(...), polar3=dict(...), ...)
We don't yet have a single function to batch update all polars like we do for update_xaxes but we will soon :)


text:
Q: How to get the size of tar.gz in (MB) file in python I am doing backups in python script but i need to get the size of tar.gz file created in MB
How can i get the size in MB of that file

A: To get file size in MB, I created this function:
import os

def get_size(path):
        size = os.path.getsize(path)
        if size < 1024:
            return f"{size} bytes"
        elif size < pow(1024,2):
            return f"{round(size/1024, 2)} KB"
        elif size < pow(1024,3):
            return f"{round(size/(pow(1024,2)), 2)} MB"
        elif size < pow(1024,4):
            return f"{round(size/(pow(1024,3)), 2)} GB"

>>> get_size("k.tar.gz")
1.4MB

A: It's not clear from your question whether you want to the compressed or uncompressed size of the file, but in the former case, it's easy with the os.path.getsize function from the os module
>>> import os
>>> os.path.getsize('flickrapi-1.2.tar.gz')
35382L

To get the answer in megabytes you can shift the answer right by 20, e.g.
os.path.getsize('large.tar.gz') >> 20

Although that operation will be done in integers - if you want to preserve fractions of a megabyte, divide by (1024*1024.0) instead.  (Note the .0 so that the divisor will be a float.)
Update: In the comments below, Johnsyweb points out a useful recipe for more generally producing human readable representations of file sizes.

A: Use the os.stat() function to get a stat structure. The st_size attribute of that is the size of the file in bytes.

A: According to Python on-line docs, you should look at the size attributes of a TarInfo object.

A: You can use the below command to get it directly without any hazel
os.path.getsize('filename.tar') >> 20
print str(filename.tgz) + " MB"


text:
Q: Laravel how to load specific column of related table? I have the following code, what I want is to take specific columns of related tables.
auth()->user()->load(['business', 'passwordSecurity']);

A: To select only specific columns from a relationship you should be able to do it like this:
auth()->user()->load([
    'business' => function ( $query ) {
        $query->select('id', 'title');
    },
    'passwordSecurity',
]);

Or like this:
auth()->user()->load(['business:id,name', 'passwordSecurity']);

Please note that you have to select IDs and foreign key constraints that are needed to form this relationship.


text:
Q: Checking if the VPN is still connected and reconnect if needed I have a script written in powershell that connects to a VPN
Now i want to make it reconnect to the VPN if it is disconnected. Can i do that with what i have now ?
I am new to PowerShell so please bear with me.
#Source www.cze.cz
#This script is tested with "Cisco AnyConnect Secure Mobility Client version 3.0.5080"
#Please change following variables

#IP address or host name of cisco vpn
[string]$CiscoVPNHost = "ip address"
[string]$Login = "user"
[string]$Password = "pass"

#Please check if file exists on following paths
[string]$vpncliAbsolutePath = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe'
[string]$vpnuiAbsolutePath  = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe'

#****************************************************************************
#**** Please do not modify code below unless you know what you are doing ****
#****************************************************************************

Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop

#Set foreground window function
#This function is called in VPNConnect
Add-Type @'
  using System;
  using System.Runtime.InteropServices;
  public class Win {
     [DllImport("user32.dll")]
     [return: MarshalAs(UnmanagedType.Bool)]
     public static extern bool SetForegroundWindow(IntPtr hWnd);
  }
'@ -ErrorAction Stop

#quickly start VPN
#This function is called later in the code
Function VPNConnect()
{
    Start-Process -FilePath $vpncliAbsolutePath -ArgumentList "connect $CiscoVPNHost"
    $counter = 0; $h = 0;
    while($counter++ -lt 1000 -and $h -eq 0)
    {
        sleep -m 10
        $h = (Get-Process vpncli).MainWindowHandle
    }
    #if it takes more than 10 seconds then display message
    if($h -eq 0){echo "Could not start VPNUI it takes too long."}
    else{[void] [Win]::SetForegroundWindow($h)}
}

#Terminate all vpnui processes.
Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq "vpnui")
{$Id = $_.Id; Stop-Process $Id; echo "Process vpnui with id: $Id was stopped"}}
#Terminate all vpncli processes.
Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq "vpncli")
{$Id = $_.Id; Stop-Process $Id; echo "Process vpncli with id: $Id was stopped"}}

#Disconnect from VPN
echo "Trying to terminate remaining vpn connections"
start-Process -FilePath $vpncliAbsolutePath -ArgumentList 'disconnect' -wait
#Connect to VPN
echo "Connecting to VPN address '$CiscoVPNHost' as user '$Login'."
VPNConnect

#Write login and password
[System.Windows.Forms.SendKeys]::SendWait("$Login{Enter}")
[System.Windows.Forms.SendKeys]::SendWait("$Password{Enter}")

#Start vpnui
start-Process -FilePath $vpnuiAbsolutePath
#Wait for keydown`enter code here`
echo "Press any key to continue ..."
try{$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")}catch{}

A: You can wrap you code in a function like this:
function Reconnect-VPN {

    #Source www.cze.cz
    #This script is tested with "Cisco AnyConnect Secure Mobility Client version 3.0.5080"
    #Please change following variables

    #IP address or host name of cisco vpn
    [string]$CiscoVPNHost = "ip address"
    [string]$Login = "user"
    [string]$Password = "pass"

    #Please check if file exists on following paths
    [string]$vpncliAbsolutePath = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe'
    [string]$vpnuiAbsolutePath  = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe'

    #****************************************************************************
    #**** Please do not modify code below unless you know what you are doing ****
    #****************************************************************************

    Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop

    #Set foreground window function
    #This function is called in VPNConnect
    Add-Type @'
      using System;
      using System.Runtime.InteropServices;
      public class Win {
         [DllImport("user32.dll")]
         [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetForegroundWindow(IntPtr hWnd);
      }
    '@ -ErrorAction Stop

    #quickly start VPN
    #This function is called later in the code
    Function VPNConnect()
    {
        Start-Process -FilePath $vpncliAbsolutePath -ArgumentList "connect $CiscoVPNHost"
        $counter = 0; $h = 0;
        while($counter++ -lt 1000 -and $h -eq 0)
        {
            sleep -m 10
            $h = (Get-Process vpncli).MainWindowHandle
        }
        #if it takes more than 10 seconds then display message
        if($h -eq 0){echo "Could not start VPNUI it takes too long."}
        else{[void] [Win]::SetForegroundWindow($h)}
    }

    #Terminate all vpnui processes.
    Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq "vpnui")
    {$Id = $_.Id; Stop-Process $Id; echo "Process vpnui with id: $Id was stopped"}}
    #Terminate all vpncli processes.
    Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq "vpncli")
    {$Id = $_.Id; Stop-Process $Id; echo "Process vpncli with id: $Id was stopped"}}

    #Disconnect from VPN
    echo "Trying to terminate remaining vpn connections"
    start-Process -FilePath $vpncliAbsolutePath -ArgumentList 'disconnect' -wait
    #Connect to VPN
    echo "Connecting to VPN address '$CiscoVPNHost' as user '$Login'."
    VPNConnect

    #Write login and password
    [System.Windows.Forms.SendKeys]::SendWait("$Login{Enter}")
    [System.Windows.Forms.SendKeys]::SendWait("$Password{Enter}")

    #Start vpnui
    start-Process -FilePath $vpnuiAbsolutePath
    #Wait for keydown`enter code here`
    echo "Press any key to continue ..."
    try{$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")}catch{}
}

Then, choose an IP address that is only reachable when VPN is connected, and ping it. If ping fails, run the Reconnect-VPN function:
$testIP = "10.10.10.10"

if(-not (Test-Connection $testIP)) {
    Reconnect-VPN
}


text:
Q: Create an Image Grid in Xaringan I'm trying to learn a bit more CSS/HTML to customize xaringan slides and could use some help.
I would like to place a number of GIF's in an image grid like the one shown here into a xaringan slide.

I know that normally one can display two images side-by-side by either using .pull-left[] & .pull-right[] or by defining sections with custom CSS like this:
.left-code {
  color: #777;
  width: 38%;
  height: 92%;
  float: left;
}
.right-plot {
  width: 60%;
  float: right;
  padding-left: 1%;
}

Then one would put the images in a xaringan slide with R code like this:
.pull-left[

]

.pull-right[

]

For an image grid the custom CSS would be:
.row {
  display: flex;
  flex-wrap: wrap;
  padding: 0 4px;
}

/* Create two equal columns that sits next to each other */
.column {
  flex: 50%;
  padding: 0 4px;
}

.column img {
  margin-top: 8px;
  vertical-align: middle;
}

However, it also includes HTML code that specifies all of the images so I'm not quite sure how to integrate the two in a xaringan slide.

A: You can do this using the extension theme here.
This theme is included the later version of xaringan so you can specify in the YAML by css: "ninjutsu". The layout should look like below:
---
title: "Split to grid in `xaringan`"
output:
  xaringan::moon_reader:
    css: ["ninjutsu"]
---

class: split-four

.column[

]

.column[

]

.column[
other images
]

.column[
other images
]