text:
Q: Perl Spreadsheet::ParseXLSX err, format error: can't find EOCD signature help! I have a Perl program using Spreadsheet::ParseExcel. However, there are two difficulties that have arisen that I have been unable to figure out how to solve. perl error is follow:
format error: can't find EOCD signature
 at /usr/local/lib/perl5/site_perl/5.12.0/Archive/Zip/Archive.pm line 719
        Archive::Zip::Archive::_findEndOfCentralDirectory('Archive::Zip::Archive=HASH(0x9103b38)', 'IO::File=GLOB(0x91476d8)') called at /usr/local/lib/perl5/site_perl/5.12.0/Archive/Zip/Archive.pm line 597
        Archive::Zip::Archive::readFromFileHandle('Archive::Zip::Archive=HASH(0x9103b38)', 'IO::File=GLOB(0x91476d8)', '151008171923.xls') called at /usr/local/lib/perl5/site_perl/5.12.0/Archive/Zip/Archive.pm line 565
        Archive::Zip::Archive::read('Archive::Zip::Archive=HASH(0x9103b38)', '151008171923.xls') called at /usr/local/lib/perl5/site_perl/5.12.0/Spreadsheet/ParseXLSX.pm line 35

Help.


text:
Q: Automatic Restart of Raspberry PI I am trying to see the best way to restart the Raspberry PI from Cumulocity, out of the box using PI agent.
This is a use case where the CPU temperature of PI goes up, Cumulocity will trigger a restart. So far the work I have done does the following

*

*Send measurements from PI via MQTT (python paho client). I can see
them show up in Cumulocity

*Using Shell options in cumulocity UI, I send a manual a manual
restart message

*Subscribe the restart message in python client and then issue a
restart to PI

To summarize I would like to how to read the measurements received in Cumulocity and if it reaches above a certain value, trigger an automatic restart of the PI device. That is skip steps b and c above and make it automatic.
Thanks for your help,
JM

A: If you see the measurement in the data point explorer, select "Create Smart Rule" and either "On measurement threshold create alarm" or "On measurement explicit threshold create alarm". Configure the threshold and the alarm type.
When you see the alarm, click on it and again select "Create Smart Rule", using "On alarm execute operation". The template has already restart in it, so you can just click OK.
You can do the same directly by clicking on "Smart Rules", but then you have to enter the measurement names and alarm types manually.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Haskell Lens composition of ?~ We have an operator ?~ in Lens.
We can do a & b . c ?~ d if _c is a field of b type. What should I use if b has a Maybe (type of _c) type?

A: Perhaps something like:
[Just (Just 1, 'a')] & _head . _Just . _1 ?~ 2


text:
Q: SSJS Create Data Extension with Retention I'm using following SSJS script to create a Data Extension and set the retention of 7 days at row level:
Platform.Load("core", "1.1");
var deObj = {
    "CustomerKey": "my_DE",
    "Name": "my DE",
    "DataRetentionPeriodLength": 7,
    "DataRetentionPeriod": "Days",
    "DeleteAtEndOfRetentionPeriod": true,
    "RowBasedRetention": false,
    "ResetRetentionPeriodOnImport": false,
    "Fields": [{
            "Name": "id",
            "FieldType": "Text",
            "MaxLength": 100,
            "IsPrimaryKey": true,
            "IsRequired": true
        },
        {
            "Name": "person_id",
            "FieldType": "Text",
            "MaxLength": 80
        }
    ]
};
try {

    var myDE = DataExtension.Add(deObj);

} catch (ex) {
    Write("An error has occurred: " + Stringify(ex));
}

I could not find any documentation around the Retention attributes but I took the SOAP envelope attributes and tried using it in SSJS. But I keep getting error. Are the DataRetentionPeriodLength , DataRetentionPeriod , DeleteAtEndOfRetentionPeriod , RowBasedRetention , ResetRetentionPeriodOnImport  not supported with SSJS DataExtension.Add function?

A: As @Gortonington mentioned above DataExtension.Add works of you give Data Manager role. But as we found out from one of our Salesforce Consultant WSProxy works without this role as well. The code he shared was as below:
    Platform.Load("Core","1.1.1");

    var prox = new Script.Util.WSProxy();
    var name = "Retention_Testing";

    var de = {
        Name: name,
        CustomerKey: name,
        Description: "Retention_Testing",
        Fields: [{
            FieldType: "Text",
            Name: "Field1",
            MaxLength: 254,
            IsPrimaryKey: true,
            IsNillable: false,
            IsRequired: true
    },
    {
        FieldType: "Text",
        Name: "Field2",
        MaxLength: 254
    }],
    DataRetentionPeriodLength: 7,
    DataRetentionPeriod: "Days",
    RowBasedRetention: 0,
    ResetRetentionPeriodOnImport: 1,
    DeleteAtEndOfRetentionPeriod: 0
}

  var res = prox.createItem("DataExtension", de);


text:
Q: Pear Barcode 2 - save to disk I am generating a gif barcode using Pear Barcode2.
this currently works and I can see the image as gif image file. so the page is not shown in HTML form but as a stand alone image.
my code is:
$small_graph_height = 55;
        $small_graph_width = 1.2;
        $large_graph_height = 55;
        $large_graph_width = 1.14;
        $type = "gif";
        $code = "code39";
        $to_browser = TRUE;

          include_once "application/libraries/Image/Barcode2.php";

        $ticketno='TDN4993';
              $productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
              $productserial_type = $code;
              $productserial_imgtype = $type;
              $productserial_bSendToBrowser = $to_browser;
              $productserial_height = $large_graph_height;
              $productserial_width = $large_graph_width;

              $productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);

              ob_start();
                imagepng($productserial_img);
                $productserial_imgBase64 = base64_encode(ob_get_contents());
              ob_end_clean();

              imagedestroy($productserial_img);

               $image= '<img class="ProductSerial" src="data:image/' . $productserial_imgtype . ';base64,' . $productserial_imgBase64 . '">';
            echo $image;

what I want to do is save this image directly to the server hard disk  rather than display it to the user.
I have tried to use PHP's imagegif but it doesnt like the fact that $image is in a string format.
Any advice will be welcome. Thanks as always

A: If you need to save the image on the disk you would need to use imgpng() function.
An example which i got from here.
imagepng($bc->draw($data, $type, 'png', false),'ur_image_location');

A: $small_graph_height = 55;
$small_graph_width = 1.2;
$large_graph_height = 55;
$large_graph_width = 1.14;
$type = "gif";
$code = "code39";
$to_browser = TRUE;

include_once "application/libraries/Image/Barcode2.php";

$ticketno='TDN4993';
$productserial_str = empty($productserial_str) ? ucfirst($ticketno) : $productserial_str;
$productserial_type = $code;
$productserial_imgtype = $type;
$productserial_bSendToBrowser = $to_browser;
$productserial_height = $large_graph_height;
$productserial_width = $large_graph_width;

$productserial_img = Image_Barcode2::draw($productserial_str, $productserial_type, $productserial_imgtype, $productserial_bSendToBrowser, $productserial_height, $productserial_width);

ob_start();
imagepng($productserial_img);
$png = ob_get_contents();
ob_end_clean();

file_put_contents('barcode.png', $png);

echo 'image saved to file barcode.png';


text:
Q: Permanently switching to zsh in a script, without being root and without being asked for the password Is there any way to run chsh -s /bin/zsh without being root and without being asked for the password? I want to put it into a non-interactive script that isn't called by root.

A: If you don't have the permission to change your login shell, you can tell bash (I assume bash is your login shell) to replace itself with zsh. In your ~/.bash_login, add this line:
exec /bin/zsh --login

A: If your version of chsh requires a password (mine does), you will need to setup sudo with special permissions. You can configure it to allow access to any program without prompting for a password like this:
user   ALL=(ALL) NOPASSWD:/usr/bin/chsh

Where "user" is your username (or prefix with % for a group name). Make sure specify the full path to your chsh. This will not allow the user to run anything ELSE as root (including from a script) but it will allow that one binary to be run as root without a password, thus bypassing the user-password prompt.

A: Depending on your exact needs, if you want to do this because you're running a long script and don't want it to hang in the middle to that question, you can ask for the password upfront and then execute chsh with sudo privileges, reading the password from stdin.
read -p 'What is your password?' sudo_password

# rest of the script here

sudo -S chsh -s '/bin/zsh' "${USER}" <<< "${sudo_password}"

-S causes sudo to read the password from stdin. Be aware of possible security risks with this approach (I haven't been able to reproduce that, though, and again, depending on your needs this might not be an issue).


text:
Q: Curl : connection refused I got the following error while running curl:

curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection
  refused.

It seems that it is easy to debug, but, I didnt find how to solve it.
The adress 127.0.0.1 is mentioned in the file etc/hosts.
I am using curl version 7.47 on Ubuntu system.
Anyone has an idea about it ?
Thank you.

A: Try curl -v http://localhost:8080/ instead of 127.0.0.1

A: Make sure you have a service started and listening on the port.
netstat -ln | grep 8080

and
sudo netstat -tulpn

A: Listen to the port in one session and then open another session to test it with l$ curl -v http://localhost:8080/
It should work. That's how I worked although in l
Termux

A: You have to start the server first, before using curl. On 8/10 occasions that error message arises from not starting the server initially.

A: 127.0.0.1 restricts access on every interface on port 8000 except development computer. change it to 0.0.0.0:8000 this will allow connection from curl.


text:
Q: EL not evaluated in the 'id' field Currently I am using a rich:dataTable to loop through records.  I simply output the text like this:
<h:outputText value="#{property.variableName}" />

This displays the data properly in the table.  Now I want to add IDs to test my stuff.  I tried adding the same property as the ID like this:
<h:outputText id="#{property.variableName}" value="#{property.variableName}" />

The result is an empty ID error.  I prepended it with "id_" and all that gets returned to the DOM is "id_"  (no property variableName) added to it.
Am I losing my mind?  I feel as if this should work as I've done it in the past.


text:
Q: Passing one object to many classes using Java I need to pass an object from one class to many different classes.
The aim of this is to create one method that broadcasts the object to any other classes that are listening. This is so that more classes can be added and I just need to implement a listener function for that class and not edit any of the framework.
I am trying to accomplish this without the use of JMS (if it's possible!)

A: Observer pattern to the rescue! Woooosh!
Let your Subject define a method for relaying that object to many listening Observers. You can then dynamically add and remove listeners.


text:
Q: How to enable ManipulationDelta event outside of ScrollViewer in Windows Phone 8? I wrote a xaml with a scrollviewer, and the scrollviewer is replaced inside a frame. I want to register the ManipulationDelta event for the frame, but I failed. If that is possible to register ManipulationDelta event outside of the scrollviewer control in windows phone 8?
<Grid>
    <Frame ManipulationDelta="Frame_ManipulationDelta">
        <ScrollViewer>
            <StackPanel>
                <ListView x:Name="List">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
                <ListView x:Name="List2">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding}" Foreground="Blue"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackPanel>
        </ScrollViewer>
    </Frame>
</Grid>


text:
Q: How to replace a complex string with a column in one column of a file? I have a file (1kG_MDS5.bim) like this:
1   rs58108140  0   10583   A   G
1   1:11508[b37]A,G 0   11508   A   G
1   1:15820[b37]G,T 0   15820   T   G
1   1:16257[b37]C,G 0   16257   C   G
1   1:16378[b37]C,T 0   16378   T   C

I would like to remove all occurrences of  [b37] in the 2nd column and also replace comma with column so that the FINAL result looks like this:
1   rs58108140  0   10583   A   G
1   1:11508:A:G 0   11508   A   G
1   1:15820:G:T 0   15820   T   G
1   1:16257:C:G 0   16257   C   G
1   1:16378:C:T 0   16378   T   C

I tried to partially solve this (by just removing [b37])  by running:
sed -i -E 's/([b37])/:/g' 1kG_MDS5.bim

but I got this:
1   rs58108140  0   1058:   A   G
1   1:11508[:::]A,G 0   11508   A   G
1   1:15820[:::]G,T 0   15820   T   G
1   1:1625:[:::]C,G 0   1625:   C   G

Can you please advise me on how to get the final results where the lines would look like shown above. It doesn't need to be sed solution (awk would be great) Also this file contains about 6 million lines.

A: You can try this:
sed 's/\[b37\]\(.\),/:\1:/' 1kG_MDS5.bim

Output:
1   rs58108140  0   10583   A   G
1   1:11508:A:G 0   11508   A   G
1   1:15820:G:T 0   15820   T   G
1   1:16257:C:G 0   16257   C   G
1   1:16378:C:T 0   16378   T   C

The problem in your pattern is that the brackets are not escaped, so sed tries to replace the occurrences of b, 3 and 7, not the string "[b37]".


text:
Q: Save HashMap properties to a properties file, and load those properties back to the HashMap So I run into a casting problem with storing HashMap properties to a Properties file because the key of the HashMap is an object that cannot be cast to java.lang.String because properties must be (String, String) and my HashMap is (Object, Long).
I just want to save the contents of the HashMap to a file so I can load those contents back into the HashMap the next time the program is ran.
I have gone through an excessive amount of worthless attempts to try to refill HashMaps with objects they contained before they were saved. I tried to think of an easy way to convert the object to a string which I can do, but since Properties and HashMaps are not indexed, I can not change those strings back to the object they need to be. How to achieve this?
Here is what I am trying to do:
    public File savedHashMaps = new File("SavedHashMaps.list");
// in my case, the object is 'Location' from an implemented API
public Map<Location, Long> map = new HashMap<Location, Long>();

public void saveMaps() {
    Properties prop = new Properties();
    try {
        if (!map.isEmpty()) {
            prop.load(new FileInputStream(savedHashMaps));
            prop.putAll(map);
            prop.store(new FileOutputStream(savedHashMaps), null);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void loadMaps() {
    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream(savedHashMaps));
        if (!prop.isEmpty()) {
            map.putAll((Map)prop);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

A: Using an ObjectInput/OutputStream
public File savedHashMaps = new File("SavedHashMaps.list");
public Map<Location, Long> map = new HashMap<Location, Long>();

public void saveMaps() {
    try {
        ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream(savedHashMaps));
        oos.writeObject(map);
        oos.close();
    } catch (Exception e) {
        // Catch exceptions
    }
}

public void loadMaps() {
    try {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(savedHashMaps));
        Object readMap = ois.readObject();
        if(readMap != null && readMap instanceof HashMap) {
            map.putAll((HashMap) readMap);
        }
        ois.close();
    } catch (Exception e) {
        // Catch exceptions
    }
}

This is from memory, so sorry for errors, however this will save and reload all your Location, Long mappings. Also as a note, the Location class must implement Serializable (or have a super-class that implements it)(It's a marker interface (See java.dzone.com/articles/marker-interfaces-java) so you just add implements Serializable).


text:
Q: Getting and manipulating a value of a key from an array of objects using Mongoose This is a document from my profiles collection:
{
    _id: ObjectId("5f2ba3a43feccd0004b8698c")
    userID: "238906554584137728",
    serverID: "533691583845892100",
    username: "W.M.K",
    money: 15775,
    __v: 4,
    items: [...],
    serverName: "W-15i: Overworld",
    gladium: 7959.33,
    stocks: [{
        _id: {...},
        stockID: "605b26d309a48348e05d88c9",
        name: "GOOGL",
        amount: 1,
        desc: "Alphabet Inc's (Google) Stock."
    }]
}

I'm using const profile = await Profile.findOne({userID: userID, 'stocks.stockName': stock.name})
EDIT: For one stock, it's as easy as profile.stocks[0].amount -=1. But when I have multiple stocks, how do I get the amount and manipulate it like amount -= 1?

A: there are few ways you can go through an array of objects in mongoose... you can map through the array,  you can also use dot notation in an update.  Either way one thing you'll need to do is mark the document modified because mongo doesn't detect changes in arrays of objects.   To do this, make the changes and then use the markModified() function on the document.  It takes a parameter of the array field name that was modified.   in this case....  profile.markModified('stocks')
This is done after changes and before the save.
You can use dot notation with mongoose and you can also iterate through the array via map or forEach
The benefit of using map is that you can double it up with .filter() to filter the array for certain stocks

A: As already stated by Jeremy, it is basically a matter of array manipulations.
Here is one example:
for(let i = 0; i < profile.stocks.length; i++) {
 profile.stocks[i].amount -= 1;
}

If you just want to update the profile on your database, you could also look into some very advanced mongodb querys (I think it's called "aggregation"), but that is probably overkill.


text:
Q: Integrate a MS Word Editor I'm currently creating a web site, in which I want to integrate a Microsoft Office Word editor. I'm not searching a javascript lib like 'https://poi.apache.org/' but a UI editor.
Is there anything available on the Microsoft API's page or should I find it somewhere else ?

A: You can use TinyMce WYSIWYG editor for your website. Here Is the demo:
It's like word editor, but if you can't use java files in your website, you can use it as CDN .. here is the tinymce cdn library

A: I highly recommend using CKEditor since there's a free open source version of it.
CKEditor


text:
Q: Google Maps Javascript API: Elevation Graph Along a Direction I am using Google Maps API to build an website and I'm having trouble building the Elevation Graph. Google gives an example in their documentation but it refers to declaring some waypoints which is not my case. I am using Directions API so Google is automatically building the path.
Here is my code:

Someone can help me with this?

A: Pass the path returned from the directions service to the elevations service.
Inside the callback from the directions service, pass the overview_path in the returned result to the getElevationAlongPath function as the path.
if (status == 'OK') {
    directionsDisplay.setDirections(response);
    elevationService.getElevationAlongPath({
      path: response.routes[0].overview_path,
      samples: SAMPLES
    }, plotElevation);

    console.log(response);
  } else {
    window.alert('[directionsService] error: status: ' + status);

Where the callback to the elevations service is:
  // Takes an array of ElevationResult objects
  // and plots the elevation profile on a GViz ColumnChart
  function plotElevation(results) {
    elevations = results;

    var path = [];
    for (var i = 0; i < results.length; i++) {
      path.push(elevations[i].location);
    }

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Sample');
    data.addColumn('number', 'Elevation');
    for (var i = 0; i < results.length; i++) {
      data.addRow(['', elevations[i].elevation]);
    }

    document.getElementById('chart_div').style.display = 'block';
    chart.draw(data, {
      width: 512,
      height: 200,
      legend: 'none',
      titleY: 'Elevation (m)',
      focusBorderColor: '#00ff00'
    });
  }

proof of concept fiddle

code snippet:
(doesn't quite work due to errors: Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.)

/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */

#map {
  height: 50%;
}

#chart_div {
  height: 50%;
}

/* Optional: Makes the sample page fill the window. */

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


text:
Q: ObservableCollection dependency property not updating when add is called I am having some strange problems with my ObservableCollection. I am using .Net 4.0.
I have a viewmodel like this:
PoViewModel : DataViewModelBase
{
    public ObservableCollection<PoDetail> PoDetails { <omitting dp boiler code for ease> }

    public void Add()
    {
        this.PoDetails.Add(new PoDetail()); //<-- this is not getting detected in the wpf UI
    }
}

DataViewModelBase is a DependencyObject
I have this bit of test code that is verifying nothing is happening:
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
    base.OnPropertyChanged(e);
    this.IsDirty = true;
    MessageBox.Show(e.Property.Name + " just changed");
}

What could be the problem? I am assuming I don't understand how ObservableCollections work but from everything I have read this should be working fine.

A: Why do you need a dependency property on your viewModel?
Simply implementing INotifyPropertyChanged should be enough.
Also, you don't expect the property of name "PoDetails" to be updated when adding an element to the ObservableCollection. You should expect the CollectionChanged event of the ObservableCollection instance to be raised.


text:
Q: How cut a substring? I have a lot of string which can contain italic font. I want to copy this string with this font. In each new string I have bold word
Example:
BIG STRING:
I tried:
Public Function GetDefinition(ByVal rngText As Range) As String
Dim theCell As Range
Set theCell = rngText.Cells(1, 1)

For I = 1 To Len(theCell.Value)
    If theCell.Characters(I, 1).Font.Bold = False Then
        If theCell.Characters(I + 1, 1).Text = " " Then
            theChar = theCell.Characters(I, 1).Text
            Else
            theChar = theCell.Characters(I, 1).Text
        End If
        Results = Results & theChar
    End If
Next I
GetDefinition = Results
End Function

A: I think you could use this:
Option Explicit

Sub test()

    Dim LastRow As Long, i As Long, j As Long, PositionOfDot As Long

    With ThisWorkbook.Worksheets("Sheet1")

        'Find last row of column A
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Loop from row 1 to lastrow
        For i = 1 To LastRow
            'Copy paste from column A to C keeping formatting
            .Range("A" & i).Copy .Range("C" & i)
            'Find the position of "."
            PositionOfDot = InStr(1, .Range("A" & i), ".")
            'Delete characters starting from the first one up to PositionOfDot+1
            .Range("C" & i).Characters(1, PositionOfDot + 1).Delete

        Next i

    End With

End Sub

Results:

A: If your bold string always ends with a dot this will do it for you:
Option Explicit
Public Function GetDefinition(ByVal rngText As Range) As String

    Dim SplitBold As Variant

    SplitBold = Split(rngText, ". ")
    GetDefinition = Trim(SplitBold(1))

End Function


text:
Q: OpenCV2 Stitching Header not found I am trying out the stitching module of openCV2. I am following this example https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/cpp/stitching.cpp?rev=6683
The problem is that, I seem to not find the header "opencv2/stitching/stitcher.hpp"
I also tried searching for this file on my system using "locate" on Ubuntu. But I cannot find the file.
Is it required to install this module? Am I missing something?


text:
Q: skip lines that contain semi-colon in text file How can I skip lines in a text file that contain a semi-colon at the beginning of a line? I'm currently reading a text file in with server names which works fine. I want to throw a semi-colon at the beginning of a line to comment it out in case a server is going into maintenance mode.

A: var lines = File.ReadAllLines( path );
foreach( var line in lines )
{
    if( line.StartsWith( ";" ) )
    {
        continue;
    }
    else
    {
        // do your stuff
    }
}

A: EDIT: OK, so we can make this easier...
foreach (var currentLine in File.ReadAllLines(@"C:\somefile.txt"))
{
    if (currentLine.StartsWith(";")) continue;

    // Pretend this is the function you want to do below.
    ProcessLine(currentLine);
}

A: if (!textline.StartsWith(";"))
  // do something

A: Assuming your using something that derives from System.IO.TextReader you could Peek at the next character and see if it's a semicolon.  Otherwise read the line and check the first character of the string.

A: Try this:
        var allLines = System.IO.File.ReadAllLines("SOME-PATH");
        var filteredLines = from l in allLines
            where !l.StartsWith(";")
        select l;

A: I understand you are asking this question for C#.
In this case you can use a startswith from string class, i am not sure how is your code but i think this can help you:
using System;
using System.IO;

class Program {
    static void Main( string[] args ) {
        string filePath = @"test.txt";
        string line;
        string fileContent = "";

        if (File.Exists( filePath )) {
            StreamReader file = null;
            try {
                file = new StreamReader( filePath );
                while ((line = file.ReadLine()) != null) {
                        if (!line.StartsWith(";")){
                                Console.WriteLine( line );
                                fileContent += line;
                        }
                }
            } finally {
                if (file != null)
                    file.Close();
            }
        }
    }
}
}

A: foreach(string line in readLines())
{
   if (line[0] == ';') continue;
   ...
}

A: Maybe StartWith will help
string line = null;
using (System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (!line.StartsWith(";"))
        {
            // do thomething
        }
    }
}

A: in .NET 4.0:
  File.ReadLines("c:\test.txt").Where(x => !x.StartsWith(";"));

Maybe you want AsParallel
  File.ReadLines("c:\test.txt").AsParallel().Where(x => !x.StartsWith(";"));

;)


text:
Q: How to delete all files with 0x00 as content? My hard drive crashed.  However, I was able to make a partial mirror copy and recovered the files from the copy.  Due to the partial copy, the hex content of many files are just 0x00, although file names and folder locations are correct.
I'd like to delete these corrupted files, starting with 0x00 (let's say 8 bytes of 0x00 to be safe) and leaving me the good ones.
Is there a good way to check the Hex content of the first few bytes of a file, and delete these 0x00 files recursively through all folders, either under linux or windows command prompt?
I know this is not a typical task.  I am sure you pros have a genius way of getting this done in a line or two commands.
Thank you very much in advance.

A: In a Windows batch-file you can use the FC command to do a binary compare of one file to another. In this use case you would first create a dummy file with 8 bytes in it of the same character. You can then pipe the output of the FC command to the FIND command to count the instances of the binary compare.  Unlike other shell scripting languages that allow you to assign the output of a command directly to a variable, you need to use FOR /F command to capture the output of a command to assign it to a variable.  In this instance we want to capture the output of the FIND command as it will be telling us how many occurrences of the NULL being at the beginning of the file.  Once you have that number you can then use an IF command to see if it is equal to the number of occurrences you are expecting and then use the DEL command to remove the file.  The FOR /R command is iterating all the files in a directory structure.
@echo off
REM CREATE A DUMMY FILE WITH 8 BYTES
set /p ".=AAAAAAAA"<nul>dummy.txt

REM Get all files
FOR /R %%G IN (*.*) DO (
    REM Compare file to dummy file and count instances of NULLS
    FOR /F "delims=" %%H IN ('fc /b "%%G" dummy.txt ^|find /C ": 00 41"') DO (
        REM Check If we have a file that starts with 8 nulls, delete file
        IF "%%H"=="8" ECHO DEL "%%G"
    )
)

If you are satisfied with the output on the screen, then remove the ECHO to allow the DEL command to execute the file removal


text:
Q: Usage of lazy expressions I am trying to learn regex and I fail to understand the differences in the usage of many code
/apples??/

/.*?[0-9]*/

/.*?[0-9]+/

On the result I understood that if I use ? with  any thing it makes that step optional (or just neglecting it)
e.g.:
the first command will only match apple and not apples
the second command will match 26 in page 26
I expected that the 3rd command will do the same but it matched the whole page 26 string.

A: ? means many different things in a regex, depending on context.
When used as a quantifier it means "optional". For example, [0-9]? matches 0 or 1 digits (an optional digit).
However, when applied to another quantifier, it means "non-greedy". Normal quantifiers try to match as many times as possible (giving up matches only if the rest of the regex would fail otherwise). Non-greedy matching inverts this: It first tries to match as few times as possible and only matches more if the rest of the regex would fail otherwise.
For example, a[a-z]*b applied to abcdebafcbad matches abcdebafcb (or (abcdebafcb)ad(using parentheses to mark the match)). [a-z]* will first consume the whole string, only giving back characters until the following b can match.
However, a[a-z]*?b applied to abcdebafcbad matches ab (or (ab)cdebafcbad(using parentheses to mark the match)). [a-z]*? first starts out by matching no characters at all, and because b is able to match immediately, that's where the regex stops.
As for your examples:
The first thing you need to understand about regexes is the outer loop. There is a loop that tries to invoke the regex engine at every position in the input string, from left to right. If a match is found, the loop stops and reports success. If all positions are exhausted without finding a match, the loop stops and reports failure.
(Strictly speaking we're not looping over the characters in the input string, but over the gaps between characters. ab has 3 possible match positions: before a, between a and b, and after b.)
Your first regex, apples??, is equivalent to apple(?:|s). We match apple followed by either an empty string or s (i.e. we try to match nothing first). Since the empty regex always matches and this is the end of the regex, there's nothing that could come later on and force us to revisit this decision. The regex is equivalent to just apple.
Your second regex, .*?[0-9]*, is a bit curious. The first thing you should notice is that all parts of it are optional, i.e. it can match a string of length 0. Because an empty string can be matched anywhere in the input and the outer loop mentioned above starts at offset 0, this regex will always match at the beginning of the input string.
The second thing to notice is that it attempts to reimplement the outer loop within the regex: .*? will consume 0 characters at first, then (if the rest of the regex doesn't match) 1 characters, then 2, ... until a match is found. This is a bit pointless because the outer loop already does exactly that.
If the input string is page 26, .*? will start out by matching as few characters as possible, i.e. none. Then [0-9]* will try to match as many digits as possible, but p is not a digit, so "as many as possible" is also none. Thus .*?[0-9]* matches the empty string at the beginning of page 26: ()page26 (using parentheses to mark the match).
Your third regex, .*?[0-9]+, still contains that redundant explicit loop at the beginning, .*?. But now the digits part is not optional: [0-9]+ requires at least one digit to match.
If the input string is page 26, .*? will start out by matching as few characters as possible, i.e. none. Then [0-9]+ will try to match as many digits as possible, but at least one. This fails because p is not a digit. Because [0-9]+ failed, we backtrack into .*? and try to consume one more character (p). Then we try [0-9]+ against the remaining input string, age 26. This also fails; we backtrack and consume one more character in .*? (pa). Then we try [0-9]+ against ge 26, which still fails. ...
This continues until .*? has consumed page . At this point [0-9]+ finally finds a digit to match, 2. Because + is greedy, we consume all available digits at this position, 26. The final match is (page 26) (i.e. the whole input string) with .*? matching page  and [0-9]+ matching 26.

A: Bash regex doesn't support lazy quantifier after *, +, ?, so *? +? ?? will outrightly fail
but, if () group is referred back by ${BASH_REMATCH[1]} command, such;
$ [[ "apples " =~ (apples?) ]] && echo ${BASH_REMATCH[1]}

apples
$ [[ "page 26" =~ (.*[0-9]+) ]] && echo ${BASH_REMATCH[1]}

page 26
$ [[ "page 26" =~ .*\ ([0-9]+) ]] && echo ${BASH_REMATCH[1]}

26
works

A: [ This complements the existing answers rather than being an answer in of itself. ]
The following shows the matching process for the examples you provided. (The regex engine may actually take invisible shortcuts to increase performance.)

#0123456
"apples" =~ /apples??/

*

*At position 0, apple matches 5 characters ⇒ Position 5.

*

*At position 5, s?? matches 0 characters* ⇒ Position 5.

*

*Success! Pattern matches 5 characters starting at position 0 ("apple")!

#01234567
"page 26" =~ /.*?[0-9]*/

*

*At position 0, .*? matches 0 characters* ⇒ Position 0.

*

*At position 0, [0-9]* matches 0 characters ⇒ Position 0.

*

*Success! Pattern matches 0 characters starting at position 0 ("")!

#01234567
"page 26" =~ /.*?[0-9]+/

*

*At position 0, .*? matches 0 characters* ⇒ Position 0.

*

*At position 0, [0-9]+ fails to match ⇒ Backtrack!

*At position 0, .*? matches 1 character ⇒ Position 1.

*

*At position 1, [0-9]+ fails to match ⇒ Backtrack!

*At position 0, .*? matches 2 character ⇒ Position 2.

*

*At position 2, [0-9]+ fails to match ⇒ Backtrack!

*At position 0, .*? matches 3 character ⇒ Position 3.

*

*At position 3, [0-9]+ fails to match ⇒ Backtrack!

*At position 0, .*? matches 4 character ⇒ Position 4.

*

*At position 4, [0-9]+ fails to match ⇒ Backtrack!

*At position 0, .*? matches 5 character ⇒ Position 5.

*

*At position 5, [0-9]+ matches 2 characters ⇒ Position 7.

*

*Success! Pattern matches 7 characters starting at position 0 ("page 26")!

#01234
"ooba" =~ /o.*?a/

*

*At position 0, o matches 1 character ⇒ Position 1.

*

*At position 1, .*? matches 0 characters* ⇒ Position 1.

*

*At position 1, a fails to match ⇒ Backtrack!

*At position 1, .*? matches 1 characters ⇒ Position 2.

*

*At position 2, a fails to match ⇒ Backtrack!

*At position 1, .*? matches 2 characters ⇒ Position 3.

*

*At position 3, a matches 1 character ⇒ Position 4.

*

*Success! Pattern matches 4 characters starting at position 0 ("ooba")!

* —  Non-greedy because of the ?, so start by trying to match the least possible at the current position.


text:
Q: How do I stop this download task from running uncontrollably? when I use this code, it downloads a unlimited number of times. It will not stop downloading. Does anyone know why this is?
 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://gps.com/2.js"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];

NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    // Save this following url to load the file
    return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
    NSLog(@"File downloaded to: %@", filePath);
}];
[downloadTask resume];
NSString *javaScript = [NSString stringWithContentsOfURL:URL encoding:NSUTF8StringEncoding error: nil];

[webView stringByEvaluatingJavaScriptFromString:javaScript];

I also have the same problem when using this code:
NSString *jsString = [NSString stringWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"PrivacyView" withExtension:@"js"] encoding:NSUTF8StringEncoding error:nil];
[_viewWeb stringByEvaluatingJavaScriptFromString:jsString];
NSLog(@"Way out of whack :(");

I swear, this is what it looks like when I try to load a javascript file:
2017-05-28 00:03:23.724 App[81886:26511084] File downloaded to: file:///Users/App/Library/Developer/CoreSimulator/Devices/08B20943-5664-415C-87A6-1A6461C6338D/data/Containers/Data/Application/A31516E9-EDE2-4475-84AC-7AD12DE3558F/Documents/App.js
2017-05-28 00:03:25.197 App App[81886:26511084] Logged In?: Yes
2017-05-28 00:03:25.280 App App[81886:26511084] File downloaded to: file:///Users/App/Library/Developer/CoreSimulator/Devices/08B20943-5664-415C-87A6-1A6461C6338D/data/Containers/Data/Application/A31516E9-EDE2-4475-84AC-7AD12DE3558F/Documents/App.js
2017-05-28 00:03:26.188 App App[81886:26511084] Logged In?: Yes
2017-05-28 00:03:26.267 App App[81886:26511084] File downloaded to: file:///Users/App/Library/Developer/CoreSimulator/Devices/08B20943-5664-415C-87A6-1A6461C6338D/data/Containers/Data/Application/A31516E9-EDE2-4475-84AC-7AD12DE3558F/Documents/App.js
2017-05-28 00:03:27.570 App App[81886:26511084] Logged In?: Yes
2017-05-28 00:03:27.635 App App[81886:26511084] File downloaded to: file:///Users/App/Library/Developer/CoreSimulator/Devices/08B20943-5664-415C-87A6-1A6461C6338D/data/Containers/Data/Application/A31516E9-EDE2-4475-84AC-7AD12DE3558F/Documents/App.js
2017-05-28 00:03:28.885 App App[81886:26511084] Logged In?: Yes
2017-05-28 00:03:28.957 App App[81886:26511084] File downloaded to: file:///Users/App/Library/Developer/CoreSimulator/Devices/08B20943-5664-415C-87A6-1A6461C6338D/data/Containers/Data/Application/A31516E9-EDE2-4475-84AC-7AD12DE3558F/Documents/App.js
2017-05-28 00:03:30.254 App App[81886:26511084] Logged In?: Yes

I mean look at how many times its running. It just keeps being called, forever and won't stop.


text:
Q: node.js won't connect to mysql Code:
var mysql = require('mysql');
var db_config = require('./db-config.json');

var connection = mysql.createConnection({
  host: db_config.host,
  user: db_config.user,
  port: db_config.port,
  password: db_config.password,
  database: db_config.database
});

connection.connect(function(err){
  if (!err) {
    console.log("Database is connected... \n\n");
  } else {
    console.log("Error connecting database \n\n" + err);
  }
});

connection.query('select 1+1 as solution', function(err, rows, fields){
  if(err) throw err;
  console.log('The solution is: ', rows[0].solution);

});

connection.end();

and my ./db-config.json is
{
"host": "**.*.**.***",
"user": "***",
"port": "13306",
"password": "****",
"database": "***"
}

and error is
    Error connecting database
Error: Connection lost: The server closed the connection.
C:\project\Nodejs\my-app\routes\db\dbtest.js:21
if(err) throw err;
^

Error: Connection lost: The server closed the connection.
at Protocol.end            (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:113:13)
at Socket.<anonymous>    (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:109:28)
at emitNone (events.js:111:20)
at Socket.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
--------------------
at Protocol._enqueue    (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:145:48)
at Protocol.handshake    (C:\project\Nodejs\node_modules\mysql\lib\protocol\Protocol.js:52:23)
at Connection.connect (C:\project\Nodejs\node_modules\mysql\lib\Connection.js:130:18)
at Object.<anonymous> (C:\project\Nodejs\my-app\routes\db\dbtest.js:12:12)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)

This is very strange because this database is already used in another program and its works just fine.
I think the code itself is the problem because my local mysql has no problem.
I just start learning nodejs & express and at stuck at this very basic stage. Any help is appreciated.

A: You are ending the connection to the DB before the callbacks do their job.
var mysql = require('mysql');
var db_config = require('./db-config.json');

var connection = mysql.createConnection({
  host: db_config.host,
  user: db_config.user,
  port: db_config.port,
  password: db_config.password,
  database: db_config.database
});

connection.connect(function(err){
  if (err) {
    console.log("Error connecting database \n\n" + err);
    throw err
  }
  connection.query('select 1+1 as solution', function(err, rows, fields){
    if(err) throw err;
    console.log('The solution is: ', rows[0].solution);
    connection.end();
    });
});

Callbacks don't execute immediately, they are asynchronous. Your code is getting to connection.end() before it has done all the async operations.


text:
Q: EMI Input Filter Design I have been reading and watching TI's material on EMI input filter design, and I have a few questions.
My basic question is "How do you select the component values for your EMI input filter?" The specific application I am designing a filter for is a 24V, 120W flyback converter in the consumer electronics market.
Next, I will detail what I have learned.
The input EMI filter has 4 main components: Common-Mode choke, X-Cap, Y-Cap, and Filter Inductor.
The CM Choke and Y-Caps are in charge of attenuating the common-mode noise, while the Y-cap and Filter inductor are in charge of attenuating the differential-mode noise.
I believe that the common-mode choke is first selected based on its attenuation curve and what you think the the trouble frequencies will be. You then verify this choice experimentally.
I believe the X-Cap choice is based on power consumption and power factor (according to post linked below)?
X capacitor selection for SMPS power supply
I will admit that I am not sure how to calculate the power consumption of a capacitor in this context.
TI's application notes on the filter inductor put it in the context of a CLC filter, which is confusing because I thought we chose the input/smoothing capacitor value based on the input power and not the required attenuation.
My design (and the reference designs I am using) does not feature any Y-Caps because the line cord does not have an earth-ground connection prong.
Best,
Basically, I just need some help on how to initially determine the values for these components.

A:
The specific application I am designing a filter for is a 24V, 120W
flyback converter in the consumer electronics market.

The very first thing I would do is simulate the circuit in order to understand the current consumption and harmonics in the worst case loading scenario. In other words: -
$$\boxed{\text{Don't try and design any EMC filter values until you have this buttoned-down.}}$$
Then, still using a simulator, I would mimic a feed cable of the appropriate length terminated in a LISN connection so that I can actually get to the noise/interference voltages that might actually be produced by the switcher. LISN example: -

Picture from this website. At this point I have to mention this: -
$$\boxed{\text{The above is an attempt to establish conducted emission values}}$$
Having said that, pretty much most of the radiated emissions are going to be emitted from the feed cable so, it's not such a bad thing to only concentrate on conducted emissions.
Regards the LISN and the feed cable, you will have to decide what the set-up is and, this is determined to a large extent by what conducted emission standard you are trying to meet. I can't tell you what this is so you need to do your homework.
$$\boxed{\text{Decide on the standard and read what LISN it uses}}$$
You will also need to evaluate the feed cable and estimate to what extent it may not be perfectly balanced with respect to earth. You have to do this in order to generate conducted emissions because, if you didn't do this then, in a simulator, because the cable would appear to be "perfect", there would be zero common-mode conducted emissions and that would be pointless to pursue: -
$$\boxed{\text{So, model your power feed cable with attention to detail}}$$
You actually might need to do some physical testing on a cable to determine how imbalanced it might be relative to earth.
The actual easy bit (that takes very little time if done properly) is adding whatever common mode filters and chokes are needed to reduce the emissions to a reasonable level.
However, do not skimp on modelling the CM chokes at this point; do some research on what resonant frequencies the CM choke may have and thoroughly satisfy yourself that your model is good.

My design (and the reference designs I am using) does not feature any
Y-Caps because the line cord does not have an earth-ground connection
prong.

Well, in that case you have no ideal place to connect the CM mode capacitors and you will always sail close to a pass/fail if you do not take great care reducing the harmonics of current consumed through live and neutral. Even more reason to simulate.
$$\boxed{\text{This is how I would do it}}$$
But, there's no guarantees you will pass your conducted emission test because reality is never the same as a simulation. However, not simulating isn't really a viable option these days because you will definitely significantly improve your chances of getting close to a pass by doing so and, pretty much, all from the comfort of your desk.


text:
Q: dynamic sql statement insertion issue I have created a Temp table(#TempTable). I am trying to insert the date to get but I am getting an error. It's a dynamic query.
I am trying to get the date from another table and inserting the date to temp table
Just to make sure you understand the problem I have given an example
DECLARE @OfferEndDateTime datetime
SELECT @OfferEndDateTime = getdate()-1
print @VOfferEndDateTime

DECLARE @SQL VarChar(1000)
SELECT @SQL ='INSERT INTO #TempTable '+
'SELECT D,Points,@OfferEndDateTime '
exec(@sql)

Please  Let me know where I am going wrong

A: You need to use sp_executesql when passing a parameter to dynamic sql
exec sp_executesql @sql, N'@OfferEndDateTime datetime', @OfferEndDateTime=@OfferEndDateTime

A: You have, at least, three problems:

*

*The variable needs to be outside:

SELECT @SQL ='INSERT INTO #TempTable '+
'SELECT D,Points,' + @OfferEndDateTime

*

*The variable needs to be varchar type or similar

*What is D,Points? They are not defined anywhere. If they are varchar values you nead to quote them (use " or '') for that purpose.

If you need to use the parameter like datetime you should use sp_executesql instead. Check HERE for some info on it!


text:
Q: Can't see newly created parition (and formatted as ExFat or NTFS) in Bootcamp (Windows 7) I'm trying to resize my Bootcamp partition and finally shrunk my AFPS partition smaller and formatted the new partition to NTFS (and later to ExFAT) in hope to be able to see it in Windows and merge it with Bootcamp (Since I can't do it in macOS due to my Boocamp partition being NTFS) but I can't see it in Windows in any program I try to merge them. I just see Bootcamp partition and one big "Apple" one which in fact should be three.
(I'm Using Mojave)
Thanks
Here is the result of my "diskutil list" command:
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *750.2 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                 Apple_APFS Container disk1         413.9 GB   disk0s2
   3:       Microsoft Basic Data newly                   259.9 GB   disk0s3
   4:       Microsoft Basic Data BOOTCAMP                76.0 GB    disk0s4

/dev/disk1 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +413.9 GB   disk1
                                 Physical Store disk0s2
   1:                APFS Volume Macintosh HD            301.7 GB   disk1s1
   2:                APFS Volume Preboot                 22.3 MB    disk1s2
   3:                APFS Volume Recovery                509.8 MB   disk1s3
   4:                APFS Volume VM                      4.3 GB     disk1s4


text:
Q: Flutter androidManifest.xml Parsing Eror I am developing Flutter on Vs Code,
This is my AndroidManifest.xml files and I get this error :Please ensure that the android manifest is a valid XML document and try again
I think I have a double quotes or other problem,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.object_detection">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Object Detector"
        android:icon="@mipmap/launcher_icon">
        <meta-data android:name="com.google.android.gms.ads.APPLICATIN_ID" android:value
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

A: You are have a android:value that is not in parameter. This is corrected Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.object_detection">
    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="Object Detector"
        android:icon="@mipmap/launcher_icon">
        <meta-data android:name="com.google.android.gms.ads.APPLICATIN_ID"
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>


text:
Q: Converting a 3D numpy array to coordinates and values I have a 3D numpy array of shape (7,100,50) that represents a stack of 7 100x50 images.
I want to convert this array to a dataframe containing the position of all pixels x,y,z and the value of the pixel (id)
I have managed to do this for a single image (no z):
import numpy as np
import pandas as pd
img = np.random.randint(0,30,size=(100,50))
cell_id = img.flatten()
x = [i % img.shape[1] for i in range(len(cell_id))]
y = [y_ for y_ in range(img.shape[1]) for _ in range(img.shape[0])]
df = pd.DataFrame(data={"id":cell_id, "x":x, "y":y, "z":0})
df:
    id  x   y   z
0   29  0   0   0
1   16  1   0   0
2   3   2   0   0
3   15  3   0   0
4   23  4   0   0
...     ...     ...     ...     ...
4995    7   45  49  0
4996    6   46  49  0
4997    1   47  49  0
4998    5   48  49  0
4999    7   49  49  0

5000 rows × 4 columns

How do I adjust this to work for
zimg = np.random.randint(0,30,size=(7,100,50))

?

A: import numpy as np
import pandas as pd
img = np.random.randn(7,100,50) # (z,x,y)
mapping = {
    'x': [],
    'y': [],
    'z': [],
    'id': [],
}
for z in range(7):
    for x in range(100):
        for y in range(50):
            mapping['x'].append(x)
            mapping['y'].append(y)
            mapping['z'].append(z)
            mapping['id'].append(img[z][x][y])
df = pd.DataFrame.from_dict(mapping)
df.head()

Or
you could do what you just did 7 times, z values would change and just concatenate each table using pd.concat

A: I see you mentioned np.ndenumerate in another comment, this should do the trick:
import pandas as pd
import numpy as np

def constructor(array, z=0):
    """Transform an array into df

    Here we assume z=0 as in your example
    """
    for (img_id, y, x), value in np.ndenumerate(array):
            yield (img_id, value, x, y, z)

a = np.random.randint(0,30,size=(7,100,50))

df = pd.DataFrame(
    constructor(a),
    columns=('image_id', 'id', 'x', 'y', 'z')
)

A: I will take same shape but smaller size of (2,10,5) so that output is easy to interpret and also code can run on online compiler where I am validating. You can give original size of (7,100,50).
import numpy as np
import pandas as pd
x = np.random.randint(0,30,size=(2,10,5))
x[x==0] = -1 #replace 0 with -1 to use np.nonzero
val = np.transpose(np.nonzero(x)) #get pixel indices as 2d array
id = x[np.nonzero(x)] #get pixels as 1d array
df = pd.DataFrame.from_records(val) #create df
df = df.set_index(id) #set new index
df.columns = ['x','y', 'z'] #set column names
df.index.name = 'id' #set index column name
df = df.reset_index() #reset index to get id as column
df = df.clip(lower=0) #replace -1 in id with 0
print(df.head(100))

Output:
    id  x  y  z
0    6  0  0  0
1   17  0  0  1
2   19  0  0  2
3   26  0  0  3
4   12  0  0  4
..  .. .. .. ..
95  16  1  9  0
96  26  1  9  1
97   8  1  9  2
98   5  1  9  3
99  13  1  9  4


text:
Q: Create an L-shaped border using HTML and CSS, is it possible? Is it possible to create an L-shaped border like this using only HTML and CSS?

Edit: That is what I have at the moment: http://jsfiddle.net/cBwh8/
Edit2: I'm looking to replicate the picture above -- appropriately curved round corners. This is the main reason I'm having difficulties here: http://jsfiddle.net/cBwh8/1/

A: Yes.
http://jsfiddle.net/HwKGx/1/

#one {
    margin:10px;
    width:45px;
    height:75px;
    border:2px solid #333; }
#two{
    float:left;
    width:35px;
    height:65px;
    border-width:2px;
    border-style:solid;
    margin:-2px 0 0 -2px;
    border-color:#FFF #333 #333 #FFF;
}

A: Try this: worked for me
div.outer {
    margin: 10px;
    width: 200px;
    height: 200px;
    border: 1px solid blue;
    border-radius: 10px;
}

div.inner {
    width: 160px;
    height: 160px;
    border-right: 1px solid blue;
    border-bottom: 1px solid blue;
    margin-top:-1px;
    margin-left:-1px;
    background:#FFF;
}

A: Little bit tricky but had fun doing this
.left{float:left}
.right{float:right}
#container{border-right:1px solid #000;border-bottom:1px solid #000;width:300px;height:300px;margin:100px auto;}
#leftBox{width:70%;height:69%;border-right:1px solid #000;border-bottom:1px solid #000;}
#leftBox2{border-left:1px solid #000;width:100%;height:29%;}
#rightBox{width:29%;height:70%;border-top:1px solid #000;}

and the mark up

A: A slightly more complex, but useful option:
http://dabblet.com/gist/2884899
This is two sibling elements, absolutely, and relatively positioned, z-indexed to overflow over one another.
the top div hides the bottom div's topborder.
This is extra useful for drop down menus. (to have a bordered box, expand with a context menu)
EDIT( code pasted from link ):
HTML:

css:
.holder{
  position:relative;
}

.top{
  width: 50px;
  height:50px;
  background:red;
  border:blue solid 2px;
  border-bottom:none;
  position:relative;
  z-index:4;
}

.bottom{
  z-index:2;
  width: 100px;
  height: 100px;
  position:absolute;
  top:50px;
  left:0;
  border: blue solid 2px;
  background:red;

}

A: For anyone interested, here's an L-Shaped set of Fieldsets:
JSFiddler code
HTML:

        <fieldset class="topPortion">
            <legend>Some legend</legend>
            <input type="text" value="Foo" />
            <input type="submit" value="Submit" />
        </fieldset>
        <fieldset class="bottomPortion">
            <input type="text" value="Foo" />
            <input type="submit" value="Submit" />
        </fieldset>

CSS:
fieldset.topPortion
{
border: 1px solid red;
border-bottom: 0;
/*top: 20px;*/
padding: 5px 5px;
position: relative;
width: 250px;
z-index: 100;
background-color: yellow;
top: 1px;
border-radius: 5px 5px 0 0;
}

fieldset.bottomPortion
{
border: 1px solid red;
width: 500px;
height: 100px;
position: absolute;
z-index: 1;
margin-top: -10;
padding: 5px 10px;
background-color: yellow;
border-radius: 0 5px 5px 5px;
}

A: NECRO, actually I just had this issue and this was the first post I found, so I'd like to add to it a little, in case someone else lands here with the problem or if the problem is still occurring.
Using the edit2 that you linked, change "border-radius" with "border-bottom-right-radius" this makes it so only the bottom right corner ends up being rounded, thus fixing the weird rounded/faded edges.
You can also add in things like
-moz-border-radius-bottomleft: 10px;
-webkit-border-bottom-left-radius: 10px;
If you wanna give more support to older browsers.


text:
Q: "Hippo CMS" in my "Eclipse Luna", Tomcat not starting I am trying to integrate "Hippo CMS" in my "Eclipse Luna". For that i installed "Tomcat 8". But when i am trying to run the tomcat after adding the module to it. It is throwing error

"java.lang.NoClassDefFoundError: Lorg/slf4j/Logger".

I searched over google, it gives a solution, "That I either did not copy the shared folder correctly, or I did not copy the conf/catalina.properties correctly". But what need to be done, to resolve this issue and start my server?

A: If you are working locally then you can start your server with the mvn profile 'cargo.run'. This will automatically deploy a tomcat version.
If you need a standalone tomcat then perhaps this page will help you:
http://www.onehippo.org/library/development/create-a-project-distribution.html


text:
Q: Is this a Chrome UI performance bug related to input + datalist? I have a data entry input form with (invoice + details) that are added dinamically. For the product search I've created an input linked to a datalist with options. Whenever the user types, it filters a big array of products with JS and then replaces the contents of the linked datalist with the constructed options, so it's updates the suggestions (it's like jQuery autocomplete but all native). So far, so good.

Now, when I keep adding details to the invoice, the performance of the search operation starts to degrade.. (Version 59.0.3071.115 (Official Build) (64-bit) on MacOsX and Windows). I've started to profile stuff, and I nailed the problem to the line that sets up the innerHTML of the datalist:
  updateDatalist: (filter = '') =>
    options = @buildOptions(@filterWith(filter))
    console.time 'updateDatalist'
    @$datalist[0].innerHTML = options
    console.timeEnd 'updateDatalist'

The performance timer starts reporting ~30ms when there is only one detail, and then it scales to 500-700ms when there are 10 aprox. I've been profiling, guessing that there should be something wrong with my setup but nothing. Then I try it with Firefox and, wala, it works perfect always and performance never degrades.

Do you think it's a bug or I'm missing something? Should I report it and how?
EDIT: Here is a complete gist of the source: https://gist.github.com/vizcay/969f2b492630b12a520adb6e7433628e

A: Well I managed to find a workaround around this, and I want to leave it here for the poor soul that happens to meet the same problem again:
1) This has nothing to do with the filtering of the array data, as was confirmed by the profiling. But I've actually replaced the filtering function with a fixed string of options and the performance bug was still present.
2) The performance hit is proportional to: a) the number of options introduced into the datalist by innherHTML (or $.html etc) and b) the number of datalists in the page.
To solve this issue what  I've done is to unlink the datalist to the input by means of removing it's id, then setting the innerHTML and finally linking again them by restoring the id. It looks like there is some kind of event handler related to Chrome UI that when the two are linked is doing something stupid.


text:
Q: Finding the Cheapest path connecting multiple nodes I have a grid, where I have to connect multiple nodes(cells) with a single branching path (with obstacle cells at different positions). Path is, by nature, bidirectional. Any node can be source or destination, without affecting the problem. I want to connect all the selected nodes with a single cheapest branching path.
Currently, the approach I am using is as follows:

*

*We pick an arbitrary order nodes, say [1,2,5,0,3,4].

*First we create the cheapest path between two of the nodes, in this case between nodes 1 and 2 using A*.

*Then, we take the third node (in this case 5) and find the cheapest path between the third node and each node of the cheapest path between 1 and 2. Then, we pick the path, which is the shortest among all those paths.

*We repeat this process until we have a path connecting all the nodes.

The above process is repeated for various such orders till we find the cheapest possible path. However, I feel like this method is very, very suboptimal and there has to be a better way to go about solving this problem.
I also found this particular question(pathfinding with multiple source and sinks?) which is similar but in this case, the output seems to be having multiple paths.But, in my case, I want a single path connecting the selected nodes (branching is allowed). I have a feeling that Dijkstra's algorithm (atleast from my limited understanding of it) might be the one that will work in this case.
Any help(papers or articles) will be much appreciated. Thank you.

A: I think you are looking for a spanning tree

https://en.wikipedia.org/wiki/Spanning_tree

not looking to connect all the nodes, but only few specific nodes
among a grid of large number of nodes

*

*Calculate cheapest path between each pair of specific nodes ( Dijkstra )

*Remove all nodes that are not specific

*Remove all edges

*Add edges between pairs of specific nodes with the cost of the cheapest path between them

*Calculate spanning tree.


text:
Q: simplest way to rename multiple files in a folder? I have files with names like below and i need to change that to the right side format.
CK-123443-1.dft  - CK-123443.dft
CK-123344-A.dft  - CK-123344.dft
123322-B.dft     - 123322.dft

I tried using split('-') but this is not working for all files because some files have two hipen and some have one. can I get any other solution for this problem?
My Code with re:
i am not sure about the re-expression
import re
new = re.sub('-', '.', old)

A: If you are sure that every filename in the directory has a hyphen that needs to be removed, you can split at hyphens and only exclude the last split part.
So, something like this:
name, ext = file_name.split('.')  # Get the 'dft' part aside

new_name = ''.join(name.split('-')[:-1]) + f'.{ext}'

A: SOLUTION:
import re
#assuming that your file is called file_name
new_name = re.sub('-[A-Za-z0-9]\.', '.', file_name)
#this replaces the characters after the last hyphen and before the extension.

I think you can easily do it using regex - before I tell you what pattern to match though, I need some more clarity on how you want the name to change - do you want to maintain any leading alphabet characters and remove all trailing characters after a hyphen and before the extension?


text:
Q: Show that if $c : \mathbb R → \mathbb R^n$ is a parametrisation by arc-length of a closed curve, then c is periodic. Show that if $c : \mathbb R → \mathbb R^n$ is a parametrisation by arc-length of
a closed curve, then c is periodic.
My attempt:- I know the definition of periodic curve as A parametrised curve $c : \mathbb R → \mathbb R^n$ is called periodic with
period $L$ if for all $t ∈ \mathbb R$ we have $c(t + L) = c(t), L > 0,$ and there is no
$0 < L'
< L$ such that $c(t + L'
) = c(t)$ for all $t ∈ \mathbb R$ as well. A curve is called
closed if it has a periodic regular parametrisation.
I know here Period will be arc length($S$) of the curve. Let $c:[0,S]\to \mathbb R^n$ represent the closed curve. $c(s+S)=c(\int_0^s||\dot{c}(t)||dt+ S)$. I don't know How to proceed further. Please help me.

A: Suppose you have an arc-length parametrization $c(s)$ of a regular closed curve. Being closed, according to your definition, means that there is a regular parametrization $\gamma:\mathbb{R}\to \mathbb{R}^n$ which is periodic, $\gamma(t+L)=\gamma(t)$ for any $t$ ($L$ is the principal period, as in your definition). Choose $t_0$ such that $\gamma(t_0)=c(0)$. By regularity, $\|\gamma'(t)\|>0$ and then
$$
s(t)=\int\limits_{t_0}^t\|\gamma'(r)\|\,dr
$$
is a strictly increasing function, with $s(t_0+L)=S$ (total length of the curve) and $s(t)=at+f(t)$, where $a=S/L$ and $f$ is periodic with period $L$ (this is a general fact: the integral of a periodic function is linear + periodic, you can easily prove this yourself). Therefore, for any $s=s(t)$,
$$
c(s+S)=\gamma(t+L)=\gamma(t)=c(s),
$$
thus proving the claim.


text:
Q: Javascript "imageflow" IE not loading, slow in other browsers I'm using a javascript script called ImageFlow. It runs fine in FF/Chrome, however is very slow and hangy.
In IE (9,8,7) it just refuses to load at all. There are no JS problems, and I can't post the code as there is too much and I also didnt code any of the site so dont know what triggered it to go wrong.
The demo site is http://crofts.propertylogic.net and the JS for the imageflow can be found at http://crofts.propertylogic.net/coverflow/imageflow.js . The effect is meant to slot into the white box in the middle of the page, with the team members, as you can see on chrome/ff. If anyone could point me in the right direction that would be great.

A: I can't fix the code for you, but I can tell you basically why it isn't working in IE9. The init event that finds the 'myImageFlow' div is happening before that div has been read into the DOM. I believe it's because of the way the ImageFlow plugin imitates the DOMContentLoaded event for IE. The ImageFlow plugin uses the DOMContentLoaded plugin which hasn't been updated since May '08. I would bet you that library is out of date and as a result it is breaking ImageFlow, which also looks to be quite out of date.
I would honestly suggest that you look for a more modern plugin. If that doesn't help, try messing around with the DOMContentLoaded section to see if you can figure out why it is not delaying long enough in IE9 (use the debugger F12).

A: If you didn't code any of the site, chances are you didn't install imageflow at the site either. But installation has been covered, right? Or maybe not!
http://finnrudolph.de/ImageFlow/Installation

The image width and height parameters (w_x and h_x) must be set in the XHTML for full compatibility with the Internet Explorer. Sorry for
  this extra load of work - every browser but Microsofts Internet
  Explorer can fetch the right image dimensions via the JavaScript!

That means would you have to insert the image dimensions into the xhtml at server side for ie I think. Is that currently being done?

A: Checked the website on IE8 and seems to be working fine with animation bit, only things i the Images looks stretched vertically.

A: you can fix this using jQuery - all are correct the dom handler is the issue.
$(document).ready() is the key

$(document).ready(function()
{
    var circular_3 = new ImageFlow();
    circular_3.init({ ImageFlowID: 'imageflow1',
        //circular: true,
        reflections: false,
        reflectionP: 0.4,
        slider: false,
        captions: false,
        opacity: true,
        xStep: 250,
        imageFocusM: 1.5,
        startID: 2
    });

A: I know this is a little late to answer this question. InvisibleBacon is correct in that the domReady code hasn't been modified since 2008, but I checked the domReady code and it does work for IE 5 through 11, Firefox, Chrome, Mobil Chrome, Safari, and Mobile Safari. I did not check the code with Opera.
In this case I would say the problem is with the imageflow.js code you were using, which I see you no longer use.


text:
Q: zend framework 2 underscore private Will Zend Framework 2 continue to place underscores in front of private members and methods of classes? e.g:
class blah {
    private $_name;

    private function _doSomethingToName()
    {
    }
}

I see that they are still there in the dev release of ZF2.

A: Probably yes, accodring to the poll:

There are currently 381 responses:

*

*57% vote "Yes" (to remove the underscores)

*38% vote "No" (to retain underscores)

*4%  vote "No opinion"

A: From zf2 coding standard
Functions and Methods
Function names MUST contain only alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
...
For methods on objects that are declared with the "private" or "protected" modifier, the first character of the method name MAY be an underscore. This is the only acceptable application of an underscore in a method name, and is discouraged (as it makes refactoring to public visibility more difficult). Methods declared "public" SHOULD NOT contain an underscore.
http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards

A: Yes, and why shouldn't they? It's a convention to do so.

A: This is a convention in other object-oriented languages too.
Check out these two code convention guidelines:

*

*http://www.liferay.com/community/wiki/-/wiki/Main/Development+Style

*http://geosoft.no/development/javastyle.html
But all and all this should be a team convention, which is probably how it is for Zend. I believe these code conventions should be used for clarification and consistency when you write code. For me, the Zend use of underscore prefix for private members is a great time saver, especially when I'm not very familiar with a class.

A: I was recently wondering about this question and did a search through the entire ZendFramework-2.1.4 source tree to get a definitive answer. The underscore convention appears to no longer be in use for variables. There is not even one private or protected variable declaration in the entire project that begins with a single underscore.  There are a small number of variables in the following three files that begin with two underscores but that's it.
\ZendFramework-2.1.4\library\Zend\View\Renderer\PhpRenderer.php
\ZendFramework-2.1.4\library\Zend\View\Renderer\ConsoleRenderer.php
\ZendFramework-2.1.4\library\Zend\Stdlib\AbstractOptions.php
At least one of these files contains the following comment:
Note: all private variables in this class are prefixed with "__". This is to
 * mark them as part of the internal implementation, and thus prevent conflict
 * with variables injected into the renderer.
Regarding methods I was able to find three files that use "private function _" and 89 files that use "protected function _" to declare methods. There were also three files using "private static function _" and seven files using "protected static function _". These are a very small minority of the total number of method declarations in the project.
It would appear that this convention is dead or dying within Zend Framework 2.
EDIT: It looks like these two sections of the ZF2 codign standards state this clearly.
http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards#CodingStandards-Variables
http://framework.zend.com/wiki/display/ZFDEV2/Coding+Standards#CodingStandards-FunctionsandMethods
Variables
Variable names MUST contain only alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged in most cases.
For variables that are declared with private or protected visibility, the first character of the variable name MAY be a single underscore. This is the only acceptable application of an underscore in a variable name, and is discouraged (as it makes refactoring to public visibility more difficult).
Functions and Methods
Function names MUST contain only alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
Function names MUST always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word MUST be capitalized. This is commonly called "camelCase" formatting.


text:
Q: Python / Tkinter listbox troubles I posted a question here and I was advised to restructure the code. It's now different enough that I feel it justifies asking a new question.
Anyway, I'm trying to add drag/drop functionality to a listbox, but I figured a good first step would be to get the event binding working in the first place. Currently, when I click on the list I get the following error upon clicking the listbox. The listbox window appears, but when I click it the error occurs.
 "AttributeError: make_list instance has no attribute 'nearest'.

Also, when I print listbox in the build_listbox method, the following decimal is printed .40720520L. Shouldn't this print the values in the listbox? Afterall, it's in the same method. Is the listbox not being created properly?
from Tkinter import *
import Tkinter

class make_list:

    def move_mouse(self, event):
        self.curIndex = event.nearest(event.y)
        print self.curIndex

    def click_button(self, event):
        w= event.widget
        self.curIndex = int(w.curselection()[0])
        #print self.curIndex
        value = w.get(self.curIndex)
        print value

    def build_main_window(self):
        self.build_listbox()

    def build_listbox(self):
        listbox = Listbox()
        listbox.bind('<<ListboxSelect>>', self.click_button)
        listbox.bind('<B1-Motion>', self.move_mouse)
        for item in ["one", "two", "three", "four"]:
            listbox.insert(END, item)
        listbox.insert(END, "a list entry")
        listbox.pack()
        print listbox
        return

if __name__ == '__main__':
    start = make_list()
    start.build_main_window()
    mainloop()

A: The value you get when you do a print on a Tkinter widget is largely irrelevant to the user, it is merely the name of a Tcl variable that was created for you.
Now, since apparently your code is working (by quickly going through the comments in the question), I would suggest doing the drag & drop functionality in a different manner. For instance, if we had a list of values that was associated to the values in the Listbox, then it would be much easier to do the task if we could update this list and then it would reflect upon the Listbox display, right ? Too bad we don't have such thing in Python, but for the moment consider the following code:
import Tkinter

def list_click(event):
    w = event.widget
    index = w.nearest(event.y)
    w._selection = index

def list_motion(event):
    w = event.widget
    if w._selection is None:
        return
    index = w.curselection()[0]
    w._var.swap(index, w._selection)
    w._selection = index

def list_clear(event):
    event.widget._selection = None

root = Tkinter.Tk()

v = ListVar(values=('one', 'two', 'three', 'four'))
v.append('a list entry')

listbox = Tkinter.Listbox(listvar=v)
listbox.pack()

listbox._selection = None
listbox._var = v
listbox.bind('<1>', list_click)
listbox.bind('<B1-Motion>', list_motion)
listbox.bind('<ButtonRelease-1>', list_clear)

root.mainloop()

This code works in the following manner: when a mouse click happens in the listbox it marks the nearest item as "selected", when you move the mouse it swaps the items and update the selection, when you release the mouse button it clears the selection. What is missing is this ListVar thing then. Here it is:
class ListVar(Tkinter.Variable):
    def __init__(self, master=None, name=None, **kwargs):
        Tkinter.Variable.__init__(self, master, kwargs.get('values'), name)

    def set(self, values):
        self._tk.call('set', self._name, values)

    def set_index(self, index, value):
        self._tk.call('lset', self._name, index, value)

    def get_index(self, index):
        return self._tk.eval('lindex $%s %d' % (self._name, index))

    def get(self, start=None, end=None):
        if start is None and end is None:
            res = self._tk.eval('lrange $%s 0 end' % self._name)
        elif end is None:
            res = self._tk.eval('lrange $%s %d end' % (self._name, start))
        else:
            res = self._tk.eval('lrange $%s %d %d' % (self._name, start, end))
        return self._tk.splitlist(res)

    def swap(self, a, b):
        if a != b:
            tmp = self.get_index(a)
            self.set_index(a, self.get_index(b))
            self.set_index(b, tmp)

    def append(self, value):
        self._tk.eval('lappend %s {%s}' % (self._name, value))

It is very rough, will fail if you pass a value like "hello{", etc. This can be improved in many ways.


text:
Q: CREATE TABLE permission denied in Azure database 'master' NOTE: I can delete the database and can create a table through the shell but when I run a query in my Android Studio to create a table it through permission denied error.
Connection can successfully establish to the database.
I am using Stander S0 tier of Microsoft Azure(Free trail)
Here is my Code:
public class MainActivity extends AppCompatActivity {
Button add;
TextView errorlbl;
EditText name, address, pincode;
Connection connect;
Context context;
PreparedStatement preparedStatement;
Statement st;
String ipaddress, db, username, password;

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

    setContentView(R.layout.activity_main);
    add = (Button) findViewById(R.id.btnadd);
    errorlbl = (TextView) findViewById(R.id.lblerror);
    name = (EditText) findViewById(R.id.txtname);
    address = (EditText) findViewById(R.id.txtaddress);
    pincode = (EditText) findViewById(R.id.txtpincode);

    connect = ConnectionHelper();

    if (connect != null) {
        System.out.println ("Connet is NOT NULL");

        // Drop previous table of same name if one exists.
        Statement statement = null;
        try {
            statement = connect.createStatement ();
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        try {
            statement.execute ("DROP TABLE IF EXISTS studentRecord;");
            System.out.println ("Finished dropping table (if existed).");
        } catch (SQLException e) {
            e.printStackTrace ();
        }
        // Create table.
        try {
            statement.execute ("CREATE TABLE studentRecord (Name VARCHAR(50), Address VARCHAR(50), Pincode INTEGER PRIMARY KEY);");
            System.out.println ("Created table.");
        } catch (SQLException e) {
            Log.e ("Database not created", e.getMessage ());
            e.printStackTrace ();
        }
    }
    else {
        System.out.println ("Connet is NULL");
    }

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                st = connect.createStatement();
                preparedStatement = connect
                        .prepareStatement("insert into studentRecord (Name,Address,Pincode) values ('"
                                + name.getText().toString()
                                + "','"
                                + address.getText().toString()
                                + "','"
                                + pincode.getText().toString() + "')");
                preparedStatement.executeUpdate();
                errorlbl.setText("Data Added successfully");
            } catch (SQLException e) {
                errorlbl.setText(e.getMessage().toString());
            }
        }
    });

}

@SuppressLint("NewApi")
public Connection ConnectionHelper(){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll ()
            .build();
    StrictMode.setThreadPolicy(policy);

    Connection connection = null;
    String ConnectionURL = null;
    try {
        Class.forName ("net.sourceforge.jtds.jdbc.Driver");
        ConnectionURL = "jdbc:jtds:sqlserver://andridserver.... this link work fine";

        connection = DriverManager.getConnection (ConnectionURL);

        System.out.println ("Connection successful");

    }
    catch (SQLException se){
        Log.e ("error 1: ", se.getMessage ());

    }
    catch (ClassNotFoundException cne){
        Log.e ("error 2 :", cne.getMessage ());
    }

    catch (Exception e){
        Log.e ("error 3 :", e.getMessage ());
    }
    return connection;
}

}


text:
Q: Deno: request getting called twice import { serve } from "https://deno.land/std@0.50.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
// listing to  requests
for await (const req of s) {
    const res = await fetch('https://api.github.com/users')
    let data = await res.json()
    console.log('test- call')
    req.respond({ body:JSON.stringify(data)});
}

In the above code, when I try hitting http://localhost:8000/, I could see the console logging twice 'test- call'.
Not sure why is this happening. Help required to understand.

A: Your code is actually running fine.
If you try to access http://localhost:8000 with a browser, this is the output:
$ open web browser http://localhost:8000
test- call GET /
test- call GET /favicon.ico <- extra

However, if you access it with curl then you will see only one output as expected:
$ curl localhost:8000
test- call GET /

To see the extra request, log request details:
console.log('test- call', req.method, req.url)

Hope it helps!


text:
Q: Copy cells from excel sheet and paste it to a DB query Sikuli I am new to Sikuli. I need to copy data from excel sheets and paste them to a DB query using sikuli script. And how can I iterate among the excel cells to copy and paste the data repeatedly.

These data needs to copied and pasted one after the other.

A: It might be easier to copy all of the cells at once, then paste them one by one.
once Sikuli has opened Excel, you could do something like:
type(Key.HOME, KeyModifier.CTRL) #takes you to cell A1
type("a", KeyModifier.CTRL) #select all
type("c", KeyModifier.CTRL) #copy to clipboard
fromExcel = Env.GetClipboard().strip() #get clipboard contents into Sikuli, without leading or trailing white space
cells = fromExcel.split("/n") #split each cell into list on newline

#go to the destination app, maybe using App.open("nameOfYourApp") if it's not open yet, or App.focus("nameOfYourApp") if it is already open

for cell in cells: #use python to iterate through your list
    #navigate to the line or cell where you want to paste
    paste(cell)

Would something like that be of help?

A: Rather than providing a specific approach let's understand the options you have.

*

*Simulate user keyboard actions (like it is described here by @autoKarma).

*Excel sheet having a very specific structure allows you to detect some key points like first column and first row and then calculate other cells locations based on them.

*You can try and use one of the Python Excel API libraries to access the excel sheet directly via API. If you only need to read the document and to to amend it, I believe this will be fairly easy to do.

Note: In all cases you will obviously have to think of how do you bring yourself to the point where you have an open Excel sheet on your screen and how to dispose of it when done.


text:
Q: String copy error in C I don't understand why str1 is changing here. Please help.
#include<stdio.h>
#include<string.h>
int main (){
    char str1[]="stackoverflowwwwwww";//str1
    char str2[] = "stackoverflow";
    char str3[40];
    char str4[40];
    char str5[] = "asdfgh";
    strcpy(str2, str1);
    strcpy(str3, "successful");
    strcpy(str4, str5);
    printf("str1: %s\nstr2: %s\nstr3:%s\nstr4:%s\n", str1, str2, str3, str4);
    return 0;
}

output is:
str1: www
str2: stackoverflowwwwwww
str3: successful
str4: asdfgh

Why is str1 changing here?

A: Your program contains a buffer overflow. str2 is a buffer, its size is 14bytes (the length of "stackoverflow" + the terminating NULL character). When you execute strcpy(str2, str1) you are overflowing that buffer since str1 is longer than 14bytes. strcpy has no way of knowing the size of the buffer, so (by its definition) it blindly copies from one buffer to the other.
 Buffer overflow on the stack
Now, why does this alter str1? Well, because when strcpy copies more chars than the destination buffer's size, these chars must go somewhere.
Since both str2 and str1 are allocated on the stack, they are placed right next to each other. So, when strcpy copies onto str2 and overflows its size, it will move on to whatever's next to it in the memory - in your case that's str1.
So, the last characters strcpy is copying - the last few characters in str1 - are copied back onto the beginning of str1.

A: First of all, the destination str2 is shorter than string length str1 therefore this is an undefined behaviour.
But to understand why this happens, consider the following.
When I print out the memory addresses of the string, before any modification of your code in my system it is like this.
printf("str1: %p (%d)  \nstr2: %p (%d)\n", str1, strlen (str1),  str2, strlen (str2));

str1: 0x7ffd394e85d0 (19)
str2: 0x7ffd394e85c2 (13)
str1: wwwww
str2: stackoverflowwwwwww
str3:successful
str4:asdfgh

Note the address of str1 and str2. str2 starts first (lower address) and 0x7ffd394e85d0 - 0x7ffd394e85c2 = e, which is 13 in decimal, the exact length of the string.
Therefore the initial layout is
Initial layout
0x7ffd394e85c2               0x7ffd394e85d0
str2                         str1
|                            |
|                            |
V                            V
s t a c k o v e r f l o w \0 s t a c k o v e r f l o w w w w w w w \0

When the string is being copied from str1 to str2, strcpy will align and copy strings as follows. Here the end of str2 buffer gets violated.
When being copied
0x7ffd394e85c2               0x7ffd394e85d0
str2                         str1
|                            |
|                            |
V                            V
s t a c k o v e r f l o w \0 s t a c k o v e r f l o w w w w w w w \0
s t a c k o v e r f l o w w  w w w w w \0

After copy the state is as follows
After copy
0x7ffd394e85c2              0x7ffd394e85d0
str2                        str1
|                           |
|                           |
V                           V
s t a c k o v e r f l o w w w w w w w \0 v e r f l o w w w w w w w \0

Now str1 points to the beginning of the buffer starting with a 'w' and it has five consecutive 'w's until it reaches '\0'. Therefore the C string pointed by str1 now is "wwwww", as you see in your output.
Note that this is for my system where I get five consecutive 'w's. In other systems, the compiler may generate code which has a few blank bytes between the end of str2 and the beginning of str1, therefore they can have a varying number of 'w's. Also, note that, as this is an undefined behaviour, and the storage layout of the two strings are not defined, the output can be anything.

A: The result of this program is unknown, maybe various,because:
str3 and str4 are used without initialized, you had better initialize like this:
char str3[40] = {0};
char str4[40] = {0};

So, the borders which obey the size 40 will be under control of a programmer.
Obviously, the space of str2 cause problems if execute 'strcpy(str2, str1);'


text:
Q: catch never outputs the console even though I know it's failing I have my mongodb service stopped, so I know that my front end is not connected to my DB. I am using react and express.
Upon my app starting, I want to indicate that to the user somehow the server is offline so I figured if my original get call for users fails, then the server is offline.
I'm doing a simple call:
componentDidMount () {
        axios.get ('/api/users')
        .then ((res) => this.setState(
            { users : res.data }
        ))
        .catch ((error) => {
            //console.error(error);
            console.log('error found : offline');
        });
    }

But nothing happens in situation. I never get the catch call for the console. Am I going about this wrong? I'm new to backend so this is all a learning experience for me.
I was going to set a failed flag and then render a display error for the user and then retry the connection every 1500ms or something (is that bad programming?).