text:
Q: C# - Multi-touch help? USB web cam input? Image Analysis? I am trying to make a DIY touchscreen and would like to enter it into the local science fair but wanted to do it on the programing aspect of Multi-touch. My problem lies in that i have never worked with analyzing images (from a USB based web-cam).
 I would like to do this project in C# if possible (C++ - if worst comes to worst)
 I need to analyze a black picture (from a USB web-cam) and then detect when white blotches come into view. How would i go about doing this? --- is there a known method for detecting the change vs analyzing every pxl? if so a pointer to where this is would be nice :)
 Also how would i get the input from the Web-Cam via USB? --- where can i get the libraries / ddl's ?
I have seen some programs that work with this but they convert the images - which takes up time and processor speed... is there a way to use the raw imput image/data?
 HELP?

A: Once you have your input you will have (assuming it is perfectly dark and perfectly bright contrast) you will have an matrix of values similar to this: (gray scale)
0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 256 0 0 0 0 0
0 0 0 0 0 256 256 256 0 0 0 0
0 0 0 0 0 0 256 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0

Your job would need to be to segment out the section of the right color values (256) and to determine position. To get movement [assuming you are only tracking 1 object] you would have to compare the next position of the blob with the previous.
In the realworld, especially with a webcam you will never get a solid dark background with a good contrast. The webcam is low resolution, the light is never perfect, and noise is added in from the lense and CCD defects/color approximation.
Additionally, you may run into problems with tracking the blobs movement (a blob may be misdectected elsewhere on the surface. When you attempt to track two blobs you will run into more issues.
Some of these issues include:

*

*Blob collision (how do you know which blob goes where)

*Blob cross overs  (did the blobs switch sides, or did the blobs move in a reverse direction from previous travel)

*Blob combining (where two blobs become one)

To grab the camera using C# you may want to check this out. WIA is not the quickest method to use to take pictures. However, it is a lot easier to deal with. My suggestion to you if you are still interested in doing this is to draw two images in photoshop and track the markers.  Its not as exciting, but it will help you tackle the problem easier and relax the problem description.

A: What you want is "blob-detection". Here is a good thread about a blob library
There is a heap of multi-touch/computer vision libraries and software out there already. The best resource for this kind thing is wiki.nuigroup.com. Especially the Frameworks and Libraries section. Currently there is not to much C# info there, but if you do find out  something, make sure you put it on that wiki for everyone.
There is also the NuiGroup forum C# (.NET/Silverlight/WPF) section that should help you out a lot. There are some great help to be given in that community.

A: As a place to start wit the web cam, I would start here:
http://www.hanselman.com/blog/CapturingVideoAWebCameraUsingWIANotPossible.aspx
You'll have a few links to follow, but I'm suggesting you start here because this is the article where Scott talks about different challenges and common questions and provides links to more info.

A: To get images from the webcam the AForge framework is dead easy to use! Check out the motion detection sample app for code harvesting purposes :)


text:
Q: Unicode encode error in python 2.7 for Google Cloud project in Windows 10 I have an API in Python, there are no errors if it runs in Mac, only happens with Windows 10, I am using Python 2.7.
I would not like to modify it since the project is working well on PROD and in mac locally but I would like to make it work on my Windows machine.
The error comes from other libraries not from my code, the project is working well except in Windows.
E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\pkg_resources\__init__.py:2689: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   if item == nloc: E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\pkg_resources\__init__.py:2695: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal   elif item
== bdir and self.precedence == EGG_DIST: Traceback (most recent call last):   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\dev_appserver.py", line 14, in <module>
    from bootstrapping import bootstrapping   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\bootstrapping\bootstrapping.py", line 39, in <module>
    from googlecloudsdk.core import config   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\core\config.py", line 33, in <module>
    from oauth2client import client   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\oauth2client\client.py", line 52, in <module>
    from oauth2client import crypt   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\oauth2client\crypt.py", line 56, in <module>
    from oauth2client import _pycrypto_crypt   File "E:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\third_party\oauth2client\_pycrypto_crypt.py", line 17, in <module>
    from Crypto.PublicKey import RSA   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\PublicKey\RSA.py", line 78, in <module>   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\Random\__init__.py", line 28, in <module>   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\__init__.py", line 34, in <module>   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\nt.py", line 28, in <module>   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\winrandom.py", line 7, in <module>   File "e:\temp\easy_install-38xi7l\pycrypto-2.6.1-py2.7-win-amd64.egg.tmp\Crypto\Random\OSRNG\winrandom.py", line 6, in __bootstrap__ UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 13: ordinal not in range(128)

A: You are mixing Unicode strings and bytestrings when checking for equality, which you can confirm by printing type(comparable 1) with type(comparable 2)  where comparable 1, comparable 2 are the ones you are comparing. This error occurs in Python 2.X when comparing a Unicode string to a byte string. Python 2.X attempts to implicitly convert the byte string to Unicode string using the default ascii codec. If that fails, due to the byte string containing non-ASCII bytes, that warning occurs.
There are 3 approaches by which you can try solving the issue :

*

*Decode your text data as early as possible, and only compare Unicode
objects. So decoding as UTF-8 first would resolve the warning.

You can set UTF-8 on Windows by running:
set PYTHONIOENCODING=UTF-8
Or, create an environment variable with the name 'PYTHONIOENCODING' and value 'UTF-8'
Or, $env:PYTHONIOENCODING='UTF-8' with Powershell

*Convert your code to Python 3 as suggested by John Hanley. Python
3.X reduces the confusion by not allowing non-ASCII characters in a Unicode string literal.

*You can also change your non-ASCII characters to ASCII characters,
that way Python 2.X will not fail when trying to convert byte
strings to Unicode using ascii codec.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting older packages from ppa Can I install an older version of a specific package from a ppa? Specifically, I want to get an older version of xserver-xorg-video-intel (and dependencies) from xorg-edgers ppa. The reason is that the older version seemed to work with my hardware. The present version seems to feature (I would like to found out if it is really the source) severe crashes as the present stable releases of this package do. I tried
apt-get install pkg=version

but didn't succeed. I am afraid that the packages in the cache are lost after
apt-get clean

I do not even know the precise version number of the previous version, assuming that it doesn't have to be exactly one less. The current version is xserver-xorg-video-intel-2.20.15
Alternatively: Is there a place, e.g. at launchpad, where I can manually download the previous version of the package?

A: Yes, you can install a specific version of a package with apt-get install pkg=version but the version you want needs to be available from one of your APT sources.
e.g.
$ apt-cache policy dpkg
dpkg:
  Installed: 1.16.12
  Candidate: 1.16.12
  Version table:
     1.17.1 0
        800 http://localhost:3142/debian/ unstable/main amd64 Packages
 *** 1.16.12 0
        900 http://localhost:3142/debian/ testing/main amd64 Packages
        100 /var/lib/dpkg/status

in this case, both 1.17.1 and 1.16.12 are available to APT. 1.16.12 is installed.
Like the main Ubuntu archive, PPAs remove superseded packages. So, only one version is available for each, Ubuntu release, in a PPA.

A: You can retrieve old versions of packages from the Ubuntu Archive, and from PPAs, but they are not available directly via apt. You have to follow the launchpad build links, look for 'Superseded' builds and you can download the .deb files. This is automated with 'pull-lp-debs', 'pull-ppa-debs', etc from the 'ubuntu-dev-tools' package.
Then you can use apt install ./deb1 ./deb2 ./deb3 etc.. you have to install all the matching debs at the same time. For a list of matching debs, install 'dctrl-status'


text:
Q: How can I use GROUP BY with AGGREGATED column values I'm learning SQL so I'm not sure about my question. I'm running the following query :
SELECT count(key), FORMAT_DATE("%Y-%m", DATE(min(created_date))) as First_Month
FROM `xxxxxxxx.xxxxxxx_xxxxx.xxxxxxxx` as table
GROUP BY First_Month
ORDER BY First_Month

Big query returns me this error :
Error: Column First_Month contains an aggregation function, which is not allowed in GROUP BY at [3:10]

Basically I have a table with a list of account and payment. What I want to do is counting the number of accounts at their first month. Which is I think what we called a cohort analysis... but again I'm not sure.
I feel like there is something more complex beyond my question but I'm not able to express...

A: Use a subquery.  Presumably you intend something like this:
SELECT count(*), FORMAT_DATE("%Y-%m", DATE(min_created_date)) as First_Month
FROM (SELECT t.key, min(created_date) as min_created_date
      FROM `xxxxxxxx.xxxxxxx_xxxxx.xxxxxxxx` t
      GROUP BY t.key
     ) t
GROUP BY First_Month
ORDER BY First_Month
LIMIT 1000;

You have a lot of history if you are expecting more than 1000 months of history.


text:
Q: JS - Assigning a variable while using a callback I'm relatively new to JS, and have been stuck on this problem for a while.  I am trying to assign a variable from the return value of a function, like this:
var data = makeApiRequest(url);

However, the code continues before the makeApiRequest() function completes, causing data to be undefined.
I've been researching the problem for a while and found that the problem can be fixed with a callback.  My issue is I'm not sure how to get data assigned to the result of makeApiRequest() in doing so.
I found this example (on callbackhell.com) that I think perfectly illustrates my problem:
var photo = downloadPhoto('http://coolcats.com/cat.gif')
// photo is 'undefined'!

Author's solution:
downloadPhoto('http://coolcats.com/cat.gif', handlePhoto)

function handlePhoto (error, photo) {
  if (error) console.error('Download error!', error)
  else console.log('Download finished', photo)
}

console.log('Download started')

The thing that I cannot figure out for the life of me is how photo is assigned (or even declared) in this example.  I feel like if I could crack that, I could figure out my specific problem.  Any help would be greatly appreciated.  Thanks very much in advance.

A: makeApiRequest(url) is an asynchronous call. That means that if you try to evaluate it immediately after calling it, it will be undefined. The modern solution is to use a Promise.
However, a callback function is perfectly acceptable if your logic won't go layers deep. You can do so by altering the parameters on your makeApiRequest function like so:
function makeApiRequest (url, callback) {
    // make the api call, and then:
    callback(results);
}

Now, you will call makeApiRequest() as such:
makeApiRequest (url, function(data) {
    // handle your data here.
    console.log(data);
});

A: When download function completes, it invokes callback function handlePhoto with data (photo) passed to it as a second argument, so that it can be used inside of the handlePhoto function.

A: If you want to assign the return value of a promise then you could wrap the variable inside async function and later use await.
** But async and await is a new feature and not widely supported.
So in your case assuming makeApiRequest() returns a promise
  async function any(){ /* using async before function declartion*/

    var getValue = await makeApiRequest(); // using await

    console.log(getValue); // returned value of makeApiRequest
  }


text:
Q: how to create an array for calculation in php? First, I have rating table in my database like this
=====================================
| id | userid | item_id    | rating |
=====================================
| 1  |   1    |     B      |   5    |
| 2  |   1    |     C      |   4    |
| 3  |   2    |     A      |   4    |
| 4  |   2    |     C      |   3    |
| 5  |   3    |     A      |   2    |
| 5  |   3    |     B      |   2    |
| 6  |   3    |     C      |   2    |
=====================================

Then I want to create an array from the table, and calculate the array. For more details, this is my code
<?php
include './connect.php';
$userid = $_SESSION['ids'];

$sql1 = "SELECT item_id, rating FROM rating WHERE userid='$userid' ";
$result1 = $conn->query($sql1);

$itemI = array();
$itemJ = array();
$items = array();

while($row1 = mysqli_fetch_assoc($result1)){
    $items[$row1["item_id"]] = $row1["item_id"];
    $itemI[$row1["item_id"]] = $row1["rating"];
    $itemJ[$row1["item_id"]] = $row1["rating"];

    $ditemI = $itemI[$row1["item_id"]];
    $ditemJ = $itemJ[$row1["item_id"]];
    $nume = 0;
    $den1 = 0;
    $den2 = 0;
    $rs = 0;

$sqlr = "SELECT AVG(rating) AS avgRatingUser FROM rating WHERE userid='$userid' ";
            $resultr = $conn->query($sqlr);
            $duser  = array();
            while($rowr = mysqli_fetch_assoc($resultr)){
                $duser[$u]["avgRatingUser"] = $rowr["avgRatingUser"];
                $duserU = $duser[$u]["avgRatingUser"];
            }

    for($i = 0; $i<count($itemI); $i++){
        for($j = $i+1; $j<count($itemI); $j++){

            $nume += (($itemI[$i] - $duser[$u]) * ($itemJ[$j] - $duser[$u]));
            $den1 += (pow(($itemI[$i] - $duser[$u]), 2));
            $den2 += (pow(($itemJ[$j] - $duser[$u]), 2));

        $squart = (sqrt($den1)) * (sqrt($den2));
        $rs += $nume/$squart;
    }
}
}

echo $nume. " ";
echo $den1. " ";
echo $den2. " ";
echo $squart. " ";
echo $rs. " ";

then my question is, why the result of the array calculation is not showing?
and where is the error of my code?

A: Your problem revolve around the fact that you use wrong index for both read and write.
In the first loop after SELECT-ing data, you add the following code (which is fine):
$items[$row1["item_id"]] = $row1["item_id"];
$itemI[$row1["item_id"]] = $row1["rating"];
$itemJ[$row1["item_id"]] = $row1["rating"];

And in the next codes, you read it like this (which also fine):
$nume += (($itemI[$i] - $duser[$u]) * ($itemJ[$j] - $duser[$u]));
$den1 += (pow(($itemI[$i] - $duser[$u]), 2));
$den2 += (pow(($itemJ[$j] - $duser[$u]), 2));

The problem is, from your table information, it is known that item_id is A, B, C, ... and you read the array in the later codes by using integer index taken from for loop code. You need to decide what kind of index you want to use for your array.


text:
Q: Why I need to specify permit again in the controller? I am writing an app which has a comment controller, inside the controller,
it has the strong parameter like
def comment_params
  params.require(:comment).permit(:text)
end

but I found I still need to add permit when I use
@comment = @post.comments.build(params[:comment].permit(:text)) in the create method or I will receive the error.
I would like to know the reason here. I am using Rails5.

A:
why I need to specific permit again in the controller?

Because you didn't use your comment_params.
@post.comments.build(comment_params)

There is no magic, you should use your method.
In this code you didn't use it:
@post.comments.build(params[:comment].permit(:text))


text:
Q: Does data save while trying Ubuntu 13.10 Booted through EFI on Macbook pro retina (late 2013) Im trying to make safe and secure bitcoin paper wallets and the only Ubuntu live cd that will work is the 13.10 version ( Ubuntu 12.04 wont boot at all matter what on my new MacBook Retina that has not been taken online yet ). Is "trying out" Ubuntu 13.10 on a USB drive through EFI as safe and secure as Ubuntu 12.04? Will it save my files/data at all? cause that's exactly what I wouldn't want.  My MacBook pro will only boot Ubuntu through "EFI" mode while holding ALT when starting up the laptop, There is 2 options, Windows, and EFI. When I click the Windows boot option it won't detect that there is Ubuntu on that USB so  Ubuntu  will only start up and work while booting through EFI. What's the difference with EFI btw? And when it loads up the screen, its so small that you can barely see your cursor. How do I fix the size of the screen layout as well??
Thanks,
 Sky

A: EFI is a way of booting operating systems, like BIOS. Generally speaking, Windows will boot using BIOS, while Mac and Linux will boot using EFI (or UEFI). I believe that you can now get Windows to boot using EFI as well though (and you can also boot Linux using BIOS), so it's not quite as simplistic as I'm suggesting.
If you can boot it with the "EFI" option but not the "Windows" option, just use the "EFI" option.
Regarding saving files, this will depend on what files you create and how. If you are using ubuntu's "Try it" option, then as long as you aren't saving the files to the physical drive, then you will be fine. As soon as you reboot the computer (or turn it off), those files will be gone.


text:
Q: KVM: guest with FQDN DNS resolution / no bridge I have a (Hetzner) server with a public IP of eg. 123.123.123.123, and an additional IP of eg. 456.456.456.456.
I want to serve some private webspace apps on 123.123.123.123, including a hidden master BIND server for some domains, and bridge a KVM guest to 456.456.456.456 for some publicly published webspace.
Is it possible to do that while also setting up a separate virtual network with libvirt that will resolve FQDNs to guests? These guests should be able to be accessed by, and access the internet, and should be able to have multiple FQDN's per guest, but will not have public IPs of their own. I see some documentation that states that adding 192.168.122.1 to /etc/resolv.conf on the host will allow connecting to guests via their hostname locally, and I see some information for libvirt regarding Addressing, here, but I'm ma bit lost. It seems as if this should be possible, but I'm missing something.
Do I just need to purchase IP space for every VM I want accessed by the internet, or is there a way to accomplish this?
TLDR Is it possible to set up a virtual network with libvirt that will resolve FQDNs to guests from the internet?

A: Short answer: this is not possible.
Better to use IPv6 addresses (which are in abundance) for any KVM that does not absolutely require the general public to access it. Any traffic that is server-to-server will work fine on IPv6, and anything such as private cloud services will work so long as your ISP offers IPv6, which most ( > 80% ) ISP's do, and you're client is configured to use it (which most are).
Therefore just use a network bridge with IPv6 on the KVM instances.
For the public facing requirements, set up a reverse proxy like Nginx (recommended), Pound, Squid as a reverse proxy, or Apache's mod_proxy on IPv4 and reverse proxy to the IPv6 instances from there.
There are other ways of achieving this, such as SIIT-DC, but I know little about that.


text:
Q: Compile Error "Expected:end of statement in vb6" When i define an initialize a variable i get the compile time error as "Expected:End of statement". The code is :
Dim i as integer=1

A: The VB6 compiler does not let you declare and initialise a variable in one line (like you can in VB.NET).
So you have to declare it on one line and initialise it on another:
Dim i As Integer
i = 1

If you want to have both statement on the same line you can use a colon:
Dim i As Integer : i = 1

But you can only do this inside a procedure and not in a module, form or class declaration

A: dim i as integer
i=1

You need to split declaring a variable and assigning its value.

A: You cannot assign a value to a variable you are declaring in VB6, UNLESS it is a constant
' BAD
Dim i as Integer = 1

' GOOD
Dim i As Integer
Const i As Integer = 1


text:
Q: Buenas practicas sobre uso de Include dentro de un While? Tengo una plantilla sobre caja para los productos, entonces estuve practicando en realizar un include de esa plantilla dentro de un While de la siguiente manera:
$stmt->bind_result($product);
while ($stmt->fetch()) {
    include 'template_box_product.php';
}

Entonces a esa plantilla ya le agrego las variables del bind_result:

<?php echo $product; ?>

$300$120,00

Esto funciono sin problemas, pero es una buena practica realizarlo de esta manera, me refiero en temas de tiempo de ejecución, rendimiento, ¿Qué otros aspectos se deben evaluar para tomar decisiones?
O se debe emplear de la manera más habitual/común:
while ($stmt->fetch()) {
echo '

'.$product.'

$300$120,00

';
}

A: Supongo que la idea de tener el contenido en un archivo para luego incluirlo es tener el código mejor organizado y/o poder reutilizar código, lo cual es una buena práctica.
Una forma de asegurar la separación de contenidos sería poner un return al archivo template_box_product.php y recuperarlo luego en una variable una sola vez, usando luego esa variable. Así evitarás un include dentro de un bucle, lo cual no es una buena idea, porque al fin y al cabo es código repetitivo.
En cuanto a los valores dinámicos, puedes poner marcadores y organizar la salida con printf().
Entonces, template_box_product.php quedaría así:
$html='

%s

$300$120,00

';

return $html;

Y, cuando quieras usarlo:
$html=include 'template_box_product.php';

$stmt->bind_result($product);
while ($stmt->fetch()) {
    printf($html,$producto);
}

Lo que ocurrirá aquí es que el marcador %s que pusimos aquí:
%s
 será sustituido por el valor de $producto en cada iteracción. Si necesitaras más valores, pones más marcadores y pasas los valores respectivos como parámetros. Aquí la s significa un marcador para un dato de tipo cadena (string), y hay otros tipos de marcadores según el tipo de dato, como podrás ver en el Manual de PHP.


text:
Q: Identify date range and merge into max and min dates I have data ( int, date , date types)
SELECT * FROM
(
  VALUES
     (1700171048,'2020-12-21','2021-01-03'),
     (1700171048,'2021-01-05','2021-01-12'),
     (1700171048,'2021-01-13','2021-01-17'),
     (1700171048,'2021-01-18','2021-01-19'),
     (1700171048,'2021-01-22','2021-01-27'),
     (1700171048,'2021-01-28','2021-02-17')

     (1700171049,'2020-12-21','2021-01-03'),
     (1700171049,'2021-01-04','2021-01-05'),
     (1700171049,'2021-01-06','2021-01-17'),
     (1700171049,'2021-01-18','2021-01-19'),
     (1700171049,'2021-01-20','2021-01-27'),
     (1700171049,'2021-01-28','2021-02-17')

 ) AS c (id1, st, endt )

I need output( i.e. if start and end dates are continuous then make it part of group )
 id1         st             endt
 1700171048 '2020-12-21' , '2021-01-03'
 1700171048 '2021-01-05' , '2021-01-19'
 1700171048 '2021-01-22' , '2021-02-17'

 1700171049 '2020-12-21' to '2021-02-17'

I tried this, won't work.
    select id, case when min(b.st) = max(b.endt) + 1 then min(b.st) end,
            case when min(b.endt) = min(b.st) + 1 then max(b.st) end
     from c a  join c b
   group by id

A: This is a type of gaps-and-islands problem.  Use lag() to identify if there is an overlap.  Then a cumulative sum of when there is no overlaps and aggregation:
select id1, min(st), max(endt)
from (select t.*,
             sum(case when prev_endt >= st + interval '-1 day' then 0 else 1 end) over (partition by id1 order by st) as grp
      from (select t.*,
                   lag(endt) over (partition by id1 order by st) as prev_endt
            from t
           ) t
     ) t
group by id1, grp;

Here is a db<>fiddle.


text:
Q: How to generate new sheet from find result? I would like to generate new sheet for all values contains "_S" :
Example:

When user click on "Generate page", two new sheet are created (one sheet with title "Folder22_S" and other one with title "Folder3_S"
In second time, i would like that new sheet generated from a model (not generate a empty sheet)
My question is: How to do this ? I doesn't know how to find all values contains "_S" and get cell value ( Folder22_S and Folder3_S) ?
My pseudo VBA code:
Sub generate()
    'Array contains all values *_S'
    Dim AllValuesContains_S As Variant
    AllValuesContains_S = Array("Folder22_S", "Folder3_S", ...)
    For Each item As String In AllValuesContains_S
      Sheets.Add.Name = item
    Next
End Sub

A: I will assume the range you want to search is A2:C7. Adjust that portion of the code to be whatever range you need.
Sub New_Wksht()
Dim SearchRange as Range, c as Range
Dim sht as Worksheet
With ThiwWorkbook
   Set SearchRange = .Sheets("Your Sheet Name").Range("A2:C7") 'Change sheet name and range to be what you need
   For Each c in SearchRange
      If Right(c.Value,2) = "_S" Then
         Set sht = .Sheets.Add
         sht.Name = c.Value
      End If
   Next C
End With
End Sub


text:
Q: Geopandas overlay issue I am trying to get an overlay (intersection) of two collections of polygons
in geopandas:
splits = gp.overlay(nhds, cts, how='intersection')
but result is very weired (see the picture below).
I opened an issue on geopandas github, but wondered if someone saw similar behavior or can detect what is going on (I am inclined to blame spatial index) here from the image

A: Issie disappeared after
- rebooting geopandas and installing "clean" gdal version
- replacing geojson census_tract dataset with the shapefile - probably, there was an issue with the geometry


text:
Q: tikz: `! Package PGF Math Error: Unknown function` in for loop but works outside of loop I am working on drawing a triangle and some vectors using tikz and tikz-euclid.
I want to draw each edge of my triangle as a vector, with length equal to the length of the edge, located at the midpoint, O, and perpendicular to the relevant edge. Almost like what I have sketched so far, but instead of intersecting the midpoints, the vectors should be perpendicular.
I'm trying to get my head around tikz syntax here, and had tikz-euclid suggested to me from a previous question. Because I am drawing more than one vector I would like to put the draw functions in a loop, like so:
% 1. Coordinates of the line segment midpoints, E,F,G
% 2. get lengths of vectors A, B, C (as, dA, dB, dC)
% 3. draw the vectors from O passing through relevant midpoint
\foreach \mid/\tip/\tail/\vector in {E/P/Q/A, F/Q/R/B, G/R/P/C}{
    \coordinate (\mid) at ($(\tip)!0.5!(\tail)$);

    % Calculate length of segments and label as dA, dB, dC
    \tkzCalcLength(\tip,\tail)\tkzGetLength{d\vector}

    %THIS throws an error:
    %> ! Package PGF Math Error: Unknown function `dApt' (in 'dApt').
    \draw[->] (O)--++ ($(O)!d\vector pt!(\mid)-(O)$);
}

But this has thrown an error:
! Package PGF Math Error: Unknown function 'dApt' (in 'dApt')
However, re-writting the code just after the loop:
\draw[->] (O)--++ ($(O)!\dA pt!(E)-(O)$);
\draw[->] (O)--++ ($(O)!\dB pt!(F)-(O)$);
\draw[->] (O)--++ ($(O)!\dC pt!(G)-(O)$);

Produces what I want. Is there a way to re-write this so that it works within the \foreach loop? I figure there is some escape sequencing or something messing with the line in the loop. But I can't figure out how to get it right. Any ideas?
For reference the code I have generates something that looks like this, and for the moment if I get something that looks like this out but done in a loop I will be happy.

\documentclass[border=20pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{intersections, calc,through,backgrounds}
\usepackage{tkz-euclide}

\begin{document}

    \begin{tikzpicture}[scale=3]

        % Coordinates for a triangle
        \coordinate (P) at ($(0,0) + (rand,rand)$);
        \coordinate (Q) at ($(2,-2) + .5*(rand, rand)$);
        \coordinate (R) at ($(-2, -2) + .5*(rand, rand)$);
        \coordinate (O) at (barycentric cs:P=1,Q=1,R=1) ;

        % 1. Coordinates of the line segment midpoints, E,F,G
        % 2. get lengths of vectors A, B, C (as, dA, dB, dC)
        % 3. draw the vectors from O passing through relevant midpoint
        \foreach \mid/\tip/\tail/\vector in {E/P/Q/A, F/Q/R/B, G/R/P/C}{
            \coordinate (\mid) at ($(\tip)!0.5!(\tail)$);

           % Calculate length of segments and label as dA, dB, dC
            \tkzCalcLength(\tip,\tail)\tkzGetLength{d\vector}

            %THIS throws an error:
            %> ! Package PGF Math Error: Unknown function `dApt' (in 'dApt').
            %\draw[->] (O)--++ ($(O)!d\vector pt!(\mid)-(O)$);
        }

        % This works
        % Draw the vectors A,B,C from O, passing through E,F,G respectivley
        \draw[->] (O)--++ ($(O)!\dA pt!(E)-(O)$);
        \draw[->] (O)--++ ($(O)!\dB pt!(F)-(O)$);
        \draw[->] (O)--++ ($(O)!\dC pt!(G)-(O)$);

        \draw [thin] (P) -- node[midway,sloped] {$||$}(Q) --node[midway,sloped] {$||$} (R) --node[midway,sloped] {$||$} cycle;

        \tkzDrawPoints(P,Q,R,O)

        % Labels
        \node at (O) [left=2pt]{$O$};
        \node at (P) [above right]{$P$};
        \node at (Q) [right=2pt]{$Q$};
        \node at (R) [left=2pt]{$R$};

        % midpoints
        \begin{scope}[black!40]
        \node at (E) [below left=.5em]{$E$};
        \node at (F) [below=.5em]{$F$};
        \node at (G) [below right=.5em]{$G$};
        \end{scope}

    \end{tikzpicture}
\end{document}

A: Turns out tikz-euclid was getting in the way.
This answer by @Sandy G earlier put me on the path to the right solution.
replacing the tkz-euclid code with
\draw[->, blue] let
                \p1 = ($(\tip)-(\tail)$)
            in
                (O)--++($(O)!sqrt(\x1*\x1+\y1*\y1)!(\mid)-(O)$);

allowed me to put the draw command in a loop without too much of a hassle.
Thus my code became the following, which produced this picture.

\documentclass[border=20pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{intersections, calc,through,backgrounds}

\begin{document}

    \begin{tikzpicture}[scale=3]

        % Coordinates for a triangle
        \coordinate (P) at ($(0,0) + (rand,rand)$);
        \coordinate (Q) at ($(2,-2) + .5*(rand, rand)$);
        \coordinate (R) at ($(-2, -2) + .5*(rand, rand)$);
        \coordinate (O) at (barycentric cs:P=1,Q=1,R=1) ;

        % 1. Coordinates of the line segment midpoints, E,F,G
        % 2. draw the vectors from O passing through relevant midpoint
        \foreach \mid/\tip/\tail/\vector in {E/P/Q/A, F/Q/R/B, G/R/P/C}{
            \coordinate (\mid) at ($(\tip)!0.5!(\tail)$);

            \draw[->, blue] let
                \p1 = ($(\tip)-(\tail)$)
            in
                (O)--++($(O)!sqrt(\x1*\x1+\y1*\y1)!(\mid)-(O)$);
        }

        % Draw triangle, and midpoint markers
        \draw [thin] (P) -- node[midway,sloped] {$||$}(Q) --node[midway,sloped] {$||$} (R) --node[midway,sloped] {$||$} cycle;

        % Labels: verticies
        \node at (O) [left=2pt]{$O$};
        \node at (P) [above right]{$P$};
        \node at (Q) [right=2pt]{$Q$};
        \node at (R) [left=2pt]{$R$};

        % Labels: midpoints
        \begin{scope}[black!40]
        \node at (E) [below left=.5em]{$E$};
        \node at (F) [below=.5em]{$F$};
        \node at (G) [below right=.5em]{$G$};
        \end{scope}

    \end{tikzpicture}
\end{document}

A: One way of solving your issue is to ask less. Especially store the result in your foreach loop into a simple variable (here, I used \len).
Now, if you want to reuse these length, you can still write what you did in the first place, but it won't work into your loop (and I currently don't know why, maybe Alain Matthes would know, as the package creator).
\documentclass[border=20pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{intersections, calc,through,backgrounds}
\usepackage{tkz-euclide}

\begin{document}

    \begin{tikzpicture}[scale=3]

        % Coordinates for a triangle
        \coordinate (P) at ($(0,0) + (rand,rand)$);
        \coordinate (Q) at ($(2,-2) + .5*(rand, rand)$);
        \coordinate (R) at ($(-2, -2) + .5*(rand, rand)$);
        \coordinate (O) at (barycentric cs:P=1,Q=1,R=1) ;

        % 1. Coordinates of the line segment midpoints, E,F,G
        % 2. get lengths of vectors A, B, C (as, dA, dB, dC)
        % 3. draw the vectors from O passing through relevant midpoint
        \foreach [count=\i] \mid/\tip/\tail/\v in {E/P/Q/A, F/Q/R/B, G/R/P/C}{
            \coordinate (\mid) at ($(\tip)!0.5!(\tail)$);

           % Calculate length of segments and label as dA, dB, dC (NOT)

            \tkzCalcLength(\tip,\tail)\tkzGetLength{len}    % PROBLEM SOLVED
            \draw[->] (O)--++ ($(O)!\len pt!(\mid)-(O)$);   % PROBLEM SOLVED
        }

        \draw [thin] (P) -- node[midway,sloped] {$||$}(Q) --node[midway,sloped] {$||$} (R) --node[midway,sloped] {$||$} cycle;

        \tkzDrawPoints(P,Q,R,O)

        % Labels
        \node at (O) [left=2pt]{$O$};
        \node at (P) [above right]{$P$};
        \node at (Q) [right=2pt]{$Q$};
        \node at (R) [left=2pt]{$R$};

        % midpoints
        \begin{scope}[black!40]
        \node at (E) [below left=.5em]{$E$};
        \node at (F) [below=.5em]{$F$};
        \node at (G) [below right=.5em]{$G$};
        \end{scope}

    \end{tikzpicture}
\end{document}


text:
Q: define variable index im in the medal of coding and i reached the point where i have something like this,

the problem is i have up to 35 terms and all should be index in order to preform summation to count all possibilities, is there any automatic way to generate as variable index as much as i want ? also is there any way to fill all the summations automatically ?
thanks

A: You could use $ii[1]$, $ii[2]$, $ii[3]$ etc instead of $ii$, $kk$, $ll$:
expr = Product[Indexed[u, ii[i]][t], {i, 3}];

Sum[expr, ##] & @@ Array[{ii[#], jj} &, 3]

A: If you really have that simple structure, exploit it:
Clear[u]
jj = 4;
Times @@ (Total /@ Array[u, {3, jj}])


text:
Q: Robô para informações Bom dia, Tarde , Noite.
gostaria de sabe se tem como criar um robô onde ele pega alguns preços de produto, e joga essa informação em um app.
estou com uma ideia para um app e sou iniciante ainda estou fazendo logica de programação e depois vou fazer java script

A: Creio que você quiz fazer referência ao Robo no caso de "algo que torne seu aplicativo capaz de consumir dados de Preços de algum lugar", no caso consumir dados de um banco de dados de preços por exemplo, ou consumir dados de uma API ok ("Application Programming Interface").
Na verdade existem diversas formas de entender sua dúvida, como você falou em Javascript seria interessante abrir uma ideia para você consumir estes dados via "Ajax" por exemplo, onde através da sua programação em Jscript você irá direcionar uma requisição de "GET" para seu aplicativo Web consumir seus dados de Preços, por exemplo por uma API retornando estes dados em formato JSON (JavaScript Object Notation). Então estes dados estariam dispostos em uma URL por exemplo: http://xxxx_precos_de_produtos , onde estariam num formato tipo assim: { "_idproduto" : "001", "nome_produto":"chuteira", "preco_produto":"150,00"}.
Como falei acima existem outras formas de consumir dados, através de consultas diretamente ao banco de dados via querys e SQL (Structured Query Language), por exemplo, utilizando linguagens como PHP, Java, Python, etc.
Veja que há muitos caminhos e formas de se consumir dados! Tentei elucidar sua dúvida de uma forma simples, já que está iniciando e todo inicio é realmente confuso, mas continue em frente, estude, busque informação e tenha sucesso! Abraço.


text:
Q: How to make an AddComponent like the Unity system? So, I kind of trying to make my own implementation of AddComponent in Unity but for SDL2-CS, I did most of the things except adding the component.
I would store the components in a list like this
private List<Component> components = new List<Component>();
public T AddComponent<T>()
{
    if(typeof(T) == typeof(Component)){
        Component component = (Component)Convert.ChangeType(typeof(T), typeof(Component));
        components.Add(component);
        return (T)component;
    }
    return default(T);
}

Although, this obviously doesn't work since I can't just convert component into T but I can't find anymore documentation for it.
I tried compiling it and, this is the error.
Cannot convert type 'SDL2.Component' to 'T'

Does anyone have any workaround for this thing?
Also, everything that will be sent to the AddComponent will be inheriting Component.
EDIT:
Now I kind of found a way! Thanks to Fabjan for the recommendation.
private List<Component> components = new List<Component>();
public T AddComponent<T>()
{
    var instance = Activator.CreateInstance(typeof(T));
    var component = (Component)instance;
    components.Add(component);
    return (T)instance;
}

A: Convert.ChangeType is not meant to create new objects, use Activator.CreateInstance instead.

A runtime approach can verify inheritance at runtime:
public T AddComponent<T>()
{
    if(typeof(Component).IsAssignableFrom(typeof(T))){
        var component = Activator.CreateInstance(typeof(T));
        components.Add(component as Component);
        return component;
    }
    return default(T);
}

But you can have a better approach which makes the test at compile time:
public T AddComponent<T>() where T : Component
{
    var component = Activator.CreateInstance(typeof(T));
    components.Add(component);
    return component;
}


text:
Q: Citation: Sample mean as consistent and unbiased estimator of the expected value A reviewer asked for a citation that the sample mean is a consistent and unbiased estimator of the expected value and therefore converges towards the expected value. I know I can easily do the calculations myself based on the variance of the sample mean etc. However, since the reviewer specifically asked for a citation, I am not sure a proof instead would be acceptable. Also, I don't like adding proofs that have almost nothing to do with the actual subject of the article.
In most books I looked at, this fact is either only provided for the normal distribution (i.e. sample mean is an estimator of the parameter $\mu$), or included as an exercise.
Is anybody aware of a citation that I could use to support the claim that the sample mean is an unbiased estimator for any distribution (assuming of course expected value exists and variance is finite).

A: Unbiasedness: Casella and Berger, Statistical Inference, 2nd Ed., Theorem 5.2.6 p213-214
Consistency: Casella and Berger, Statistical Inference, 2nd Ed., Example 10.1.2 et seq., p468-469


text:
Q: java to matlab conversion I am a newbie at matlab . As a part of a larger problem, I need to find maximum number of occurrences of a string in an array of Strings.
Since I have some experience in java I have written the partial code in java ( only until the number of occurences of the string within the string array can be computed I can sort the hashmap depending on the values and extract this)
int incr = 0;
    String[] c = { "c1", "c2", "c3", "c1", "c2", "c2", "c2","c1","c2" };
    Map<String, Integer> classRegistry = new HashMap<String, Integer>();
    for (int i = 0; i < c.length; i++) {
        String classes = c[i];
        if (!(classRegistry.containsKey(classes))) {
            for (int j = i + 1; j < c.length; j++) {
                if (classes.equals(c[j])) {
                    incr++;
                }
            }
            classRegistry.put(classes, incr+1);
            incr = 0;
        }
    }

Any idea how i can use something like a hashMap in MATLAB to calculate the number of occurrences of all the strings in an array
Thanks,
Bhavya

A: MATLAB has a function TABULATE available in the Statistics Toolbox:
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
t = tabulate(c)
t = t(:,1:2)

The result:
t =
    'c1'    [3]
    'c2'    [5]
    'c3'    [1]

Alternatively, you can do the same using the UNIQUE and ACCUMARRAY functions:
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
[classes,~,subs] = unique(c);
counts = accumarray(subs(:),1);

Again the result as before:
>> t = [classes(:) num2cell(counts)]
t =
    'c1'    [3]
    'c2'    [5]
    'c3'    [1]

Then to find the string that occurred the most, use:
>> [~,idx] = max(counts);
>> classes(idx)
ans =
    'c2'

A: You didn't specify exaclty how you would want your input and output data types to be, but I wrote this quick script you might find usefull.
c = {'c1' 'c2' 'c3' 'c1' 'c2' 'c2' 'c2' 'c1' 'c2'};
count = struct();
for ic=1:length(c)
    field = c{ic};
    if isfield(count, field)
        count = setfield(count, field, getfield(count, field) + 1);
    else
        count = setfield(count, field, 1);
    end
end

The output for this specific c would be
count =

    c1: 3
    c2: 5
    c3: 1

A: Since you have experience with Java, you could just write your code in Java and call it from MATLAB.  This techdoc article should help you get started if you decide to go this route.  But it would probably be more useful to learn how to do it in m-script (see jomb87's answer)
Incidentally, you could improve the performance of your Java algorithm if you take further advantage of the hash map:
    for (int i = 0; i < c.length; i++) {
        String classes = c[i];
        if (classRegistry.containsKey(classes)) {
            classRegistry.put(classes, classRegistry.get(classes) + 1);
        } else {
            classRegistry.put(classes, 1);
        }
    }


text:
Q: How do I place a formula in column D for every stop sub? So I have been tasked with creating a Spread Sheet to calculate how much time is spent in any given task. So far I have buttons set up to start and stop the clock but now i am stuck trying to add the following formula to each Stop Sub:
=text(A2-A3,HH:MM:SS)
Here is what I have so far:
'
Sub StartTask()
'
Dim lr As Long
lr = Sheets(2).Range("a" & Rows.Count).End(xlUp).Row
Sheets(2).Range("a" & lr + 1).Formula = Now()
Sheets(2).Range("b" & lr + 1) = "Task Name"
Sheets(2).Range("c" & lr + 1) = "Start"

End Sub

Sub StopTask()

Dim lr As Long
Dim lra As Range
Dim lrb As Range
'
lr = Sheets(2).Range("a" & Rows.Count).End(xlUp).Row
lra = Sheets(2).Range("a" & lr)
lrb = Sheets(2).Range("a" & lr - 1)
Sheets(2).Range("a" & lr + 1).Formula = Now()
Sheets(2).Range("b" & lr + 1) = "Task Name"
Sheets(2).Range("c" & lr + 1) = "Stop"
Sheets(2).Range("d" & lr + 1).Formula = Text(lra - lrb, "hh:mm:ss")
End Sub

The formula is to find the amount of time spent in each task by subtracting the start time from the stop time. Every time Sub StartTask is run a new row is placed in sheet two, and every time Sub StopTask is run a new row is inserted in the row below that, and so on. this means that the formula needs to be placed in the same row as all the other data from Sub StopTask. I think the problem is that i am not defining lra and lrb correctly, but I'm not really sure. How can i place the formula in column D of each StopTask row?

A: placing formula:
Sheets(2).Range("d" & lr + 1).Formula = "=Text(" & lra.Address & " - " & lrb.Address & ", ""hh:mm:ss"")"

A: As per my comment:
Sub StopTask()

Dim lr As Long
Dim lra As Range
Dim lrb As Range
'
lr = Sheets(2).Range("a" & Rows.count).End(xlUp).Row
Set lra =2 Sheets(2).Range("a" & lr + 1)
Set lrb = Sheets(2).Range("a" & lr)
Sheets(2).Range("a" & lr + 1).Formula = Now()
Sheets(2).Range("b" & lr + 1) = "Task Name"
Sheets(2).Range("c" & lr + 1) = "Stop"
Sheets(2).Range("d" & lr + 1).Value = Format(lra - lrb, "hh:mm:ss")
End Sub

First if you look, you were referring to the wrong rows for your values.  Second text is a worksheet function.  Use format instead.


text:
Q: How to find the defined name for a specific excel cell in c# I'm trying to find the defined name of a cell in an Excel file in C#, I tried to find the value and I succeeded in that but I'm not able to find the name.
Here is my code that succeeds in finding the value:
            Application application = new Application();
            Workbook workBook = application.Workbooks.Open(requestSheetPath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            Worksheet workSheet = (Worksheet)workBook.Worksheets.get_Item(sheet);
            Range range = workSheet.UsedRange;
            if (range.Cells[column, row] != null && range.Cells[column, row].Value2 != null)
                return range.Cells[column, row].Value2.ToString();

How can I find the defined name?

A: You'll want to use Excel.Worksheet.Names
foreach (Excel.Worksheet sheet in wb.Sheets) {
foreach (Excel.Range range in sheet.Names) {
    // this is the named ranges
 }

}
you can see This answer for more info


text:
Q: fetching user media from instagram api without user id I did what @krisrak told me to do. I used two API calls.
One to search for the username with
https://api.instagram.com/v1/users/search?count=1&q=USERNAME

and i got the user id from there to perform the second API call
The second call was
https://api.instagram.com/v1/users/USER-ID/media/recent/

This worked perfectly until I searched a certain username and I was given another. So I want to know if there's a sort of where clause to use to get the username I want from a list of results gotten. So my 1st call would now be
https://api.instagram.com/v1/users/search?count=0&q=USERNAME

to enable me get all results.

A: If there is no match, then that username probably does not exists, go to instagram.com/USERNAME and check if it exists. You may have to ignore and display that username does not exist.
BTW to get all the results, just remove count=1, then it will return a bunch of usernames that match similar search, usually the first one will be the exact match, so thats the reason count=1 is used to match a particular username.
https://api.instagram.com/v1/users/search?q=USERNAME


text:
Q: Regexp to get website name from a link? I am trying to get the website name from link, for example if the give link is
http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip

I want to get just www.example.com out of it. The links are hundreds, so manual work is useless. Therefore I'm tring regexp with something like sed.
Can anyone help?

A: This can make it:
sed -r 's|(.*://)?([^/]*).*|\2|' file

It handles both urls with and without http / ftp...:
$ cat a
http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip

$ sed -r 's|(.*://)?([^/]*).*|\2|' a
www.example.com
www.example.com

A: With (GNU) grep:
grep -oP '(?<=//)[^/]*' <<<"$url"

I'm using a positive lookbehind assertion, which is available only in perl compatible mode -P.

(Original answer)
With sed:
sed 's#.*//\([^/]*\).*#\1#' <<<"$url"

A: Try this also,
$ sed 's/^http:\/\/\([^/]*\).*/\1/g' file
www.example.com

A: Rather than using regular expressions, you could use the Perl module URI::URL. Assuming your list of links is in a file named links, this will print out all of the hostnames:
perl -MURI::URL -ne '$url = url $_; print $url->host' links

Sample input:
http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
http://www.other.example.org/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip
http://www.third.net/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip

Output:
www.example.com
www.other.example.org
www.third.net

A: try this:  /\/{2}(.*?)\// it will find anything between // and /

A: Use grep Utility eg.
echo 'http://www.example.com/Something/SomethingElse/SomethingUnwanted/Usefulthing.zip' | grep -o 'http://[a-zA-Z0-9.-]*/'


text:
Q: Init App from SQLite DB from multiple table? In my app,
First Screen is splash screen, it displays the ProgressDialog until the data is loaded from DB and then forward the user to next Main App Screen.
I am using doInBackground to load category data and in onPostExecute set this to catgoryList.
I also want to laod some category Item's when app inits.
1) Is is fine to execute two AsyncTasks, one for category and other for items.
2) Or can it be done in one AsyncTask. doInBackground can return only one type of list at the moment.
How can I change it to return both catgory and item from doInBackground of one AsyncTask.
Thanks

A:
Is is fine to execute two AsyncTasks, one for category and other for items.

Yes, this is fine.
In order to synchronize with your main activity, you have at least two solutions:

*

*Run the AsyncTasks sequentially. The first AsyncTask will spawn a second one in its onPostExecute(). Then the second task starts the main activity.

*Use a countdown latch. Conceptually this is just a integer that is incremented by each AsyncTask as it completes. Java and Android implement this idea in CountDownLatch. When the count down is reached, then you can start the main activity. This YouTube video gives a great in-depth description of the concepts involved.

A:
How can I change it to return both catgory and item from doInBackground of one AsyncTask.

Store them in a list and return it in doInBackground.
You can get it by identify the position.

A: You can also define a new type as value holder and use it:
public class DataValueHolder {
    public List<Item> items;
    public List<Category> categories;
}

Now, create an object of this class and return it in doInBackground method.


text:
Q: Write directly to screen with c++ Hello I am new to c++ and am wondering where to go about looking to print directly to the screen? For example the HUD interface that appears on laptops when you change the volume.  I'm not really looking for any fancy graphics, just, say, a variable or info from a file.
I've tried googling but havn't come up with anything yet.  So...where should I begin looking?
Thanks!

A: Under windows there are a few ways to do it.  You could use DirectDraw Overlays (If the system supports them).  Or you could create a layered window (WS_EX_LAYERED) and make everything but the bit you want to display transparent.

A: Pure C++ has only one screen interface, in the  library. That's text-oriented. To do graphics, you need another OS-specific interface. So, you'd be looking at the API documentation for your OS.
BTW, the overlay graphics when you change the volume on your laptop are really special, IIRC. They're generated by your laptop itself, using System Management Mode - not the OS itself, and certainly not a program.


text:
Q: Lanzar evento en el form desde un control de usuario Tengo un formulario que va a contener varias copias de un control de usuario, lo que quiero hacer es que cuando dentro de uno de esos controles de usuario se haga click en un boton, se lanze un evento del formulario que lo contiene.
He pensado en guardar una referencia del formulario en el constructor del control de usuario y asi poder llamar a cualquier metodo de ese formulario, pero me parece una solucion poco elegante.
Agradeceria si alguien me puede indicar alguna manera mas elegante de hacer esto.

A: Podrias hacerlo por propagación de eventos:
public partial class UserControl1 : UserControl
    {

        public delegate void ButtonClick(object sender, EventArgs e);
        public event ButtonClick OnButtonClick;
        public UserControl1()
        {
            InitializeComponent();

            button1.Click += new EventHandler((sender, args) =>
            {
                OnButtonClick?.Invoke(this, null);
            });
        }
    }

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            UserControl1 usrCtrl = new UserControl1();
            usrCtrl.OnButtonClick += UsrCtrl_OnButtonClick;
            this.Controls.Add(usrCtrl);
        }

        private void UsrCtrl_OnButtonClick(object sender, EventArgs e)
        {
            MessageBox.Show("Click en boton dentro del usercontrol");
        }
    }


text:
Q: How to turn pandas dataframe row into ordereddict fast Looking for a fast way to get a row in a pandas dataframe into a ordered dict with out using list. List are fine but with large data sets will take to long. I am using fiona GIS reader and the rows are ordereddicts with the schema giving the data type. I use pandas to join data. I many cases the rows will have different types so I was thinking turning into a numpy array with type string might do the trick.

A: This is implemented in pandas 0.21.0+ in function to_dict with parameter into:
df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])
print (df)
   a  b
0  1  2
1  3  4

d = df.to_dict(into=OrderedDict, orient='index')
print (d)
OrderedDict([(0, OrderedDict([('a', 1), ('b', 2)])), (1, OrderedDict([('a', 3), ('b', 4)]))])

A: Unfortunately you can't just do an apply (since it fits it back to a DataFrame):
In [1]: df = pd.DataFrame([[1, 2], [3, 4]], columns=['a', 'b'])

In [2]: df
Out[2]:
   a  b
0  1  2
1  3  4

In [3]: from collections import OrderedDict

In [4]: df.apply(OrderedDict)
Out[4]:
   a  b
0  1  2
1  3  4

But you can use a list comprehension with iterrows:
In [5]: [OrderedDict(row) for i, row in df.iterrows()]
Out[5]: [OrderedDict([('a', 1), ('b', 2)]), OrderedDict([('a', 3), ('b', 4)])]

If it was possible to use a generator, rather than a list, to whatever you were working with this will usually be more efficient:
In [6]: (OrderedDict(row) for i, row in df.iterrows())
Out[6]: <generator object <genexpr> at 0x10466da50>


text:
Q: Logging log4j and Null object I wonder that can I avoid NullPointerException in _log.info.
I have 1 null object (obj) and then
_log.info("obj id: " + obj.objId());

In this case I want _log printout that obj.objId() is null and not throw an exception :-? anyone know how to ?

A: That's not an issue with log4j, that's an issue with your program
You could do something along the lines of ....
_log.info("obj id: " + (obj == null ? null : obj.objId()));

I don't think the problem is that the ID is null, I think, from what you are saying, the obj is null, thus the reference to obj.objId() is causing the NPE

A: What about: _log.info(String.format("obj id: %s", (obj == null ? obj : obj.objId())));?


text:
Q: How To set Shadow(Light) using DirectioalLight on boxgeometry in threejs? I am used Directionl light for shadow, But I need Light shadow not Dark. I am using this code : -
   this.root.remove(this.light.shadow.camera);
   this.scene.remove(this.light);
   this.scene.remove(this.camera);
   this.light.position.set(0, minPosition, maxPosition);
   this.light.castShadow = true;
   this.light.intensity = 1.6;
   this.light.shadow.camera.top = 16; // default
   this.light.shadow.camera.bottom = -6; // default
   this.light.shadow.camera.right = 10; // default
   this.light.shadow.camera.left = -10; // default
   cube.castShadow = true;
   this.light.shadow.transparent = true;
   this.light.target.position.add(this.scene.position);
   this.light.shadow.mapSize.width = 1024;
 this.light.shadow.mapSize.height = 1024;

[![BoxShadow][1]][1]
[1]: https://i.stack.imgur.com/00byW.png

A: You can use "Hemishpere light " over the "Directional light" which will reduce the shadow intensity. You can refer to the three.js examples :
https://threejs.org/examples/#misc_exporter_ply


text:
Q: Defining a minor of an array I have 2 functions, in the first one I generate a bidimensional array and in the second one I define an array minus the last line and column. However it does not work. The code is as follows:
function calcDet () {
    var A = [];     //generates the array
    for (var i = 0; i < k; i++) {
        A[i] = [];
        for (var j = 0; j < k; j++) {
            var id = "A" + (i + 1) + (j + 1);
            A[i][j] =  parseFloat(document.getElementById(id).value);
        }
     }
     return (A);
}
function returnDet() {
    var s;
    var A = calcDet();
    var smaller=[];
    for (var i=0;i<k-1;i++) {
        smaller[i]=A[i]
        for (var j=0;j<k-1;j++) {
            smaller[i][j]=A[i][j];
        }
    }
    alert (smaller);
}

A: Your code has undefined variables:
"k" seems to appear out of nowhere in both functions
Line
var id = "A" + (i + 1) + (j + 1);
will generate identical id for (some) different variations of i and j ([i = 11 and j = 1] == [i = 1 and j = 11]) that may be a cause of further errors
And it is always useful if you mention the error that you are getting - I would expect that your scripts would not run at all as they are...

A: Your variable k, the length of the arrays, is defined nowhere. It should trow an error stating that.
You've got an error in your returnDet function. You first create the array smaller, then fill it with the "second-level" arrays from A:
    smaller[i]=A[i];

After that, you set each (except the last) of the values in smaller[i] to the value they already have:
    for (var j=0;j<k-1;j++) {
        smaller[i][j]=A[i][j];
    }

Yet, smaller[i][k-1] (the last one, which you don't want) still exists in the array, because both smaller[i] and A[i] point to the same object. What you want to do is:
function returnDet() {
    var A = calcDet();
    var smaller = [];
    for (var i=0; i<A.length-1; i++)
        smaller[i] = A[i].slice(0, -1);
    return smaller;
}
alert(returnDet());

Array.slice() copies the values from the array.

A: Using built-in language features makes the code simpler to write and understand and also more efficient.
function trim (arr, r, c) {
  // Return a new array omitting the last r rows and c columns
  //    of a two dimensional array arr
  //    if not specified r and c default to 1

  arr = arr.slice (0, -(r || 1)); // remove last r rows
  arr.forEach (function (v, i, a) { a[i] = v.slice (0, -(c || 1)); });
  return arr;
}

[JSON.stringify (trim ([[11, 12, 13], [21, 22, 23], [31, 32, 33]])),
 JSON.stringify (trim ([[11, 12, 13], [21, 22, 23], [31, 32, 33]], 1, 2)),
 JSON.stringify (trim ([[11, 12, 13], [21, 22, 23], [31, 32, 33]], 2, 1))]

/* Displays on JS console :
  ["[[11,12],[21,22]]", "[[11],[21]]", "[[11,12]]"]
*/


text:
Q: When subclassing SKNode, should the Frame property return a non-empty value? I'm subclassing SKNode to render a map that consists of many SKSpriteNodes by adding those nodes to my subclass.
All is working well but I noticed that the Frame of my node subclass is always 0.
I couldn't find anything about this in the docs, so: am I supposed to override the Frameproperty and return a correct value?

A: The frame property is the frame of the node itself, ignoring any children. For an SKNode this is a position but zero width and height.

The frame is non-empty if the node's class draws content.
  (https://developer.apple.com/reference/spritekit/sknode)

Which I read as: SKNode draws no content so it is correct for it to be empty.
The frame of the node and its children is provided by the method calculateAccumulatedFrame() and functions that need the frame of the sub-tree should call that and not reference the frame property.
So there should be no need to override frame for your SKNode. I never have, have similar constructs in a few apps
and have not yet had problems...


text:
Q: Attempting to get a css value with jquery I am attempting to get a css value of a background. My attempt is failing and the correct value isn't being delivered. I have a spectrum.js color picker and no matter which color I choose rgba(0,0,0,0) is always chosen. When I look at the background in the console it displays it correctly in the DOM.
Does anybody see why this is failing?

$(".colorpicker").spectrum({
    color: "#FFF",
    showInput: true,
    className: "full-spectrum",
    showInitial: true,
    showPalette: true,
    showSelectionPalette: true,
    maxSelectionSize: 10,
    preferredFormat: "hex",
    localStorageKey: "spectrum.demo",
    change: function(color) {
        var eq =  $(this).index('.colorpicker');
        $('.container').eq(eq).css('background-color', color.toHexString())
    }
});

var color = $( "#outside-preview" ).css( "background-color" );
$("#result").html("That div is " + color + "");

Fiddle

A: You need to place the code which reads the CSS value in the change handler so that it updates the #result element after a selection is made. Your current code is only reading it on load.
change: function(color) {
    var eq = $(this).index('.colorpicker');
    $('.container').eq(eq).css('background-color', color.toHexString())

    var color = $("#outside-preview").css("background-color");
    $("#result").html("That div is " + color);
},

Updated fiddle


text:
Q: Need to create GUI interface in Cent OS which is located in Windows XP I am in need to install GUI of Cent OS (5.8-final) in Windows XP.
I have installed Cent OS 5.8-final on Windows XP using VMPlayer. And Finally it has been done.
How can I create a GUI Interface in Cent OS ?
I googled and I got a clue that using CNTLM it is possible to do !!!
But I didn't find any exact tutorials to work it..
Finally I am here for solutions from SuperUsers :-)
Any suggestions or solutions will be grateful and thankful..

A: Looks like either CentOS doesn't boot into runlevel 5 or X server packages are missing (or maybe simply VMware tools aren't installed?)
Install VMware tools:
If not yet done, install VMware tools on your CentOS. Check this: http://www.thoughtpolice.co.uk/vmware/howto/centos-5-vmware-tools-install.html.
Check runlevel 5:
Log in to CentOS as root and run runlevel. If it shows something like:
N 3

you are running in multiuser, CLI mode. Run telinit 5. If nothing happens (that is, no GUI appears) the X server may not be installed.
Install X server:
Check this post "Can I add X to my server after install? or I installed from the Server ISO and it didn't install X, how do I install X?": http://www.centos.org/modules/smartfaq/faq.php?faqid=50.


text:
Q: Why my map function not working on filter dates? I am calling a fetch API data and create table on HTML body load. and filter and map method giving right data but when I am selecting the dates from input and then this is only return the dates but somehow filter and map method not working with those dates criteria. I tried to debug but no luck don't know where is the problems is, struggling to find where is issue.
HTML

Filter

        <select class="form-select form-select-sm" aria-label=".form-select-sm example" id="filter">
            <option value="All">All</option>
            <option value="Approved">Approved</option>
            <option value="" selected>Pending</option>
            <option value="Rejected">Rejected</option>
            <option value="Unpaid">Unpaid</option>
          </select>

From

        <input type="date" class="dates" id="filterStart">

To

        <input type="date" class="dates" id="filterEnd">
        <button type="button" onclick="getDates()">Refresh</button>

JavaScript
function getDates() {
  let filterStart = document.getElementById("filterStart").value;
  let startDate = "";
  let endDate = "";
  if (!filterStart) {
    let date = new Date();
    startDate = new Date(
      date.getFullYear(),
      date.getMonth(),
      1
    ).toLocaleDateString();
    endDate = new Date(
      date.getFullYear(),
      date.getMonth() + 1,
      0
    ).toLocaleDateString();
  } else {
    startDate = new Date(
      document.getElementById("filterStart").value
    ).toLocaleDateString();
    endDate = new Date(
      document.getElementById("filterEnd").value
    ).toLocaleDateString();
  }
  getLeaveData(startDate, endDate);
}

function getLeaveData(startDate, endDate) {
  console.log(startDate, endDate);
  console.log(typeof startDate);
  let status = document.getElementById("filter").value;
  fetch(getLeaves)
    .then((res) => {
      return res.json();
    })
    .then((data) => {
      let tableData = "";
      let id = 0;
      let table = data
        .filter((values) => {
          return (
            values.startDate >= startDate &&
            values.startDate <= endDate &&
            values.hrremarks == status
          );
        })
        .map((values) => {
          console.log(values);
          tableData += `

                    ${values.employeeId}
                    ${values.firstName} ${
            values.LastName
          }
                    ${values.email}
                    ${values.leaveType}
                    ${values.duration}
                    ${values.startDate}
                    ${values.enddate}
                    ${values.hrremarks}
                    <button type="button" >Action</button>

`;
        });
      document.getElementById("dataTable").innerHTML = tableData;
    });
}

A: Finally Struggling a lot. I found the correct way. which is working fine. I just used getTime() method.


text:
Q: Absolute div's width becomes so small that the text is wrapping When I make a button I want to make a div that appears when I hover the button, though I have problems with it's width and it's position.
The problem can be seen below in the pictures and in the jsfiddle. When I make something absolute to the relative button, it looks like it's max-width becomes the width of the button. If the button is small, the hover div will also be small. How can I make a normal hover div with a width:auto?
http://jsfiddle.net/ghpc9fwk/

A: Just add a white-space: nowrap; attribute to prevent the text from wrapping on nearest occasions;)
Here's a working example: http://jsfiddle.net/1revewwm/
I 've also modified the bottom attribute

A: Not sure if this works for you but you could perhaps use ::before pseudo element to achieve such layout.
.alt-test{
    background-color:blue;
    display:inline-block;
    margin:0;
    padding:0;
    position:relative;
    margin-bottom:20px;
}

.alt-test::before{
    content:"";
    display:block;
    height:10px;
    width:10px;
    background:red;
    position:absolute;
    left:0px;
    top:-10px;
}

JSFIDDLE

A: Something like this?

Click here now!

.button{
    width:10px;
    height:10px;
    background-color:red;
}
.alt{
    margin-top: 10px;
    display: none;
    background-color:blue;
    width: auto;
    white-space: nowrap;
}

.button:hover .alt{
    display: inline-block;
}

Updated Fiddle

A: You can wrap your button and alt container in another div with position: relative;. Example fiddle
HTML:

Click here now!

CSS:
.wrapper {
    position: relative;
}

.button{
    width:10px;
    height:10px;
    background-color:red;
    position:relative;
}

.alt{
    position:absolute;
    background-color:blue;
    display: none;
}

.button:hover + .alt {
    display: block;
}

A: A simple solution as noted before is to add white-space:nowrap to your alt/caption div, so it stretches until you insert some

Additionally
I would recommend you not to use
bottom: -[something]px
but to use
top: 100%.
this way the button could be of variable height.
I modified your JSFiddle accordingly: http://jsfiddle.net/ghpc9fwk/3/


text:
Q: How can I reorganize a directory structure in Perl? I am writing a script for renaming/copying the content of a file.
I have temp & temp1 folders. Inside temp1 I have 1,000 .txt files with names 1.txt, 2.txt, 3.txt ... & in temp folder I have sub directories named 1, 2, 3.
In the folders 1, 2, 3 ...,  I have one file with extension java or xml.
My need is to automate the copy of the contents of the .txt file, and paste into the respective file in the temp sub directory. Is it possible to do this using Perl?

A: Please see perldoc -f rename. You can rename files in a loop.


text:
Q: Retrieve Power BI data set published to the service using a desktop pibx file I have created a data model and published to the power BI service and now trying to access that Power BI data set through the new BI desktop Pibx file but keep getting the below error. It worked fine on my personal laptop (Which was on Windows 10) my office PC is on Windows 7.
Image of the thrown error


text:
Q: File path magento 2 I am getting "TypeError: Cannot read properties of undefined (reading 'replace')" error on https://www.website.com/static/version1649742238/frontend/Mgs/supro/en_AU/mage/utils/misc.js
I am not sure where should I locate this file to edit.
Any thoughts ?

A: This is static generated file you can find this in magento_root/pub/static/frontend/Mgs/supro/en_AU/mage/utils/misc.js
But it's original file can be found within magento_root/app/code/Mgs/supro
Try using find command in app/code/Mgs folder like
find -name "misc.js"
Magento versioning is enabled you can disable for development purpose set
MagentoAdmin->Stores->Configration->System->Developer->Static View files to no


text:
Q: In the database, what is the relationship between the customer_entity table and sales? I'm trying to merge Magento orders between two different stores and I'm tracking down all of the relationships. The one I'm currently trying to figure out is the customer_entity table and the sales_* tables. I don't see a foreign key or entity_id that would line the two up.
How does Magento associate customer tables with sales?

A: See sales_flat_order.customer_id
Since customer can check out as guest, then customer_id is either null for quest or contain the customer id for register member


text:
Q: Add values from count that have come from a UNION I am attempting to add together the values_occurrence for the id's that match. For example ID number 1 has 3 and another record shows ID number 1 having 4. I want to ADD 3 + 4 based on the ID matching.
I am trying to see which ID has the most entries in each table and then add them together.
ID  value_occurrence
--------------------
1    3
1    4

so far this is what I have.
SELECT ID, COUNT(ID) AS value_occurrence
FROM     TABLE1
GROUP BY ID
UNION
SELECT ID, COUNT(ID) AS value_occurrence
FROM     TABLE2
GROUP BY ID
ORDER BY ID ASC;

Any help would be appreciated.

A: Do a union all and then aggregate:
select id, count(*) as total_cnt, sum(t1) as t1_cnt, sum(t2) as t2_cnt
from ((select id, 1 as t1, 0 as t2 from table1) union all
      (select id, 0, 1 from table2)
     ) t
group by id
order by id;


text:
Q: How to convert character string to int in c THis question is to convert character string to int.
if you input the character string, the input is converted to int.
for example, if you input the character string by keyboard "C35#37"
this program should add 3 + 5 + 3 + 7 and so result is 18.
so i get length of character string by strlen. and use "for statement" to distinguish if this input is char or int.(because  if char is inputed in the atoi, the result is 0)
but this program i make run not well.
i want to know why this program is not working and how to this problem  is solved.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main(void)
{
    char str[200];

    int len, i,sum=0;

    fputs("문자열을 입력해 주세요: ",stdout);
    fgets(str,sizeof(str),stdin);

    len = strlen(str);
    for(i=0; i<len; i++)
    {
      sum= sum + atoi(&str[i]);
    }
    printf("%d",sum);

    return 0;

}

result1:
> Executing task: ./blog <

문자열을 입력해 주세요: a12
14
Terminal will be reused by tasks, press any key to close it.

result2:
> Executing task: ./blog <

문자열을 입력해 주세요: 123
149
Terminal will be reused by tasks, press any key to close it.

A: There is no need to use the function atoi. Instead of this code snippet
len = strlen(str);
for(i=0; i<len; i++)
{
  sum= sum + atoi(&str[i]);
}

you could write
for ( const char *p = str; *p; ++p )
{
    if ( '0' < *p && *p <= '9' ) sum += *p - '0';
}

If to use your approach with the function atoi then for example the string 123 is parsed as 123 + 23 + 3 = 149.


text:
Q: NSFetchedResultsController can't update the tableView swift4 I'm trying to make it work for last couple of days and can't get it working. Its something tiny detail obviously I can't seem to find.
Could you take a look and give me some insights about my code?
I'm trying to update the logView with app savings in the coredata.
Here's the entire code for ViewController and CoreData Handler.
/// fetch controller
lazy var fetchController: NSFetchedResultsController = { () -> NSFetchedResultsController<NSFetchRequestResult> in
    let entity = NSEntityDescription.entity(forEntityName: "Logs", in: CoreDataHandler.sharedInstance.backgroundManagedObjectContext)
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
    fetchRequest.entity = entity

    let nameDescriptor = NSSortDescriptor(key: "name", ascending: false)
    fetchRequest.sortDescriptors = [nameDescriptor]

    let fetchedController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataHandler.sharedInstance.backgroundManagedObjectContext, sectionNameKeyPath: "duration", cacheName: nil)
    fetchedController.delegate = self as? NSFetchedResultsControllerDelegate
    return fetchedController
}()

override func viewDidLoad() {
    title = "Week Log"

    tableView.tableFooterView = UIView(frame: CGRect.zero)
    tableView.separatorColor = UIColor.black
    tableView.backgroundColor = UIColor.red

    refreshView()
    loadNormalState()
    loadCoreDataEntities()

}

/**
 Refresh the view, reload the tableView.
 */
func refreshView() {
    loadCoreDataEntities()
    tableView.reloadData()
}

/**
 Load history entities from core data. (I'm printing on the console and
 be able to see the the fetched data but I can't load it to tableView.)
 */

func loadCoreDataEntities() {

        do {
            try fetchController.performFetch()
        } catch {
            print("Error occurred while fetching")
        }
}

import Foundation
import CoreData

class CoreDataHandler: NSObject {

/**
 Creates a singleton object to be used across the whole app easier

 - returns: CoreDataHandler
 */
class var sharedInstance: CoreDataHandler {
    struct Static {
        static var instance: CoreDataHandler = CoreDataHandler()
}
    return Static.instance
}

lazy var backgroundManagedObjectContext: NSManagedObjectContext = {
    let backgroundManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
    let coordinator = self.persistentStoreCoordinator
    backgroundManagedObjectContext.persistentStoreCoordinator = coordinator
    return backgroundManagedObjectContext
}()

lazy var objectModel: NSManagedObjectModel = {
    let modelPath = Bundle.main.url(forResource: "Model", withExtension: "momd")
    let objectModel = NSManagedObjectModel(contentsOf: modelPath!)
    return objectModel!
}()

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.objectModel)

    // Get the paths to the SQLite file
    let storeURL = self.applicationDocumentsDirectory().appendingPathComponent("Model.sqlite")

    // Define the Core Data version migration options
    let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]

    // Attempt to load the persistent store
    var error: NSError?

    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: options)
    } catch {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject
        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject

        dict[NSUnderlyingErrorKey] = error as NSError
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
    return persistentStoreCoordinator
}()

func applicationDocumentsDirectory() -> NSURL {
    return FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).last! as NSURL
}

func saveContext() {
    do {
        try backgroundManagedObjectContext.save()
    } catch {
        print("Error while saving the object context")
        // Error occured while deleting objects
    }
}

A: You have a data source delegate somewhere. That data source delegate tells the table view how many items there are, and what their contents is. How does it know how many items? That must be stored somewhere.
When the fetch controller is successful, it must modify the data that the data source delegate relies on in some way, and then call reloadData. Are you doing this? Are you doing anything that causes the data source delegate to change the number of items it reports?
And calling loadCoreDataEntities, immediately followed by reloadData, is nonsense. loadCoreDataEntities is asynchronous. By the time you call reloadData, it hasn't loaded any entities yet. realodData is called when loadCoreDataEntities has finished.


text:
Q: Can a WCF service w/ BasicHttpBinding without a MEX Endpoint be exploited by absolute strangers? From what I understand: If you don't have a MEX endpoint / WSDL, your service is basically non-discoverable. Only people who have knowledge of your data contract should be able to consume your service.
Does this assertion hold water, or are there ways for malicious denizens of the internet to figure out how to invoke/consume services that have no MEX endpoint?
EDIT: As Andrew pointed out, this strategy should not be considered to be truly secure. I'm wondering more along the lines of if it is safe from random abuse during a QA phase with external consumers.

A: Depends on your definition of secure. It's a case of security by obscurity, which might be fine for your personal to do list service, but unacceptable for a financial app.
SOAP etc is not /that/ complicated, so it's not impossible that a hacker could guess some inputs, although depending on the service, it could be very unlikely (even mathematically unfeasible). However if you distribute a client that could be reverse engineered, or if someone manages to packet sniff legitimate use of your service, then they could almost certainly exploit it?

A: People (hackers) use port sniffers to find ports where there is something listening. Then they start probing it with data and see what comes back. It doesn't take much work to figure out this is a port that want a SOAP message. Basically the errors returned will tell you as much. So no security by obscurity is no security at all and you might as well publish the URL.
The MEX part is only there to help others create service contract and never a requirement. Take a REST or JSON service for example, there is no concept of a MEX endpoint.


text:
Q: Null pointer exception while creating excel file in Java with apache poi on the line rowHeading.getCell(i).setCellStyle(stylerowHeading); I am going through POI Excel tutorial on you tube.
when I executed following code I get NullPointer exception.
Plz suggest the ans.
Thanku.
package main;

import entities.*;
import dao.*;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try{
            ProductModel pmodel = new ProductModel();
            HSSFWorkbook workbook= new HSSFWorkbook();
            HSSFSheet sheet=workbook.createSheet("List Products");
            //create heading
            Row rowHeading = sheet.createRow(0);
            rowHeading.createCell(1).setCellValue("Id");
            rowHeading.createCell(2).setCellValue("Name");
            rowHeading.createCell(3).setCellValue("Creation Date");
            rowHeading.createCell(4).setCellValue("Price");
            rowHeading.createCell(5).setCellValue("Sub Total");

            for(int i=0;i<6;i++)
            {
                CellStyle stylerowHeading= workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                font.setFontName(HSSFFont.FONT_ARIAL);
                font.setFontHeightInPoints((short)11);
                stylerowHeading.setFont(font);
                stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);
                rowHeading.getCell(i).setCellStyle(stylerowHeading);

            }

            //save to excel
            FileOutputStream out =
                    new FileOutputStream("D:\\AVIATE\\excel\\listproducts.xls");
            workbook.write(out);
            out.close();
            System.out.println("Excel written successfully........");

        }catch(Exception e){
            System.out.println("exception");
            e.printStackTrace();
        }
    }

}

A: For the first iteration of the for cycle, you call getCell(0) , but you do not create a cell with number 0. The first one is rowHeading.createCell(1).


text:
Q: PHP Regex preg_match_all I have a large text file that i need to remove a certain piece of information from, but i am still learning regular expressions and need some help with the search string statement.
Below is an example of the data i am trying to extract:
"id": "12345"  (good)
"id": "a123"   (bad)

The part i am having trouble with, is that i want to grab the first example, which has ONLY numbers as the value for ID. If there is a letter within the ID, i do not want to grab it. The ID numbers also differ in length, but the format is consistent:
"id": "number_here"

I have the following code but it does not seem to work for what i want to do:
preg_match_all("/\"id\"\:\s\"[0-9]\"/", $input_file)

A: Your regex is good (if a bit heavy on backslashes), except for one fatal flaw: You are only searching for a single digit.
preg_match_all('/"id": "[0-9]+"/', $input_file, $matches);
var_dump($matches);

Hope this helps!

A: *

*You don't need to escape many characters in yiur regex

*Use single quotes for regex

*Make sure to use quantifier + to match 1 or more digits after "id":
You can use:
preg_match_all('/"id" *: *"[0-9]+"/', $input_string, $matches) ;


text:
Q: Loading ddl in python goes in Windows Error 0xE0434F4D I have a motherboard with a kinda of jamma connector, model is axiomtek GMB121.
They provide library for GPIO for windows  as dll. The win32 application example works fine.
I'm trying to comunicate with this ddl using python.
I wrote so far, coping from the C code example and converting in python:
from ctypes import *

ERR_Success = 0
ERR_Error = -1
ERR_NotExist = -2
ERR_Opened = -3
ERR_NotOpened = -4
debounce=1
mydll = windll.LoadLibrary("C:\\Users\\test\\Documents\\TestPy\\AGP1_MFC64.dll")

iRet=mydll.AXGMB_Nvram_Open()
if (iRet != ERR_Success and iRet != ERR_Opened):
    print "error"
iRet = mydll.AXGMB_DIO_SetDebounceTime(debounce)
if (iRet == ERR_Success):
    print "AXGMB_DIO_SetDebounceTime Function success"
else:
    print "AXGMB_DIO_SetDebounceTime Function failure"
mydll.AXGMB_DIO_Close()

But what I got is:

iRet=mydll.AXGMB_Nvram_Open()
WindowsError: [Error -532459699] Windows Error 0xE0434F4D

And I don't know how to proceed, any advice?


text:
Q: Popular datagrid com threading Estou contraindo uma aplicação Windows Form. Não estou conseguindo popular meu datagrid com uma threading, aparece o seguinte erro:

"Operação entre threads inválida: controle datagrid acessado de um thread que na é aquela no qual foi criado

A: Um elemento de tela UI(controle), no Winforms e WPF nao permitem ser acessados por outras threads ou múltiplas threads.
O elemento UI apenas pode ser acessado pela thread que nela foi criada.
O que voce pode fazer é utilizar delegates...
Invoke(new Action(() =>
{
     if (dataGridView1.CurrentCell.RowIndex < dataGridView1.RowCount )
     {
          dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = false;
          dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + 1].Selected = true;
     }
}));


text:
Q: Standard way of computing a single ECDSA signature hex string from its tuple form I implemented ECDSA manually in rust, where the output is signature in the form of a tuple (r,s). I wanted to test my implementation, and therefore I was looking for functions in python or rust for verifying the signature (r,s) given the public key, message and the curve details. The Wiki article also shows the output signature in tuple form.
But, everywhere I looked, the signature is inputted as a single hex string or a byte array. Can someone please share any way of converting (r,s) pair to the hex string. I tried concatenation but got wrong result in my algo.
If it is helpful, I tried using the crate secp256k1 in rust for verification.


text:
Q: filter lines starting with ; ussing batch Hi I have a script (auto lisp AutoCAD) for a program. The rules of this script are that comments are started with ; character is it possible to write a batch that filters out all lines starting with ;. I namely then encrypt the file from a LSP to a FAS type which renders the commentary as useless (cant be read when encrypted) however AutoCAD still encrypts the text meaning a fairly heavy file size (double of what it should be). The current method is to manually delete every comment line by hand however try doing that a few hundred times. And I need the commentary in place to keep neat record of what's happening because I work from the not encrypted lisp file its self.
All in all I also want the encryption because its my hard work and my right to keep this secure as it then also means more job security, it also allows me to block some smart alec self proclaimed staff making edditation and in edition the file encryption is recommended for stability reasons by AutoCAD its self.
All in all even if it was because I like to without good reason then that should be valid enough.
I'm looking to achieve this through a batch script as that one of few languages that I feel competent enough in… outside of the AutoCAD frame.

A: The following will convert a file named "source.lsp" and produce "noComment.lsp". It will strip out lines that start with a ; (including comment lines indented with spaces).
findstr /rvc:"^ *;" "source.lsp" >"noComment.lsp"


text:
Q: Catching SIGINT signal to terminate a custom shell Hope you can help me to resolve this problem.
For school I have to transform Ctrl+C to a command which doesn't shut down the shell, but he reminds through printf() that I must type exit to close the shell. I don't even know where to start.
Thank a lot.

A: Here's a trivial implementation of handling SIGINT using sigaction which will work on posix systems. Left out error checking for brevity. The linked manual should explain about sigaction.
Basically the program loops through an infinite loop and break if user types exit. Using write as you can't use printf in signal handler. See signal manual for a list of functions that can be used safely in a signal handler.
#include<stdio.h>
#include<signal.h>
#include<string.h>
#include<stdlib.h>

char s[]="Type 'exit' to terminate\n";

void int_handler (int signum)
{
  write(fileno(stdin), s, sizeof s - 1);
}

int main (void)
{
  char str[256];
  struct sigaction sh;

  sh.sa_handler = int_handler;
  sigemptyset (&sh.sa_mask);
  sh.sa_flags = 0;
  sigaction (SIGINT, &sh, NULL);
  printf("%s", s);

  while(1) {
    fgets(str, sizeof str, stdin);
    char *p = strchr(str, '\n');
    if(p) *p = 0;
    if(!strcmp(str, "exit")) {
      printf("Exiting on request...");
      break;
    }
  }
  return 0;
}

A: Ctrl+C sends an interrupt signal (SIGINT) to the running process.You can use signal() to catch SIGINT like this:
 #include<stdio.h>
 #include<signal.h>

 void sigint_handler(int sig)
 {
   printf("Type exit to close the shell!\n");
 }

  int main()
  {
    signal(SIGINT, sigint_handler);

    /*Your code should replace the while loop.*/
    while(1)
    {
        printf("Running!\n");
        getchar();
    }

    return 0 ;
  }

A: As you're talking about doing it from the shell, you probably want:
$ trap "echo Please type \'exit\' to close the shell." SIGINT
<Ctrl-C>
Please type 'exit' to close the shell.
$

This specifies a command to execute when the listed signal is trapped (the trap command can also trap other signals; SIGINT is the one generated by Ctrl-C).  The \' protects the quote from being interpreted by the shell.


text:
Q: Why is Oracle SQL function regexp_substr not returning all matching characters? Could anyone (with extensive experience in regular-expression matching) please clarify for me why the following query returns (what I consider) unexpected results in Oracle 12?
select regexp_substr('My email: test@tes6t.test', '[^@:space:]+@[^@:space:]+')
from dual;

Expected result: test@tes6t.test
Actual result: t@t
Another example:
select regexp_substr('Beneficiary email: super+test.media.beneficiary1@gmail.com', '[^@:space:]+@[^@:space:]+')
from dual;

Expected result: super+test.media.beneficiary1@gmail.com
Actual result: ry1@gm
EDIT:
I double-checked and this is not related to Oracle SQL, but the same behaviour applies to any regex engine.
Even when simplifying the regex to [^:space:]+@[^:space:]+ the results are the same.
I am curious to know why it does not match all the non-whitespace characters before and after the @ sign. And why sometimes it matches 1 character, other times 2 or 3 or more characters, but not all.

A: The POSIX shortcut you are trying to use is incorrect, you need square brackets around it:
SELECT REGEXP_SUBSTR('Beneficiary email: super+test.media.beneficiary1@gmail.com', '[^@[:space:]]+@[^@[:space:]]+')
FROM dual;

or even simpler, assuming you only want to validate by checking for an '@' and the email address is always at the end of the string, after the last space:
WITH tbl(str) AS (
  SELECT 'My email: test@tes6t.test' FROM dual UNION ALL
  SELECT 'Beneficiary email: super+test.media.beneficiary1@gmail.com' FROM dual
)
SELECT REGEXP_REPLACE(str, '.* (.*@.*)', '\1')
from tbl
;

Note:  REGEXP_REPLACE() will return the original string if the match is not found, where REGEXP_SUBSTR() will return NULL.  Keep that in mind and handle no match found accordingly.  Always expect the unexpected!

A: The REGEX is not correct in your SQL code. Try
select regexp_substr('Beneficiary email: super+test.media.beneficiary1@gmail.com', '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b')
from dual;

select regexp_substr('My email: test@tes6t.test', '\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b')
from dual;

It gives the result that you expected.