text:
Q: How to resolve error 'While executing gem ... (TypeError) can't convert nil into String'? I am using using Windows 8 with cygwin. I am trying to configure Omega4 Drupal theme.
I have ruby version 1.9.3p547  (2014-05-14 revision 45962) [x86_64-cygwin]
I have installed ruby gems version 2.4.1 from https://rubygems.org/ , as shown also when I run the gem -v command:
$ gem -v
2.4.1

I have Drupal installed in folder c:\xampp\htdocs\drupal , and cygwin is accessible by cygdrive.
I navigate to the folder of my subtheme and then run the command like so:
$ drush omega-guard

which: no tput in (/home/prem/.rvm/gems/ruby-1.9.3-p547@omega.furniure/bin:/home/               prem/.rvm/gems/ruby-1.9.3-p547@global/bin:/home/prem/.rvm/rubies/ruby-1.9.3-p547                                                /bin:/home/prem/.rvm/bin:/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/Intel/iCLS Client:/cygdrive/c/Program Files/Intel/iCLS Client:/cygdrive/c/Windows/system32:/cygdrive/c/Windows:/cygdrive/c/Windows/System32/Wbem:/cygdrive/c/Windows/System32/WindowsPowerShell/v1.0:/cygdrive/c/Program Files (x86)/Intel/OpenCL SDK/3.0/bin/x86:/cygdrive/c/Program Files (x86)/Intel/OpenCL SDK/3.0/bin/x64:/cygdrive/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/cygdrive/c/Program Files/Intel/Intel(R) Management Engine Components/IPT:/cygdrive/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/cygdrive/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/IPT:/cygdrive/c/Program Files/Java/jre7/bin:/cygdrive/c/Ruby200-x64/bin:/cygdrive/c/Ruby193/bin:       /cygdrive/c/ProgramData/Drush:/cygdrive/c/Program Files (x86)/Drush/GnuWin32/bin:/cygdrive/c/Program Files (x86)/Drush/Php:/cygdrive/c/Program Files (x86)/Drush/cwRsync/bin:/cygdrive/c/xampp/php)
Which theme do you want to run Guard for?
 [0]  :  Cancel
 [1]  :  furniure (Subtheme of Omega) - Please provide a description for your
         theme.
 [2]  :  Ohm (Subtheme of Omega) - Omega based demonstration theme. Serves as a
         best-practice reference for the Omega documentation. Ohm will be
         constantly updated as best practice evolves so shouldn't be used in
         production.
 [3]  :  Omega - A powerful HTML5 base theme framework utilizing tools like
         Sass, Compass, Grunt, Bower, Ruby Version Manager, Bundler and more.
1
There was a problem with your setup:                                     [error]
Resolving dependencies...
Bundler can't satisfy your Gemfile's dependencies.
Install missing gems with `bundle install`.

However when I run the below command I run into an error I don't understand:
$ bundle install
Fetching gem metadata from https://rubygems.org/..........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Using addressable 2.3.6

TypeError: can't convert nil into String
An error occurred while installing sass (3.4.1), and Bundler cannot continue.
Make sure that `gem install sass -v '3.4.1'` succeeds before bundling.

$ gem install sass -v 3.4.1

ERROR:  While executing gem ... (TypeError)
    can't convert nil into String

So my question is about the above error While executing gem ... (TypeError) can't convert nil into String: how can I resolve this error?


text:
Q: Импорт классов в Python 3.7 Есть вот такая структура файлов

Запускаемый файл test.py в начале, которого
from .observer import Observer

При выполнении выдает
 Traceback (most recent call last):   File "test.py", line 1, in
 <module>
     from .observer import Observer ModuleNotFoundError: No module named '__main__.observer'; '__main__' is not a package

Помогите разобраться с импортом классов из других файлов.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Webmatrix/Razor and Stored procedure with OUT parameter I am trying WebMatrix for the first time and based on various forums, I put together the code to execute a stored procedure (in SQL Server 2008) but I need to retrieve output value from the stored procedure back in an OUTPUT parameter.
I use the following code:
@(
   var strInputParam = "Test";
   var strOutputParam = "";
   var db = Database.Open("mydatabase");
   var selectQueryString = "EXECUTE dbo.SP_Test @0, @1";
   //var selectQueryString = "EXECUTE dbo.SP_Test @0, @1 OUTPUT";
   db.Execute(selectQueryString, strInputParam, strOutputParam);
}

When I run this, the procedure runs but "strOutputParam" is still empty after the execution. I have also tried the version in the commented code as an alternative but that brings back empty value as well.
Is there anything specific I need to do to retrieve the OUTPUT param value?
Thanks for your help!

A: The Database helper doesn't support output parameters. It was never designed to work with stored procedures. You can use plain ADO.NET instead.

A: I know it is late but just in case some one else wants the answer,
If your query returns only one value:
var strOutputParam = db.QueryValue(selectQueryString, strInputParam, strOutputParam);

If your query returns an entire row:
var strOutputParam = db.QueryValue(selectQueryString, strInputParam, strOutputParam);
var col1 = strOutputParam.col1;
var col2 = strOutputParam.col2;

If your query returns multiple rows:
foreach (var strOutputParam in db.QueryValue(selectQueryString, strInputParam, strOutputParam){

}


text:
Q: HP ProLiant ML350p Gen8 server keeps crashing (full speed fans) I have a problem with a HP ProLiant ML350p Gen8 server. Most of the time it runs fine, but after several weeks of uptime, the server crashes out of the blue. This happened about 5 times now. When it crashes, the OS (VMWare ESXi 5.5) stops working and the fans are running on full speed. Pressing the power button doesn't change anything then. I have to unplug and plug back in the power cable to get it to restart.
I've done a memtest without any errors. I also didn't find anything in the logs. Do you have any ideas how to solve this?

A: There are a couple of reasons this could be happening.

*

*Firmware.

*Updates.

*possibly hardware.

Please see: http://meta.serverfault.com/q/6195/13325
If you're running Windows virtual machines configured with Intel e1000 virtual NICs, there is a chance that your VMware host is crashing. That's resolved with updates to ESXi and/or a change in your vNIC configuration.
If you're running old HP firmware, please update it.
Since you have HP hardware, please look in the ILO and the IML log to get a detailed reason for the crash. That will tell you if you're facing a hardware issue.
Memtest+ is useless on server equipment like this.


text:
Q: Отдельные лог-файлы для приложения Есть приложение на с++, пишущее данные в лог. Изначально была идея с использованием системного syslogd писать сообщения в /var/log/messenges.
Приложение пришлось адаптировать под Embedded-систему c BusyBox.
Отсюда собственно и вопрос, как сделать отдельный лог-файл (или даже не 1) для конкретного приложения? возможно ли это сделать, используя syslog.conf и если да то как примерно?

A: Вы можете сделать перенаправление вывода процесса в файл:

foo > allout.txt 2>&1


text:
Q: Saving a .php file and saving the includes too (possibly) The setup:
I have a standard .php file (index.php) that contains two includes, one for header (header.php) and one for footer (footer.php). The index.php file looks like this:
index.php
<?php
include header.php;
?>

Hello

Lorem ipsum dolar doo dah day

<?php
include footer.php;
?>

header.php like this:

<title>This is my page</title>

My Website rocks

and footer .php like this:

The end of my page

I am writing a PHP script that allows you to edit any of the ".editable" items on a page. My problem is that these editable regions could appear in any included files as well as the main body of index.php.
My php code is grabbing the index.php file with file_get_contents(); which works well. I am also able to edit and save any ".editable" regions in index.php.
My issue:
I have been unable to find a way of "finding" the includes and parse through those for ".editable" regions as well. I am looking for suggestions on how I would work through all the includes in index.php - checking them for editable regions. Would I need to use regular expressions to find "include *.php"? I am unsure of where to even start...
For those of you who may wish to see my PHP code. I am making use of the PHP class: [link text][1] which allows me to write code like:
// load the class and file
$html = new simple_html_dom();
$html->load_file("index.php");

// find the first editable area and change its content to "edited"
$html->find('*[class*=editable]', 0)->innertext = "Edited";

// save the file
$html->save(index.php);

[1]: http://simplehtmldom.sourceforge.net/manual_api.htm simple php dom parser

UPDATE
I have been playing around with regular expressions to try and match the includes. I am pretty rubbish at regex but I think I am getting close. Here is what I have so far:
$findinclude = '/(?:include|include_once|require|require_once)\s*(?:[a-z]|"|\(|\)|\'|_|\.|\s|\/)*(?=(?:[^\<\?]|[^\?\>])*\?>)/i';

This matches fairly well although it does seem to return the odd ) and ' when using preg_match. I am trying to add a bit of security into the regex to ensure it only matches between php tags - this part: (?=(?:[^\<\?]|[^\?>])*\?>) - but it only returns the first include on a page. Any tips on how to improve this regular expression? (I have been at it for about 6 hours)

A: What type of system are you creating?
If it's going to be used by the public, you'd have serious security concerns. People could include their own PHP code or JavaScript in the supplied content.
This isn't the standard way at all to create dynamic content. For most purposes, you'd want to create a single template, and then allow users to save their changes into a database. You'd then fill in the info into the template from the database for display.
If you allow them to include HTML use something like html purifier to clean it up, insert the data into your database with a prepared statement using PDO. I'm sure people here would be happy to answer any questions you may have about using a database.

A: I've misunderstood you, disregard everything after the hr.
To do what you want I guess the simplest way is to present the page to the browser, build some kind of javascript that finds and edits editable areas and submit that to a PHP file via AJAX.
The PHP file would then receive the content and the place where it should change the content, I still don't understand very well how the static CMS do it, but there are some open source projects, check here and here. I suggest you study their code to find out how they do it.

That's really simple, instead of incluiding the file like this:
file_get_contents('/path/to/file.php');

You have to do it like this:
file_get_contents('http://your-host.com/path/to/file.php');

Also, take a look at QueryPath, seems to be a lot better than SimpleHTMLDom.

A: Based on the regex you provided, I've optimized it a bit and fixed some crucial bugs:
~<[?].*?(?:include|require(?:_once)?)\s*?(?:[(]?['"])(.+?)(?:['"][)]?)\s*?;.*?(?:[?]>)?~is

And in preg_match_all():
preg_match_all('~<[?].*?(?:include|require(?:_once)?)\s*?(?:[(]?[\'"])(.+?)(?:[\'"][)]?)\s*?;.*?(?:[?]>)?~is', $html, $includes);

It should match filenames with numbers, digits, dashes, underscores, slashes, spaces, dots and so on.
Also, the filename is stored in reference #1 and the ending PHP tag is optional.
It's worth mentioning that the token_get_all() function is much more reliable than regular expressions.

A: If users can submit content into these and then they get included into a PHP file, then you are in some serious trouble.
You should have simple templates that have little or no PHP in them, which get parsed -- then and only then should you insert content into the DOM, after it has been properly sanitized.
The way to resolve your 'finding the includes' issue -- you don't need to, PHP does that for you -- maybe use ob_start et al. and then include the template file. Then grab the buffer contents (which will be HTML) and then parse the already assembled template with the DOM parser.
Please, please PLEASE make sure that you sanitize whatever you are injecting into the DOM.
Otherwise, tyranny and destruction are certain to rain down upon your web site (and you, depending on what else is on your server).

A: You need to just store the user-inputted text somewhere and load it into, and output it with, your PHP template.
I'd look into learning to use a database. There is nothing heavy-weight or slow about it, and really, this is what they're for. If you don't want to use a database, you can use files instead. I'd suggest storing the data in the file in JSON format to give it some structure.
Here's a very simple system to use files to store and retrieve JSON encoded data.
Make an array of what you want to save after editing
$user_data=array('title'=>$user_supplied_info,'content'=>$user_supplied_words);
$json_data=json_encode($user_data);
file_put_contents('path_to/user_data/thisuser',$json_data);

Then when it's time to display the page
<?php
$user_data=array('title'=>'My page rocks!','content'=>'lorems ipso diddy doo dah');

$file_data=file_get_contents('path_to/user_data/thisuser');
if(!$user_data){$no_data=true;}//file not found
$data_array=json_decode($user_data,true);
if(!is_array($data_array))
  { $no_data=true; }//maybe the json could not be parsed
else
  { $user_data=array_merge($user_data,$data_array); }
?>

<title>This is my page</title>

<?php echo $user_data['title']?>

And so on.  The defaults array holds the standard content for editable sections, which are printed if the user has not supplied any. If they have, it's loaded, and then merged with the default array. The data loaded from a file will overwrite the default array's info, if available, in array_merge part.

A: Ok, I finally worked it out. If anyone is looking to find any include, include_once, require, require_once in a .php file then you can use the following regular expression with a php function like preg_match_all.
'/(?:include|include_once|require|require_once)\s*(?:[a-z]|"|\(|\)|\'|_|\.|\s|\/)*(?=(?:[^\<\?])*\?>)/i';

This looks for any includes etc within  tags. Referencing this back to my original example. My code looks like this:
$html = new simple_html_dom();
$html->load_file("index.php");

$findinclude = '/(?:include|include_once|require|require_once)\s*(?:[a-z]|"|\(|\)|\'|_|\.|\s|\/)*(?=(?:[^\<\?])*\?>)/i';

if (preg_match_all($findinclude, $html,$includes)):

    // shift the array to the left
    $incfiles = $includes[0];
    $i = 0;

    // then loop through the includes array and print our filename
    foreach ($incfiles as $inc) {
       print basename(preg_replace('/[^a-zA-Z0-9\s\.\_\/]/', '', $inc)."\n");
    }
endif;

Job done! I can now work through this to edit each file as required.


text:
Q: Easiest way to convert HVM DomU to PVM? I've got a bunch of Xen 3.4 DomUs that are currently running as HVM because of our infrastructure (Kickstart which doesn't handle Xen PVM yet). Both DomU and Dom0 are RHEL5 machines. If I understand the documentation and configuration correctly, it would suffice to install kernel-xen on the DomUs, replace hvm with pvm in the .xsp files and set the correct boot loader. But has anyone tried this, is this really this easy?

A: You'll probably want to be sure that you have the serial console configured correctly (note that it's hvc0 or xvc0 under paravirt instead of ttyS0).
Depending on the kernel version you may also run into issues with your block devices being force-renamed from hda or sda to xvda. (This happens with paravirt_ops-style kernels; usually 2.6.27 and later, or so).

A: Yep, that's pretty much how you do it.  Nothing particularly exciting about it, I've done it a few times (Debian machines rather than RHEL, but there's no differences that should matter).

A: Don't forget to add hvc0/xvc0 to the /etc/securetty list, if you hope to console in as root.


text:
Q: convert ArrayList> to double [][] in java Please help me in understanding, looking for a solution. I have
ArrayList<ArrayList<double[]>> nwvals = new ArrayList<ArrayList<double[]>>();

And I have double[][] value.
I am setting nwvals to value
setValue(nwvals);

How to convert ArrayList<ArrayList<double[]>> to double[][]?

A: Converting
ArrayList<double[]> nwvals;

to a double[][] will work like this:
double[][] result = nwvals.toArray(new double[0][]);

Example:
import java.util.*;
class Test {
    public static void main(String[] args) {
        List<double[]> nwvals = new ArrayList<>();
        nwvals.add(new double[] { 1.,2.});
        double[][] result = nwvals.toArray(new double[0][]);
        System.out.println(result[0][0]);
        System.out.println(result[0][1]);
    }
}

Converting ArrayList<ArrayList<double[]>> to a double[][][] will definitely require a loop, and so would converting ArrayList<ArrayList<Double>> to a double[][].
There it depends on wich Java version you use - you can do a lot with streams here.


text:
Q: Git: Two local clones of the same repository synchronized between them, both in the same branch I'm working with a repository that has two different lines of development. Therefore, I have two local clones of that same repo in my PC. There are some added folders on each of the clones. Those extra folders are gitignored, and are different in each clone. They are for configuring the different SDKs needed in each case.
Time to time I have to do developments in one clone that affect the other clone too (modifications that have to be tested in both, or even developed in parallel).
The problem I'm having is that if I want to commit something from one of the clones and have it ready in the other, I have to upload it to the repo from one clone, and then download it again in the other.
I'd want to have a solution to avoid that unnecessary upload, maybe having some kind of local synchronization between the two clones.
One workaround would be to use git worktrees, but as worktrees won't let me checkout the same branch in both clones, I have to checkout to another branch in one clone and then checkout again the other clone to the branch I'm working on, which is not so straightforward.
Is this I'm asking possible in any other easier way?


text:
Q: Transferring a single row into an array & echo it into their respective textboxes I'm doing a search function where the user need to input ID number in order to search a person's info. I did search the web on how to do this, but I got stuck when transferring the data back. In my case, I want to transfer every data into their respective textbox. For example :
fullname => fullname textbox
gender => gender textbox

So how do I convert the array into individual php variable and echo it in the textbox? Or there might be any better way? Here is the function on what I've done so far :
function userRetrieve ($cardid) {
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'");
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
    if ($row){
        //What should I do here?
    }
}

Any help would be appreciated. Thank you.

A: Since you are querying only one user do
if ($row){
   $user = new user($row['id'], $row['name'], $row['birthdate'], ...);//if you have a class user,which is adivsable
   //if you do not just save the row or use it like
   echo "User name = " . $row['name'];
}

When you query multiple users you can do
$users = array();
while($row = mysql_fetch_assoc($sql)){//do not call mysql_query twice
   $users[] = new user($row['id'], $row['name'], $row['birthdate'], ...); //if you have a class user,which is adivsable
   //if you do not, just save the whole row
   $users[] = $row;
}

If you use the second option you can access the users like so:
foreach($users as $user){
   echo $user['name'];
}

the values ['here'] should match your column names in the database.
To get the values from the function do
return $row;

Your function should look like:
function userRetrieve ($cardid) {
  $cardid = mysql_real_escape_string($cardid);
  $sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($sql);
  if ($row){
     return $row;
  }
  return false;
}

Now you can call your function like so:
$current_user = userRetrieve(14); //id example, should be a variable
echo $current_user['name'];


text:
Q: All my folders and files on my flash drive have been renamed automatically and I can no longer open them... I need those files I opened up my flash drive this morning and all of my folders and files are normal, except for one folder and all its included files, which is the most important folder. The subfolders and files are renamed with bizarre characters and when I click to open them, a pop-up appears saying it's not accessible and the filename or directory name is incorrect. I don't want to reformat the flash drive because I'd lose all those files. Is there a way for me to restore it or something?
I would attach a screen shot, but apparently new users do not have that privilege. If you have a vague idea of what I'm talking about, let me know and I can email you screenshots so you can have a better understanding. Any help is greatly appreciated!

A: If you are lucky you could solve the problem by simply running a checkdisk on the USB drive (make sure to make a copy of the entire drive before doing this):

*

*Right-click on the USB drive

*Select Properties

*Select the Tools tab

*Select Check now...

*In the Check disk options window that will appear, make sure to select both "Automatically fix file system errors" and "Scan for and attempt recovery of bad sectors"

A: Try Recuva. This may help you. I tried Recuva and it helped me.
Recuva is a freeware Windows utility to restore files that have been accidentally deleted from your computer. This includes files emptied from the Recycle bin as well as images and other files that have been deleted by user error from digital camera memory cards or MP3 players. It will even bring back files that have been deleted by bugs, crashes and viruses.

A: This sort of thing usually happens when you plug in flash disk to old PCs (Pentium IV or lower) or on PC's internal card reader with USB port. Apparently, some old USB controllers (those that were manufactured before 4-GB flash storage were developed) simply do not support USB drives larger than 2GB. As a result, the files get corrupted.
If you can still open those folders and files then I suggest you copy those files to another drive immediately. Before attempting to fix it, copy the files to another drive as backup.To fix, simply run CHKDSK on your flash drive.
If you cannot recover your data through CHKDSK then I suggest you to use a recovery software.
I just found this excellent recovery software TestDisk.
It is called TestDisk and it is a powerful recovery software. It can fix partition tables, FAT, FAT32, NTFS boot sectors, recover deleted files, copy deleted files, and many more. I suggest you go to the website, download, install and give it a try for yourself. It is easy enough to use for experts and novices alike.
Another powerful tool you can use is GetDataBack for NTFS and Fat.
Hope it helps.

A: I had the same problem today. The contents of a USB Flash drive is shown in File Explorer – similar to the experience of OP – is "renamed with bizarre characters". But, different to the OP, the folders are possible to open. However, they are empty. Some of them are hidden (greyed out) and all of them have weird creation dates.
ScreenShot of currupted folders in Explorer.
I was able to get a fix with "PC Inspector File Recovery" Software. It's free, and I have been using it for years to fix deleted or curropted files on FlashCards and FlashDisks the like.
ScreenShot of PC Inspector File Recovery, as it found files and folders.
You have to try different settings, look for logical drives on the physical one, select the drive called
DRIVE (rebuilt), root entreis: 1

then search for data (not files). I was able to find my files. Hope it works!


text:
Q: Linux Shell: useradd options Could anybody give me a little help with the following line:
sudo useradd -c USERNAME new_user | passwd new_user

What I am trying to do is add a new user to the system and set up their password all in one line without having to do two commands. When I enter this line it tells me that the user new_user does not exist. Could anybody help me out here or explain to me why this is not working?
Also if there is a better way of doing this then please feel free to let me know.
Thanks you,
Alex

A: For interactive password entry the one-liner could be:
sudo $SHELL -c "useradd UNAME && passwd UNAME"

For pre-defined password you could do something like:
useradd -p $(mkpasswd --method=sha-512 --rounds=10 SECRET) UNAME

However, I'd suggest against that :)
To learn what encryption method is used on your system you can peek at /etc/shadow: if the hash begins with $6$- it is SHA-512 (as in the example).

A: Just use the -p option to useradd
sudo useradd -c USERNAME -p new_password new_user

A: You can use the -p option of the useradd command, but you need to provide the encrypted password, for example making use of openssl library:
sudo useradd -c USERNAME new_user -p $(openssl passwd -crypt new_user_password)

You can also use other encryption methods but you cannot use a clear password since useradd manual states that -p parameter takes "The encrypted password as returned by crypt(3)".

A: You can also try this one
adduser username;passwd username;


text:
Q: Outlook : Move only read mails to a folder To move all mails in Outlook I use the following code:
var
  App, NS, Inbox, Items, OtherFolder, Item: OleVariant;
  i: Integer;
begin
  App := CreateOleObject('Outlook.Application');
  NS := App.GetNamespace('MAPI');
  NS.Logon;

  Inbox := NS.GetDefaultFolder(olFolderInbox);
  OtherFolder := Inbox.Parent.Folders('Eléments supprimés');

  Items := Inbox.Items;
  for i := Items.Count downto 1 do
  begin
    Item := Items.Item(i);
    Item.Move(OtherFolder);
  end;
end.

Is there a way to move only all read mails to the folder?

A: The simple answer is to use Item.UnRead to determine whether the item has been read, however:

*

*Not all items in a folder are necessarily instances of MailItem that supports the UnRead property. You're using late binding to automate MS Outlook and the code will crash if you try to access UnRead property on an item that doesn't support it.

*There are more effective ways to do it.

To demonstrate the options let's first move away from late binding which makes things somewhat complicated and slower. Add unit Outlook2010 to your uses clause. The source code of the unit is located in OCX\Servers subfolder of RAD Studio installation location. The skeleton of code to process mail items using early binding could then look like this:
uses
  System.SysUtils, System.Variants, Outlook2010;

var
  App: OutlookApplication;
  InboxFolder, OtherFolder: Folder;
begin
  App := CoOutlookApplication.Create;
  App.Session.Logon(EmptyParam, EmptyParam, EmptyParam, EmptyParam);
  InboxFolder := App.Session.GetDefaultFolder(olFolderInbox);
  OtherFolder := (InboxFolder.Parent as Folder).Folders.Item('Eléments supprimés');
  ProcessFolder(InboxFolder, procedure(const Item: MailItem)
  begin
    Item.Move(OtherFolder);
  end);
end.

The naïve implementation of ProcessFolder would be:
type
  TMailItemProc = reference to procedure(const Item: MailItem);

procedure ProcessFolder(const AFolder: Folder; MailItemProc: TMailItemProc);
var
  ItemsToProcess: Items;
  Item: MailItem;
  Index: Integer;
begin
  ItemsToProcess := AFolder.Items;
  for Index := ItemsToProcess.Count downto 1 do
    if Supports(ItemsToProcess.Item(Index), MailItem, Item) and (not Item.UnRead) then
      MailItemProc(Item);
end;

This approach sucks as it has to go through each item in the folder and check its UnRead status. This can cause performance issues when the number of items in the folder is high. But we can do better. Let Outlook do the hard work. And there are multiple ways to do it. The following snippets were inspired by article How to get unread mail in Outlook.
Using Items.Restrict method:
procedure ProcessFolder(const AFolder: Folder; MailItemProc: TMailItemProc);
var
  ItemsToProcess: Items;
  Item: MailItem;
  Index: Integer;
begin
  ItemsToProcess := AFolder.Items.Restrict('[UnRead]=false');
  for Index := ItemsToProcess.Count downto 1 do
    if Supports(ItemsToProcess.Item(Index), MailItem, Item) then
      MailItemProc(Item);
end;

Using Items.Find and Items.FindNext methods:
procedure ProcessFolder(const AFolder: Folder; MailItemProc: TMailItemProc);
var
  ItemsToProcess: Items;
  FoundItem: IDispatch;
  Item: MailItem;
begin
  ItemsToProcess := AFolder.Items;
  FoundItem := ItemsToProcess.Find('[UnRead]=false');
  while Assigned(FoundItem) do
  begin
    if Supports(FoundItem, MailItem, Item) then
      MailItemProc(Item);
    FoundItem := ItemsToProcess.FindNext;
  end;
end;

Using Folders.GetTable method:
procedure ProcessFolder(const AFolder: Folder; MailItemProc: TMailItemProc);
var
  Session: NameSpace;
  Table: OutlookTable;
  LRow: Row;
  FoundItem: IDispatch;
  Item: MailItem;
begin
  Session := AFolder.Session;
  Table := AFolder.GetTable('[UnRead]=false', EmptyParam);
  while not Table.EndOfTable do
  begin
    LRow := Table.GetNextRow;
    FoundItem := Session.GetItemFromID(VarToStr(LRow.Item('EntryId')), EmptyParam);
    if Supports(FoundItem, MailItem, Item) then
      MailItemProc(Item);
  end;
end;


text:
Q: How to explain the motion of these pendulums? Got very interested recently in a  video I saw running thru my feed:
https://www.facebook.com/PortalAECweb/videos/913996365374257/
Well, I got very intrigued about the physics of it and wanted to know your opinion about my guesses and how to proceed regarding them.
I think that basically this mad motion is due to the fact that there's some ratio between the length of these pendulums. I spent a little time thinking and before solving the movement equations thought that maybe I couldn't use the approximation for small angles for that and MAYBE the initial motion would be related to a trasient term (indicating time interval which the system is oscillating for angles greater then 5 degrees) and then go to these repetitive patterns, for smaller angles in which the system is pretty much conservative).
I thought about solving this numerically in Mathematica, plotting multiple pendulums with different lengths.

A: Actually the pendulums swing independently, but one can consider all of them together as a Hamiltonian system. The movie illustrates the Poincare recurrence theorem. It also illustrates quasi-periodic motion  on the Liouville torus in a completely integrable Hamiltonian system


text:
Q: Elastic Search Multiple Filter values for the same field Say that I have to filter cars constructors in a Elastic Search Index (ES 7.15), where the field car_maker is mapped to keyword, having it a limited number of possibilities among car makers string names:
{
    "mappings": {
        "properties": {
            "car_maker": {
                "type": "keyword"
            }
        }
    }
}

GET /cars/_search
{

    "query": {
        "bool": {
            "filter": [{
                "term": {
                    "car_maker": "Honda"
                }
            }]
        }
    }
}

This, along with a matching query will work ok. The filter will not participate to score calculation as desired.
Now I would like to to filter more car makers for that query (let's say a should query):
{
 "query": {
    "bool": {
        "filter" : [
            {"term" : { "car_maker" : "Honda"}},
            {"term" : { "car_maker" : "Ferrari"}}
        ]
    }
 }
}

this is not going to work. I will have any error from ES query engine, but any result too. Of course is always possibile to apply more filters to different fields like car_maker and car_color, but how to do the opposite: apply more values (Honda, Ferrari, etc.) to the same filter field car_maker like in the example above, without conditioning the score calculation?

A: You might want to try the following filter query:
{
  "query" : {
    "bool" : {
      "filter" : {
        "terms" : {
          "car_maker" : ["Honda", "Ferrari"]
        }
      }
    }
  }
}


text:
Q: How to receive dynamic length data from a message queue? I have to send and receive dynamic data using a SysV message queue for a university project.
The length of the data is transmitted in a separate message, size is therefor already known.
And this is how I try to receive the data. I have to admit that I'm not a C++ specialist, especially when it comes to memory allocation.

struct {
    long mtype;
    char *mdata;
} msg;

msg.mdata = (char *)malloc(size * sizeof(char));

msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0);

The problem seems to be the malloc call, but I don't know how to do this right.
EDIT
What I try is to have a some sort of read method in a OO wrapper around the message queues. I'd like to read the data in the message queue into a char[] or a std::string. What I have now looks (simplified) like this.
bool Wrapper::read(char *data, int length)
{
    struct Message {
        long mtype;
        std::string mdata;
    };

    Message msg;
    msg.mdata = std::string(size, '\0');

    if(msgrcv(MSGQ_ID, &msg, size, MSG_ID, 0) < 0)
    {
        return false;
    }

    memcpy(data, msg.mdata.c_str(), msg.mdata.size());

    return true;
}

All I get is segmentation faults or completely corrupt data (although this data sometimes contains what I want).

A: You can't pass a pointer to a structure that contains a std::string member to msgrcv, this violates the interface contract.
The second parameter passed to msgrcv needs to point to a buffer with sufficient space to store a 'plain' C struct of the form struct { long mtype; char mdata[size]; }; where size is the third parameter to msgrcv.
Unfortunately, determining the size of this buffer might depend on size due to possible alignment issues but you have to assume that it doesn't on a system that provides this sort of interface. You can use the standard offsetof macro to help determine this size.
As a vector stores its components contiguously, once you know the size of the buffer, you can resize a vector of char and use this to hold the buffer. Using a vector relieves you of the obligation to free or delete[] a buffer manually.
You need to do something like this.
std::string RecvMessage()
{
    extern size_t size; // maximum size, should be a parameter??
    extern int MSGQ_ID; // message queue id, should be a parameter??
    extern long MSG_ID; // message type, should be a parameter??

    // ugly struct hack required by msgrcv
    struct RawMessage {
        long mtype;
        char mdata[1];
    };

    size_t data_offset = offsetof(RawMessage, mdata);

    // Allocate a buffer of the correct size for message
    std::vector<char> msgbuf(size + data_offset);

    ssize_t bytes_read;

    // Read raw message
    if((bytes_read = msgrcv(MSGQ_ID, &msgbuf[0], size, MSG_ID, 0)) < 0)
    {
        throw MsgRecvFailedException();
    }

    // a string encapsulates the data and the size, why not just return one
    return std::string(msgbuf.begin() + data_offset, msgbuf.begin() + data_offset + bytes_read);
}

To go the other way, you just have to pack the data into a struct hack compatible data array as required by the msgsnd interface. As others have pointer out, it's not a good interface, but glossing over the implementation defined behaviour and alignment concerns, something like this should work.
e.g.
void SendMessage(const std::string& data)
{
    extern int MSGQ_ID; // message queue id, should be a parameter??
    extern long MSG_ID; // message type, should be a parameter??

    // ugly struct hack required by msgsnd
    struct RawMessage {
        long mtype;
        char mdata[1];
    };

    size_t data_offset = offsetof(RawMessage, mdata);

    // Allocate a buffer of the required size for message
    std::vector<char> msgbuf(data.size() + data_offset);

    long mtype = MSG_ID;
    const char* mtypeptr = reinterpret_cast<char*>(&mtype);

    std::copy(mtypeptr, mtypeptr + sizeof mtype, &msgbuf[0]);
    std::copy(data.begin(), data.end(), &msgbuf[data_offset]);

    int result = msgsnd(MSGQ_ID, &msgbuf[0], msgbuf.size(), 0);
    if (result != 0)
    {
        throw MsgSendFailedException();
    }
}

A: Here is an example for SyS. I hope it will help.
The way you are using malloc seems to be correct but you should be very careful when making memory allocations for IPC. You should check how the other process is managing memory (byte alignment, size, platform...)
In your code, What is the purpose of the mtype? Does the size you receive takes this mtype into account? Or is it only the size of mdata?
Update: Is mtype part of the message?
If so:
msgsize = size * sizeof(char) + sizeof(long)
pmsg = malloc(msgsize);
msgrcv(MSGQ_ID, pmsg, msgsize, MSQ_ID, 0);
if not
msg.data = (char *)malloc(size * sizeof(char));
msgrcv(MSGQ_ID, msg.data, size, MSQ_ID, 0);
The mtype is alocated on the stack while the data is allocated on the heap. If the msgreceive makes a kind of memcpy on the given pointer, it will cause some troubles.

A: You seem to be freely mixing C and C++, so I'll do the same.
Note that you probably ought to write the function entirely in C, put it in its own translation unit and then call it from C++, but this should solve your immediate problem.
It seems that the root of your confusion is arguably poor design of the API of msgrcv.  You cannot have the data member of the msg struct be a pointer or a reference or anything other than a raw chunk of memory--msgrcv is going to put the data directly into the structure.

#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/* Caller must ensure that data points to at least length chars */
bool read_msg( char *data, int length )
{
    bool status = false;
    struct msg {
        long mtype;
        char data[ 1 ];
    } *m = (struct msg *)malloc( length + offsetof( struct msg, data ));

    if( m != NULL ) {
        if( msgrcv( MSGQ_ID, m, length, MSQ_ID, 0 ) == length ) {
            memcpy( data, m->data, length );
            status = true;
        }
    }

    free( m );

    return status;
}

A: Root cause
The cause of your segementation error is that memcpy tries to copy a message greater then the size of your struct. Your struct has only room for a long (4 bytes) and a std:string. A string can be a variable size, but only when used as string (and it will automatically allocate memory for this and maintain a pointer).
The std:string variable will look like
struct {
  unsigned int stringlength;
  char *pString;
}

Your code copies into msg, which in this (simplified) example is only 8 bytes long. And you overwrite the pointer with data, which is later interpreted as a memory location.
Solution
A solution is to allocate a memory block large enough to hold both the header (mtype) and the message of size bytes. Since it is only temporary space, I'd suggest to use a stack variable for this. So
 struct msg {
        long mtype;
        char data[ size ];
    }

I suggest to replace size with something more unique and meaningfull if it is a global constant. Please note that size is expressed in bytes; if you need to send a std::string of size characters you'll need to increase the array length with at least sizeof(std::string)+1 (for the structure overhead and the \0 character); better a bit more.

A: The reason for segmentation faults or corrupted data is that you're using an improper message structure for msgrcv() and msgsnd() functions. These functions require the following structure to be used:
struct msgbuf {
    long mtype;     /* message type, must be > 0 */
    char mtext[1];  /* message data */
};

But your Message structure contains an std::string which allocates memory on the heap, but the msgbuf structure expects a memory region starting at mtext[0]. The mtext member is not a pointer, but a char array inside the structure. As the size is unknown, the array is declared as a 1 sized array, but actually the caller shall provide a larger buffer. This technique is also used in some Windows APIs.
For being able to receive messages, you need a buffer
static const unsigned int BufferSize = 256;
char* buffer = new char[ sizeof(long) + BufferSize ];
msgbuf* msg = reinterpret_cast< msgbuf* >( buffer );

Then this msg can be passed to msgrcv(). And don't forget to delete[] the buffer.
Also be aware that the text received in the buffer is not null terminated, unless the 0 character is explicitly written when sending the message. Such non-null terminated text can be used either constructing an std::string from it - e.g. std::string( msg->mtext, len ) or reserving in the buffer one byte for the 0 and write it after receiving the message at the length returned by msgrcv()
Instead of plain char arrays, you could use std::vector which guarantees that the items will be stored in a continuous memory range. The following code can be used in a message receiving loop, which automatically increases the buffer size if the message does not fit into.
static const unsigned int InitialBufferSize = 32;
std::vector<char> buffer( InitialBufferSize );
msgbuf* msg = new (&buffer[0]) msgbuf();
// reserve space in the vector for the mtype member of msgbuf structure
std::vector<char>::size_type available = buffer.size() - sizeof(long);

for(;;)
{
    const ssize_t count = ::msgrcv( MSGQ_ID, msg, available, 0, 0 );
    if( -1 == count )
    {
        if( E2BIG == errno )
        {
            buffer.resize( buffer.size() * 2 );
            msg = new (&buffer[0]) msgbuf();
            available = buffer.size() - sizeof(long);
            continue;
        }
        perror( "Failed to read message from queue" );
        break;
    }

    // handle the received message
    ...
}


text:
Q: Quick Verilog HDL Prompt (Beginner) I am a beginner with Verilog HDL and trying to model a few modules from logic diagrams. If two wires are input into a NAND gate followed by another inverter afterwards, would that just be a AND gate in theory? Since the output wire desired is on the other side of the inverter. Would it be.
AND
    g1(F,A,B)

A and B being the inputs and F being the output.
Also, just for future knowledge, how would I implement an inverter using Verilog?

A: To answer your first question, yes, a NAND gate followed by an inverter is logically equivalent to an AND gate.
On your second question, the normal way to invert a signal in Verilog would be to use the bit-wise negation operator: ~
wire A;
assign A = ~B;  // A is "not B"

Since you are asking about modeling simple logic using Verilog gate primitives, I will add that there is a primitive for an inverter called not.
not U1(A, B);  // A is "not B"

Here is a good reference on Verilog gate primitives.


text:
Q: Not able to run oracle database 12 on kubernetes with persistent volume Hi I am trying to run oracle db 12 on k8s, with a persistent volume, but it's throwing the error below. please what I am missing

*

*I have created a pv/pvc, mount path /opt/oracle/oradata

*permissions to uid 54321 are provided
Listener Log File         /opt/oracle/diag/tnslsnr/oracledb-c6867b8cf-v6bnf/listener/alert/log.xml
  Listening Endpoints Summary...
    (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1)))
    (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=0.0.0.0)(PORT=1521)))
  The listener supports no services
  The command completed successfully
  [WARNING] [DBT-10328] Specified GDB Name (ORCLCDB) may have a potential conflict with an already existing database on the system.
     ACTION: Specify a different GDB Name that does not conflict with existing databases on the system.
  [FATAL] [DBT-10317] Specified SID Name (ORCLCDB) already exists.
     ACTION: Specify a different SID Name that does not already exist.
  SQL>    ALTER SYSTEM SET control_files='/opt/oracle/oradata/ORCLCDB/control01.ctl' scope=spfile
  *
  ERROR at line 1:
  ORA-01034: ORACLE not available
  Process ID: 0
  Session ID: 0 Serial number: 0

  SQL>    ALTER PLUGGABLE DATABASE ORCLPDB1 SAVE STATE
  *
  ERROR at line 1:
  ORA-01034: ORACLE not available
  Process ID: 0
  Session ID: 0 Serial number: 0

  SQL> BEGIN DBMS_XDB_CONFIG.SETGLOBALPORTENABLED (TRUE); END;

  *
  ERROR at line 1:
  ORA-01034: ORACLE not available
  Process ID: 0
  Session ID: 0 Serial number: 0

  SQL> Disconnected
  mv: cannot stat '/opt/oracle/product/12.2.0.1/dbhome_1/dbs/spfileORCLCDB.ora': No such file or directory
  mv: cannot stat '/opt/oracle/product/12.2.0.1/dbhome_1/dbs/orapwORCLCDB': No such file or directory
  The Oracle base remains unchanged with value /opt/oracle
  #####################################
  ########### E R R O R ###############
  DATABASE SETUP WAS NOT SUCCESSFUL!
  Please check output for further info!
  ########### E R R O R ###############

please what I am missing. can be related to env
where can I find more logs


text:
Q: Java AWS SDK S3 upload performance I'm using TransferManager to upload some files to S3.
    TransferManager tm = new TransferManager(creds);
    t.upload = tm.upload(bucket, k.key, new File(k.path));

The only issue is that I can only get about 1MB/s of upload. If I run 10 different file uploads concurrently, each gets about 100KB/s. Using the AWS console to drag and drop a file, I get about what is expected of my connection speed: 8MB/s.
To further complicate things, I'm on us-east-1, but if I test it on us-west-2, I get better speeds (I'm in Oregon), but still not what I get via the AWS console.
I'm using the same Windows 7 laptop for both the Java upload and AWS console (using the latest Chrome).

A: Changing the max threads (I didn't get much better performance past 64; it seems the default was 10) seemed to do the trick. You can do it like so:
    TransferManager tm = new TransferManager(
            new AmazonS3Client(creds),
            Executors.newFixedThreadPool(THREAD_COUNT));

Note how I had to use a different constructor for TransferManager, but this did not require reworking anything (i.e., it was a drop-in replacement).


text:
Q: SSIS package won't save SQL command I am updating an SSIS package and modifying the SQL command of a lookup transformation, but have found that the command won't save. I will update the command, close the editor, save the package, close and re-open Visual Studio (Professional 2015), but my changes are not preserved. There is a config file (.dtsConfig) for the package in which I have made the changes as well, but still no dice. Changes to the project, such as variables and connection managers and their use within the package (save for the SQL command) are, however, maintained.
What reasons might there be for why this package won't let me save updated SQL commands?

A: I am still unsure of why this situation was occurring, but opening the lookup in the advanced editor and modifying the SqlCommand and SqlCommandParam fields allowed preservation of my changes.

A: In addition to saving the package, be certain to also run a build.  This recreates the .dtsx package file with the new changes.  Your question did not mention having done this very important step.

A: That isn't answering the question, but provides you a guideline on how to troubleshoot the problem:
After the change do a right click on a package and view a code in XML. Look for your "SQL statement" is it there?
Copy/paste XML into separate file, save and close the solution. Reopen it and see if code has changed. Compare the changes.


text:
Q: JSON-output formats in REST I have a structure similar to this, that is returned by a REST Api:
{
    "id": 1,
    "type": "A",
    "name": "blah, blah"
}

The natural output sample is as follows:
[
    {
        "id": 1,
        "type": "A",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "A",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "B",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "C",
        "name": "blah, blah"
    }
]

For convenience, I would rather have the outout in the grouped format (around the "type"), like this:
{
    "A": [
        {
            "id": 1,
            "name": "blah, blah"
        },
        {
            "id": 1,
            "name": "blah, blah"
        }
    ],
    "B": [
        {
            "id": 1,
            "type": "B",
            "name": "blah, blah"
        }
    ],
    "C": [
        {
            "id": 1,
            "type": "C",
            "name": "blah, blah"
        }
    ]
}

Is there a common, REST-friendly way to do this in terms of input parameters?
I've though of a parameter "response_mode" which could be FLAT or GROUPED, but am not sure if it is ok from the RESTful viewpoint.

A: In php I would sort it like so:
<?php

$response = '[
    {
        "id": 1,
        "type": "A",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "A",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "B",
        "name": "blah, blah"
    },
    {
        "id": 1,
        "type": "C",
        "name": "blah, blah"
    }
]';

$jsonDecoded = json_decode($response);
$newResponse = array();

foreach($jsonDecoded as $jd) {
   $newResponse[$jd->type][] = array(
      "id"   => $jd->id,
      "type" => $jd->type,
      "name" => $jd->name
   );
}

echo json_encode($newResponse);


text:
Q: how i can get custom attribute value in magento 2 final_price.phtml I have created a product attribute in Magento 2 admin

I want to
  get custom attribute price in magento 2 final_price.phtml

How I can get this??
I tried this code but
showing null in $_product
<?php
$_product = $block->getProduct();
$attvalue = $_product->getResource()->getAttribute('attribute_id')->getFrontend()->getValue($_product);
echo $attvalue;
?>

final_price.phtml
<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

?>

<?php
/** @var \Magento\Catalog\Pricing\Render\FinalPriceBox $block */
// Daily deal Helper
$helper=$this->helper('Smartwave\Dailydeals\Helper\Data');

$productId = $block->getSaleableItem()->getId();

/** ex: \Magento\Catalog\Pricing\Price\RegularPrice */
/** @var \Magento\Framework\Pricing\Price\PriceInterface $priceModel */
$priceModel = $block->getPriceType('regular_price');

/** ex: \Magento\Catalog\Pricing\Price\FinalPrice */
/** @var \Magento\Framework\Pricing\Price\PriceInterface $finalPriceModel */
$finalPriceModel = $block->getPriceType('final_price');
$idSuffix = $block->getIdSuffix() ? $block->getIdSuffix() : '';
$schema = ($block->getZone() == 'item_view') ? true : false;
?>

<?php
//echo "TT001";
?>
<?php
$_product = $block->getProduct();
//$attvalue = $priceModel->getResource()->getAttribute('mrp_price')->getFrontend()->getValue($_product);
//echo $attvalue;
?>

<?php if($helper->isDealProduct($productId)) : ?>

    ?>
    <?php
        $deal_final_price_amount = number_format($helper->getDealproductbyId($productId),2);
    ?>

            Special Price
            <span id="product-price-<?php echo $idSuffix; ?>" data-price-amount="<?php echo $deal_final_price_amount; ?>" data-price-type="finalPrice" class="price-wrapper ">
                <?php echo $helper->getcurrencySymbol().''.$deal_final_price_amount; ?>

        <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
            'display_label'     => __('Regular Price'),
            'price_id'          => $block->getPriceId('old-price-' . $idSuffix),
            'price_type'        => 'oldPrice',
            'include_container' => true,
            'skip_adjustments'  => true
        ]); ?>

<?php elseif ($block->hasSpecialPrice()): ?>

        <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
            'display_label'     => __('Special Price'),
            'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
            'price_type'        => 'finalPrice',
            'include_container' => true,
            'schema' => $schema
        ]); ?>

        <?php /* @escapeNotVerified */ echo $block->renderAmount($priceModel->getAmount(), [
            'display_label'     => __('Regular Price'),
            'price_id'          => $block->getPriceId('old-price-' . $idSuffix),
            'price_type'        => 'oldPrice',
            'include_container' => true,
            'skip_adjustments'  => true
        ]); ?>

<?php else : ?>
    <?php /* @escapeNotVerified */ echo $block->renderAmount($finalPriceModel->getAmount(), [
        'price_id'          => $block->getPriceId('product-price-' . $idSuffix),
        'price_type'        => 'finalPrice',
        'include_container' => true,
        'schema' => $schema
    ]); ?>
<?php endif; ?>

<?php if ($block->showMinimalPrice()): ?>
    <?php if ($block->getUseLinkForAsLowAs()):?>
        <a href="<?php /* @escapeNotVerified */ echo $block->getSaleableItem()->getProductUrl(); ?>" class="minimal-price-link">
            <?php /* @escapeNotVerified */ echo $block->renderAmountMinimal(); ?>

    <?php else:?>

            <?php /* @escapeNotVerified */ echo $block->renderAmountMinimal(); ?>

    <?php endif?>
<?php endif; ?>

A: You can get custom product attribute value in final_price.phtml using following code
<?php

$_product = $block->getPriceType('final_price')->getProduct();
$attvalue = $_product->getCustomAttribute('attribute_id')->getValue();

?>


text:
Q: Assessing Whether the Series $\sum_\limits{n = 0}^\infty (-1)^n x^{2n} = 1 - x^2 + x^4 - x^6 + \dots$ Converges (conditional/absolute) or Diverges? It's been a while since I've used the various tests for convergence (conditional/absolute) and divergence, and I can't remember which test needs to be used and how to assess whether the series $\sum_\limits{n = 0}^\infty (-1)^n x^{2n} = 1 - x^2 + x^4 - x^6 + \dots$ converges (conditionally/absolutely) or diverges?
I would appreciate it if people could please explain the test that I need to use, why this test needs to be used (within this context), and how it is used (within this context).
Addition:
From Thomas's Calculus, 14th Edition:

A: $$\sum_\limits{n = 0}^\infty (-1)^n x^{2n} = 1 - x^2 + x^4 - x^6 + \dots$$
is a geometric series which converges to $$\frac {1}{1+x^2}$$ for $|x|<1$ and diverges otherwise.


text:
Q: Mediawiki/wikipedia text format issue so i got an issue with text formatting and i have no idea how this problem is called or what i should search after, so i thought i try to explain it here.
It's literally nothing dramatic or should take long, i simply want to write stuff like
''italic'' or '''bold'''

without that it actually gets italic or bold... i literally want
''italic''

to be displayed. I've also tried to use code blocks but even within the blocks it writes italic then.. i'm sure there is a <..> command but i simply can not find it
Does anyone know?

A: try this:
<nowiki>''italic''</nowiki>


text:
Q: SSL mixed content warnings. I can't make the other server that I request from have SSL. What are my options? So, I have an app on one server that I've configured to have SSL. However, it makes a bunch of API calls to another one of my servers, but that server has more than one service and no SSL. I know for a fact that if I add SSL to the second server, a lot of the apps on it will break and I don't want to have the downtime of those apps/webpages. The first server isn't in production yet, but the second one is and has multiple pages/apps.
My setup is basically this:
First server:
superwebpage.coolexample.com

and this ^ server (with SSL) makes API calls to api from the server (without SSL) below:
myweb.example.com/api
myweb.example.com/app2
myweb.example.com/anotherimportantwebpage
myweb.example.com/importantwebpage

However, my application from the first server is obviously breaking because all of the API calls aren't secure and I just get a bunch of mixed content warnings.
The reason server 2 doesn't have SSL is because I just didn't need it because no important information is being transferred until now.
My question, broadly, is what are my options? I want to avoid taking the second server down for however long it's going to take to fix all the errors that'll occur from each app/webpage that I have up on the server. I also want to have SSL on the first server because users will be logging in with passwords.
More specifically, can I make just that one folder serve https without affecting the other folders? I think that'd fix the problem, but I'm not sure it's possible.

A: You don't have to change the HTTP site to add HTTPS. Just add a VirtualHost for port 443, point the DocumentRoot to the same directory and you are all set:
<VirtualHost *:80>
    ServerName yourserver.com
    DocumentRoot /var/www/yourserver.com
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot /var/www/yourserver.com
    ServerName your-domain.com
    SSLEngine On
    SSLOptions +StrictRequire
    SSLCertificateFile /some/directory/server.crt
    SSLCertificateKeyFile /some/directory/server.key
    SSLProtocol TLSv1
</VirtualHost>

Restart Apache and you will have HTTPS and HTTP running at the same time.


text:
Q: .each jQuery captures the last elements only in this form I want to show a warning popup when a class named '.reqF' is not filled and send the form to action page when all the '.reqF' are filled..
This is my form
<form method="post" class="flat-p-form p-form-flat-extra5color4" action="/payment-verify-before-submit-multiple-students/" data-js-validate="true" data-js-highlight-state-msg="true" data-js-show-valid-msg="true" style="margin: 30px 0;" id="paymentForm" >

    <input type="text" name="parentName" placeholder="Parent Name" required class="form-control reqF" value=""/>
    <input type="text" name="payee_email" placeholder="Email" required class="form-control reqF" value=""/>
    <input type="text" name="parentMobile" placeholder="Mobile No" required class="form-control reqF" value=""/>

    <input type="text" id="sudentname" name="sudentname[]" placeholder="Student Name" required class="form-control reqF" />
    <input type="text" id="admissionnmbr" name="admissionnmbr[]" placeholder="Admission No"  class="form-control reqF" required />
    <select id="budget" name="purpose[]" class="form-control reqF" required>
        <option class="p-select-default" value="">--Type--</option>
        <option value="SchoolFees">School Fees </option>
        <option value="BoardingFees">Boarding Fees</option>
    </select>
    <input type="text" id="amount" name="amount[]" placeholder="Amount" required class="form-control reqF inputChangeVal" data-js-input-type="number" />
    <select name="Grade[]" id="grade" class="form-control reqF" required>
        <option class="p-select-default" value="" >-- Grade --</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
        <option value="5">5</option>
        <option value="6">6</option>
        <option value="7">7</option>
        <option value="8">8</option>
        <option value="9">9</option>
        <option value="10">10</option>
        <option value="11">11</option>
        <option value="12">12</option>
        <option value="13">13</option>
    </select>

  <button class="btn add_another_st_btn" style="float: right;">ADD ANOTHER STUDENT</button>

        Total Amount

        <input type="text" class="totalAmount" id="updatedTotalAmount" style="font-size: 20px; font-weight: bold; margin-bottom: 25px; text-align: right; border: 0;" readonly />

    <button class="btn" class="confirm" type="submit" name="confirm" id="payBtn"> Pay Now</button>

                    <button type="button" class="close" data-dismiss="modal">×</button>

Proccess Payment

                    "Your about to make a online payment. Click 'Edit' to review the data before proceeding or click 'Continue' to confirm the details for payment."

                    <button class="btn btn-default" data-dismiss="modal">Edit</button>
                    <button class="btn btn-primary" id="continuebtn">Continue</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

                    <button type="button" class="close" data-dismiss="modal">×</button>

All required fields should be filled.

                    "Following fields should be filled for all the students you've added"

Student Name

Admission No.

Grade

Payment Type

Amount

                    <button class="btn btn-default" data-dismiss="modal">UPDATE</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

</form>

And this is my jquery:

but the thing is it shows the #myModalforErrorMsg box only if the last element / grade is not filled up.
I am able to submit the form only after fill the grade and when I left other .reqF fields are empty..
why is that??
Sometimes it works on local host but never in WordPress..
What I am missing?

A: There is problem in this snippet
                jQuery('.reqF').each(function() {
                    if (jQuery(this).val() === '') {
                        console.log('error');
                        empty = false;
                    } else empty = true;
                });
                if (empty == true)
                    jQuery('#myModal').modal('toggle');
                else
                    //console.log('your error message');
                    jQuery('#myModalforErrorMsg').modal('toggle');

Since, you are iterating through all elements, If last one is filled empty becomes true and hence error doesnt show. What you want is if any of the empty is false you show show error.
You can modify if loop as below to make it work. Initialize empty as true.
                    if (jQuery(this).val() === '') {
                        console.log('error');
                        empty = empty && false;
                    } else empty = empty && true;


text:
Q: Why my validation accuracy and AUC are higher than my training accuracy and AUC? I have a binary classification problem and I use LightGBM classifier to build my model based on 5 features. I divided my dataset (94 observations) into two parts:

*

*Training dataset: 60 observations

*Validation dataset: 34 observations

I use only my training dataset to tune hyperparameters of LightGBM classifier by using GridSearchCV and 5-fold cross-validation. Then I test my model in terms of accuracy and AUC on the validation dataset and these are the results:
Accuracy score (train): 0.633
Accuracy score (validation): 0.706
ROC AUC (train): 0.791
ROC AUC (validation): 0.869
You see my AUC of validation dataset is higher than my training! It seems surprising to me and I think something is wrong here. I never exposed validation dataset to GridSearchCV or any other step to build my classifier. My question is: Is it logical to have a higher ROC AUC on validation dataset in comparison to training dataset or something is wrong here obviously that I can't see it. Any idea or suggestion is appreciated.
Update
I used a different random split and these are my results:
Accuracy score (train): 0.767
Accuracy score (validation): 0.706
ROC AUC (train): 0.838
ROC AUC (validation): 0.735
Now, it's opposite and my training ROC AUC and accuracy are higher than validation dataset. Any idea or suggestion? Am I seeing a huge instability in my model due to these results?

A: There is no discrepancy here, uncertainty due to the small number of tested cases is more than sufficient to explain the situation:
As a quick check of the situation, we can calculate binomial confidence intervals (for the moment ignoring that there may be additional random uncertainty due to model instability) for accuracy based on number of tested cases:
training: $63.3 \% = \frac{38}{60}$. 95% confidence interval 50 - 74 %
validation: $70.6 \% = \frac{24}{34}$. 95% confidence interval 54 - 84 %
With that overlap in the confidence intervals, there's no way to argue that the validation set accuracy is actually higher than trainins set accuracy.
Note that this also means that your sample size is too small to make meaningful comparisons of the predictive performance in order to select the best model unless the difference in the models is huge. To get an idea about the sample sizes needed, have a look at our paper
Beleites, C. and Neugebauer, U. and Bocklitz, T. and Krafft, C. and Popp, J.: Sample size planning for classification models. Anal Chim Acta, 2013, 760, 25-33.
DOI: 10.1016/j.aca.2012.11.007
accepted manuscript on arXiv: 1211.1323
Nevertheless selecting the apparently best model will tend to produce overfitting as your decision heavily influenced by the random uncertainty of your test results: if you take many different models that truly have the same predictive performance, and measure their performance only roughly, you'll still observe better and worse performance estimates. But picking among them cannot produce any truly better model. Almost the same happens if you have models that differ so little in their predictive performance that you cannot reliably detect the difference given your sample size.
This is overfitting in the very sense of the word - actually, it's what I'd consider one of the textbook situations of overfitting.
What you can and should do, though, is measuring model stability. That can be done even if the random uncertainty for the overall accuracy etc. is large due to your small sample size:
Beleites, C. & Salzer, R.: Assessing and improving the stability of chemometric models in small sample size situations Anal Bioanal Chem, 2008, 390, 1261-1271.
DOI: 10.1007/s00216-007-1818-6
This would require changing the outer train/test split into a repeated cross validation. As you did the train-test split yourself (as opposed to, say, having a clinical study where patients have been assigned to train and test arms beforehand), repeated cross validation is much better here anyways as it will lead to each and every sample being tested (and thus helping to narrow the random uncertainty: the same 70.6 % accuracy observed in a cross validation comprising all 94 cases would have 95 % ci 61 - 79 %).
Once you know whether your models are stable or not, you can choose a strategy to improve them based on this information. E.g. if they are, you may consider moving from boosting to more restrictive models or even bagging.

There are approaches to improve the grid search selection procedure (e.g. better behaved figure  of merit: a proper scoring rule, and choosing the least complex model that's better than the apparently best performance taking into account random uncertainty on that see here) - but they cannot work miracles. Still back-of-the-envelope of your accuracy, such a least complex model would have only slightly better than guessing performance which is most probabaly not an acceptable result for your application.
I think it very likely that even with a more stable training algorithm than boosting and a proper scoring as your figure of merit, you may find that your data set just doesn't have the required information content to allow data-driven tuning of model parameters. Thus, you may be overall better off using either a modeling algorithm that doesn't need tuning or one that can be tuned by your expert knowledge about your data and the algorithm.


text:
Q: Merge lots of rasters in r using do.call I am dealing MODIS MOD15A2H datasets and want to merge all the tiles of layer one together. I use gdal_translate() to convert .hdf layer into .tif file. And try to use do.call(merge, tiflist) to merge (see here). I find it so wield that the value of cells would change when the length of list is more than 5. (Update: I find there's nothing to do with 5. Sometimes it goes wrong with 4 files while arbitrary three of them go well. But for other files, there is no such problem.) Could anyone help with that? Just don't know why and in which situation do.call has such problem.
I change fun from mosaic to merge in my case since there is no overlapping problem.
#transform to tif
for (i in 1:length(hdffilenames)){
  gdal_translate(sdsnames[i,1], dst_dataset = paste("fpar_",substr(sdsnames[i,1],37,42),".tif",sep = ""))}
tifnames=paste("fpar_",substr(sdsnames[,1],37,42),".tif",sep = "")
h=as.integer(substr(sdsnames[,1],38,39))
subtifnames=list()
for (i in seq(1:36)){
  subtifnames[i]=tifnames[h=i]
}

#merge function
mergetifList <- function(tifList){

  #Internal function to make a list of raster objects from list of files.
  ListRasters <- function(list_names) {
    raster_list <- list() # initialise the list of rasters
    for (i in 1:(length(list_names))){
      tif_name <- list_names[i] # list_names contains all the names of the images in .tif format
      raster_file <- raster::raster(tif_name)
      raster_file[raster_file>1] <- NA
    }
    raster_list <- append(raster_list, raster_file) # update raster_list at each iteration
    return(raster_list)
    }

  #convert every raster path to a raster object and create list of the results
  raster.list <-sapply(tifList, FUN = ListRasters)

  # edit settings of the raster list for use in do.call and merge
  names(raster.list) <- NULL
  #####This function deals with overlapping areas
  #raster.list$fun <- max
  #run do call to implement mosaic over the list of raster objects.
  mergeRas <- do.call(raster::merge, raster.list)

  return(mergeRas)
}

and then I use some lists to test:
 > tifname1=c("fpar_h29v09.tif", "fpar_h29v10.tif", "fpar_h29v11.tif", "fpar_h29v12.tif", "fpar_h29v13.tif")
    > m_1=mergetifList(tifname1)
    > plot(m_1)

see picture here
> tifname2=c
("fpar_h29v08.tif", "fpar_h29v09.tif", "fpar_h29v10.tif", "fpar_h29v11.tif", "fpar_h29v12.tif")
> m_2=mergetifList(tifname2)
> plot(m_2)

see picture here
> tifname3=c("fpar_h29v08.tif", "fpar_h29v09.tif", "fpar_h29v10.tif", "fpar_h29v11.tif", "fpar_h29v12.tif","fpar_h29v13.tif")
> m_3=mergetifList(tifname3)
> plot(m_3)

see picture here
Thanks very much!


text:
Q: Setting up transparent mode in mitmproxy I am trying to set up mitmproxy in transparent mode.
My ultimate goal is to reverse engineer the API used by an Android app. The reason that I have to use transparent mode is because Android apps refuse to work when they detect a regular proxy.
Here is the relevant documentation: https://docs.mitmproxy.org/stable/concepts-modes/
How do I create the direct phone-computer connection that they show in the diagram?
I don't understand how it is possible to simply skip the router, especially since transparent mode isn't supposed to require any special configuration.


text:
Q: Show Child form separately in task I have main form and child form. when my child form opens from button in main form, it shows behind the main form icon in taskbar.
How can i show the child form as separate icon in taskbar
here is the code i am using

    child childform = new child();

    childform.Show();

as shown in above image now the child form shows behind the main form in taskbar.
What i need is child form to show separate icon in taskbar


text:
Q: Get one single GMaps Coordinate from Lat and Lng I am using the Google Maps API v3 and I'd like to get the distance between the map center and and right border of the bounding box.
My current code looks like this:
var EX1 = map.getCenter();
var EX2 = "(" + map.getCenter().lat() + ", " + map.getBounds().getNorthEast().lng() + ")";
var Radius = google.maps.geometry.spherical.computeDistanceBetween(EX1, EX2) / 1000;
alert(EX1);
alert(EX2);
alert(Radius);

EX1 and EX2 seem to have the same format, the coordinates of EX2 look correct, but the Radius alert always shows NaN (it works fine with var EX2 = map.getBounds().getNorthEast();).
Is there a way to get the distance between the center and the right border?
Thanks,
Timon

A: EX2 is a string.  EX1 is a google.maps.LatLng object which has a method to convert it to a string.  They are not "the same format".  This should work (not tested):
var EX1 = map.getCenter();
var EX2 = new google.maps.LatLng(map.getCenter().lat(),map.getBounds().getNorthEast().lng());
var Radius = google.maps.geometry.spherical.computeDistanceBetween(EX1, EX2) / 1000;
alert(EX1);
alert(EX2);
alert(Radius);


text:
Q: Downgrading from Ruby 2.2.2 to Ruby 2.1.6 I am a beginner Rails developer and I kept encountering this problem when I tried to do   "rails server"   on the command prompt, I keep getting an error:
"in 'require': cannot load such file -- nokogiri/nokogiri (LoadError)"
I searched online and apparently nokogiri is currently not supported for Ruby 2.2.2 (the version I am currently using).
I am currently working in Ruby 2.2.2, Rails 4.2.3, and gem v. 2.4.8 on a Windows 8.1 PC.
Is there anything I can do to circumvent this problem? Right now, I'm thinking the easiest way would just be to downgrade to Ruby 2.1.6 and go from there. Would anyone be willing to tell me just how to do that? I used RubyInstaller but I don't know if installing Ruby 2.1.6 on top of Ruby 2.2.2 would mess anything up in my system. Is there a way to automatically downgrade anything?
Thanks in advance and if there's another easier way other than downgrading please let me know!
P.S. I tried downgrading the gem version and then I realized that it doesn't actually change the Ruby version.

A: You can just delete the folder 2.2.2 was installed and re-install the older version. Just double check the PATH variable if it correctly points to the re-installed ruby path.


text:
Q: Can I use distributionmanagement in maven to distribute a directory of files? I've got a maven project which generates a set of resources files using some plugins defined in a pom.xml. I'd like to use something like distributionManagement to push these generated files to a branch in Git. I can see that I can use something like Apache Wagon to do the distribution but the distributionManagement settings seem to only cater for the repository, site and relocation elements.
Is there a way of adding some custom distributionManagement elements, or can anyone suggest another way of pushing my generated resources to a git branch?

A: Use a usual maven project, put the generated of the resources into the generate-resources life-cycle phase and package the result into a jar file and finally use the usual deployment (** mvn deploy **) or in relationship with creating a release to transfer the resulting artifacts into a maven repository.


text:
Q: Connecting Docker Postgres container to an existing empty database I want to create a tarball that contains an empty db (ie a series of empty tables) and a shell script launching a Postgres container that would connect to the empty db.  The end product is a .tar.gz that has a copy of the db, a start script and a stop script.  All this is meant to work in macOS
To create the db I started a Postgres server locally on my laptop and created a db called 'postgres-15year'.  Using 'DBeaver' database manager and 'psql' at the CLI I can see that the dbase is correctly created and functional.
I then created the following scripts:
start.sh
#!/bin/bash
echo $(pwd)
docker run --rm --name payments-15years -e POSTGRES_PASSWORD=docker -d -p5432:5432 -v$(pwd)/postgres-15year/data:/var/lib/postgresql/data:delegated postgres:11.6

stop.sh
#!/bin/bash
docker stop payments-15years
echo "docker stop payments-15years"

I then put all this in a directory that I would like to tarball.

So user would receiver the tarball, unpack it and run the start script and be able to connect to a db that has a predefined structure and schemas.  Here is what I think 'my start.sh' script is doing:

*

*creating a container name 'payments-15years'

*setting the db password for a generic user ('postgres')

*setting the db port to 5432 and also mapping it to local server port
5432 (not sure if that's necessary but all the examples seem to do
it)

*mapping the db to the container's var/lib and 'delegated' as opposed
to 'cache' so changes persist

*specifying the Postgres docker image as 11.6

My challenge is that after running the start script 'docker ps' returns:
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                    NAMES
14d2cba6abe2        postgres:11.6       "docker-entrypoint.s…"   44 seconds ago      Up 42 seconds       0.0.0.0:5432->5432/tcp   payments-15years

But when I do so and then run 'psql' from CLI:
docker exec -it payments-15years psql -U postgres

the database ('postgres-15year') is not listed.
Does anyone see what is wrong with my approach?
NOTE:

*

*I am not providing the db, however it is empty tables with schemas
defined and all the above scripts and pictures should be sufficient
to recreate the problem.

*Closest stack answer I found was here but it didn't help.

A: Actually when you ran the command with -v $(pwd)/postgres-15year/data:/var/lib/postgresql/data:delegated, According to the official documentation of the postgres-docker.

The -v /my/own/datadir:/var/lib/postgresql/data part of the command mounts the /my/own/datadir directory from the underlying host system as /var/lib/postgresql/data inside the container, where PostgreSQL by default will write its data files.

So you are just creating a data directory not a database. You can check it by using inspect keyword.
docker container inspect <container_name>

In your scenario payments-15years gives volume details of this,
"Mounts": [
            {
                "Type": "bind",
                "Source": "/Users/macair/postgres-15year/data",
                "Destination": "/var/lib/postgresql/data",
                "Mode": "delegated",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],

To create a database execute a interactive session as did before and create a db manually or try this.
docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres

A: Reference to your comment first,
I was able to create the DB using interactive. To populate the empty db with the proper schema I have a pg-dump file (.sql). I'm not sure how to make that file available to the container. Thoughts?
If you have dump file why one should bother to run the command once container up?
Better to make it part of Dockerfile and you will not need to and dump manually Docker image will take care of it.
FROM postgres
ADD mydb.sql /docker-entrypoint-initdb.d

Now if you up the container the DB will be populated automatically.
Initialization scripts

If you would like to do additional initialization in an image derived
  from this one, add one or more *.sql, *.sql.gz, or *.sh scripts under
  /docker-entrypoint-initdb.d (creating the directory if necessary).
  After the entrypoint calls initdb to create the default postgres user
  and database, it will run any *.sql files, run any executable *.sh
  scripts, and source any non-executable *.sh scripts found in that
  directory to do further initialization before starting the service.

postgress init DB
Now come to your question, you can do that with Tarball, tar does not deal with volume while Postgres docker image come with volume. so you need to follow the Dockerfile to import on Data on startup.


text:
Q: How do I use the $A= Pe^{rt}$ formula in this question? So the question is
in $2000$ the deer population in a certain area was $800$. The number of deer increases exponentially at a rate of $7%$ per year. Predict the population in $2009$.
a) $1408$
b) $1434$
c) $1471$
d) $1492$
but no matter how I try to plug in the numbers I keep getting $1502$!!! I know the answer is c but i don t get that answer no matter that i try.
I know
$p = 800$
$r= 0.07$
$t= 9 \space years$
$e = to \space  calc  \space number$
thanks for any help!!!!

A: The correct answer can be computed most simply as $800(1.07)^9$.
If you really want to use PERT, the continuous growth rate $r$ satisfies $e^r=1.07$, so $r=\ln(1.07)$. With that value of $r$, the calculation of $e^{9r}$ will also give the right answer.

A: Are you sure the question said that the population grows exponentially?
Because if it grew exponentially, you would be correct:
$$ A = P * e^{rt} = (800) * e^{(0.07)(9)} \approx 1502 $$
But if it didn't, you would use $A = P\left(1+\frac{r}{100}\right)^t$:
$$ A = P\left(1+\frac{r}{100}\right)^t = (800)(1.07)^9 = 1471 $$
where the correct choice would be (c), as you said.


text:
Q: Format a number in Excel When I have this as input
1234567890123

I want it to be displayed as
12 3456789012 3

Is this at all possible? My attempts so far were unsuccesful.

A: Select the cells you want and go to Format Cells > Number > Custom. Inside the Type box, enter the following expression:
## ########## #

Click OK, and you're done.
If you want to know more about Excel's Custom Number Formatting, see the answers to this question.


text: Q: Internal Site search using ASP.NET C# Web Form I need to search all my pages using one single text box and one single button to my ASP.NET web site form. I searched in google not find any use full code or links.


text:
Q: Call to a member function save() on null I am using the following code
public function show()
{

    $id = Auth::user()->id;
    $usuario = User::find($id);
    $mascotin = Mascota::all();
    $mascota = Mascota::find($id);
    $mascota->save();

    $cant_mascota = Mascota::count();
    $cant_pregunta = Pregunta::count();

    return view('usuario.show',[
        'usuario' => $usuario,
        'mascotin' => $mascotin,
        'mascota' => $mascota,
        'cant_mascota' => $cant_mascota,
        'cant_pregunta' => $cant_pregunta,
    ]);
}

It gives me this error
 Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR).Call to a member function save() on null

User Model
public function mascotas(){
    return $this->hasMany('App\Mascota','user_id', 'id');

}

Mascota Model
public function usuario()
{
    return $this->belongsTo('App\User', 'id','user_id');

}

Route
Route::get('/home', 'UserController@show')->name('home');

Hope you guys can help me, I'm new in laravel and I have like 1 day tring to solve this problem

A: $usuario = Auth::user();
$id = $usuario->id; // you already have user from Auth or Request, does not need to request database again
$mascotin = Mascota::all();
$mascota = $mascotin->find($id); // you can search in collection
//if you want to create Mascotin if it doesn't exists use Mascota::firstOrCreate(['id' => $id]);

if(!$mascota){
 throw new \Exception('Mascota not found', 404); //if $mascota is mandatory
}
$mascota->save(); // this does not have place here unless you are changing $mascota before that

$cant_mascota = $mascotin->count();
$cant_pregunta = Pregunta::count();

Also you should add auth middleware to this route. Only logged users should see it.
I am not sure what "Mascota" means (it will be good to use english when you share your code) but it is not good to have the same id as user. Better use relationships.


text:
Q: Column with # of times index is repeated I have a pandas DataFrame in which some rows are repeated hence they have the same index
Example:
        A
0.      34
1.      12
1.      12
2.      21
2.      21
2.      21

How can I create a column "B" which contains how many times that index was repeated?
Desired Output:
        A.    B.
0.      34.   1
1.      12    1
1.      12    2
2.      21.   1
2.      21.   2
2.      21.   3

A: You can create a dummy column of 1s and groupby the index and use cumsum on the dummy column:
df['B'] = df.assign(one=1).groupby(level=0)['one'].cumsum()

Another option is to use groupby the index and use cumcount (and add 1) to get the running count:
df['B'] = df.groupby(level=0).cumcount()+1

Output:
      A  B
0.0  34  1
1.0  12  1
1.0  12  2
2.0  21  1
2.0  21  2
2.0  21  3


text:
Q: How to persist counter variables using useReducer in React I have two objects that I'm trying to loop through using an increment and decrement function. I have the variables being stored in localStorage and the expectation is that no matter which value has been selected last, upon refresh or reload, the counter should still work. However, I've experienced some unexpected occurrences upon using the increment and decrement functions where the variable does not line with the index of the object as shown by the reducer state.
  const increment = (props) => {
    return (props.state + 1) % props.length;
  };

  const decrement = (props) => {
    return (props.state - 1 + props.length) % props.length;
  };

  const colors = [
    { id: 0, type: "Red" },
    { id: 1, type: "Blue" },
    { id: 2, type: "Green" },
    { id: 3, type: "Yellow" }
  ];

For example, at times when I call the state, it will tell me that the color is Yellow and the index is 2, and is generally inconsistent. I've tried storing the counter variable within localStorage and calling from that in hopes that it will synchronize the counter with the intended variable, however, this has not worked.
Here is a demo with CodeSandbox. I'm still relatively new to React and I'm not sure if using a counter is the best method for this problem.
Here is a reproducible example of the output I've received (upon clearing localStorage and refreshing the app) and the expected output for the shapes.
Output:
Square (next) Square (previous) Circle (previous) Square (previous) Octagon (next) Triangle
Expected output:
Square (next) Circle (previous) Square (previous) Octagon (previous) Triangle (next) Octagon

A: Having forked and refactored your original sandbox here there were a few challenges.
Firstly, the reducer actions were expanded to include increment and decrement. The example provided in React Hooks Reference has an example of incrementing and decrementing, though reducers are not just applicable for counting. The dispatch of your reducer will set the state, so having Action.Set is redundant.
Let's take a look at one of the original buttons' onClick methods. Originally, colorCount was being decremented and then an update to color occurs based on the state at the time of click, not when the state is updated. To visualize this on the original demo, log the state before and after setData.
onClick={() => {
  setData({
    payload: decrement({
      state: state.colorCount,
      length: colors.length
    }),
    name: "colorCount"
  });
  setData({
    payload: colors[state.colorCount].type,
    name: "color"
  });
}}

Now, the same onClick calls the decrement method.
onClick={() => {
  decrement({
    name: "colorCount"
  });
}}

The decrement method, moved to the context, just calls the dispatch with proper type and payload containing the name of the value to update.
const decrement = (payload) => {
  dispatch({
    type: ACTIONS.DECREMENT,
    payload
  });
};

Lastly, the reducer updates the states colorCount paired with its prefix color and shapeCount paired with its prefix shape
const reducer = (state, action) => {
  // Verify which value we need to update along with its count
  const isColor = action.payload.name.includes("color");
  // Select the proper option in context
  const options = isColor ? colors : shapes;

  switch (action.type) {
    case ACTIONS.INCREMENT:
      // Increment the count for use in the value and type setting
      const incrementedCount =
        (state[action.payload.name] + 1) % options.length;
      return {
        ...state,
        // Set the new count
        [action.payload.name]: incrementedCount,
        // Set the new color or shape type
        [isColor ? "color" : "shape"]: options[incrementedCount].type
      };
    case ACTIONS.DECREMENT:
      // Decrement the count for use in the value and type setting
      const decrementedCount =
        (state[action.payload.name] - 1 + options.length) % options.length;
      return {
        ...state,
        // Set the new count
        [action.payload.name]: decrementedCount,
        // Set the new color or shape type
        [isColor ? "color" : "shape"]: options[decrementedCount].type
      };
    default:
      return state;
  }
};

As far as updating the localStorage on update of a value, the easiest way is another useEffect dependent on the state values. Feel free to update the localStorage how and when you want, but for the purposes of keeping the state on reload the simplest approach was kept.
  useEffect(() => {
    localStorage.setItem("colorCount", JSON.stringify(state.colorCount));
    localStorage.setItem("color", JSON.stringify(state.color));
    localStorage.setItem("shapeCount", JSON.stringify(state.shapeCount));
    localStorage.setItem("shape", JSON.stringify(state.shape));
  }, [state.colorCount, state.color, state.shape, state.shapeCount]);

To the point made about contexts, this counter example does benefit from simplicity. The reducer can be used all within the App. Contexts are best used when passing down props to children becomes cumbersome.

A: What you've provided here is not sufficient for a minimum reproducible example. We can't offer much help if your problem is only happening "at times" -- please provide specific cases of what steps you take to obtain a specific problem.
Generally speaking, I think it might simplify your code to use two separate state variables. Context seems like overkill for this use case.
const [colorIdx, setColorIdx] = useState(0);
const [shapeIdx, setShapeIdx] = useState(0);

And, as a style note, it is usually a good idea to avoid inline function definitions. The following is much more readable, for example:
const incrementColorIdx = () => {
  setColorIdx((colorIdx + 1) % colors.length);
}
...

<button onClick={incrementColorIdx}>Next</button>


text:
Q: Tangential acceleration If you are spinning an object using a mass-less string with constant speed in a vertical circle, and when the object is at an angle with the vertical, what happens to the component of weight in the tangential direction?
$$mg \cos\theta + T = \frac{mv^2}{R}$$
$$mg \sin\theta =\ ?$$
or am I completely wrong in assuming no tangential acceleration?

A: Imagine what happens when the spring in horizontal. Gravity is pulling down on the mass with no counterforce upwards. Therefore, the whirling mass has to be accelerating downwards.
It's impossible to have vertical circular motion at constant speed with gravity and a purely centripetal force.


text:
Q: SimpleExoPlayer is deprecated in 2.16. version of ExoPlayer. What to use now? SimpleExoPlayer is deprecated in 2.16 version of ExoPlayer. What to use now?

A: Github release notes for 2.16.0 version -> https://github.com/google/ExoPlayer/blob/release-v2/RELEASENOTES.md
Deprecate SimpleExoPlayer. All functionality has been moved to ExoPlayer instead. ExoPlayer.Builder can be used instead of SimpleExoPlayer.Builder.


text:
Q: Swift 2 - Xcode 7 - failed with exit code 1 i have this error when i want to build my iOS App in Swift 2 and Xcode 7.0, i tried pretty much everything (clean, rebuild, delete derived date, ..)even re-install xcode but nothing has worked...

Command /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1

Thanks!!
RESOLVED:
I re-import all my files and my framework then the issue has disappear.

A: Try to delete manually DerivedData folder and restart Xcode
Users/%User%/Library/Developer/Xcode/DerivedData

A: Try Clean and rebuild, also delete derived data too.

A: *

*Delete DerivedData folder from window -> projects -> select delete on DerivedData

*Clean Your Project.

*Rebuild


text:
Q: Why is the destroy method redirecting incorrectly? I am working on the destroy functionality for a small rails app.  Currently, when I click delete I get the following error:
No route matches [POST] "/note/1"

Here is the relevant controller method:
def destroy
  if Note.find(params[:id]).destroy
    redirect_to note_index_path, notice: 'Note deleted!'
  else
    redirect_to note_path, notice: 'Note failed to updated'
  end
end

Here is a link example:

<%= link_to 'Delete Note', { action: :destroy, id: @note.id }, method: :destroy, data: { confirm: 'Are you sure?' } %>

Here are the routes:
Prefix Verb   URI Pattern              Controller#Action
note_index GET    /note(.:format)          note#index
           POST   /note(.:format)          note#create
  new_note GET    /note/new(.:format)      note#new
 edit_note GET    /note/:id/edit(.:format) note#edit
      note GET    /note/:id(.:format)      note#show
           PATCH  /note/:id(.:format)      note#update
           PUT    /note/:id(.:format)      note#update
           DELETE /note/:id(.:format)      note#destroy
      root GET    /                        note#index

A: You don't need to specify the action in the link_to helper when you make a DESTROY request, try just passing the resource, and specifying the method as delete:

<%= link_to 'Delete Note', @note, method: :delete, data: { confirm: 'Are you sure?' } %>

The @note object will give you the id, also without having to specify it.
If you make your route wait for a param id like /note/:id, then Rails will take the id value for the object passed as the second parameter in your link_to in this case.


text:
Q: How to update CodeBlocks in Kali Linux? I installed CodeBlocks on Kali Linux but I got 10.05 version and I want to update it to 13.12, preferably via terminal.
Also I would like to know how to update any application this way.

A: You could try to download the deb package and open it up using the file explorer. Then it is possible it will install.
You can download the .deb on the official Debian site at https://www.debian.org/distrib/packages then use
dpkg -i package.deb

A: In the terminal you would use apt-get to upgrade the package. You would want to try:
sudo apt-get install --only-upgrade <packagename>


text:
Q: Git repository setup with binaries My company is considering implementing Git but I have a question about what the best way would be to set it up. We have 3 sites and are planning on using Gerrit2 to create mirrors. Our repository is about 2GB and we would like to start adding binaries to it. I'm concerned about the space usage though. I don't mind if all versions of the binaries are stored in a handful of locations but I want to make sure that they don't bog down clone operations.
I understand that Git uses hard links but I think that will only work if we place a copy of the repository on every mount. Are there better options and if so what are the tradeoffs? Options that I'm looking at are "--shared" and "--reference".

A: Another alternative to git media mentioned by Marcelo is git annex:
See what git-annex is not:

git-annex is not git-media, although they both approach the same problem from a similar direction. I only learned of git-media after writing git-annex, but I probably would have still written git-annex instead of using it.
Currently, git-media has the advantage of using git smudge filters rather than git-annex's pile of symlinks, and it may be a tighter fit for certain situations.
It lacks git-annex's support for widely distributed storage, using only a single backend data store.
It also does not support partial checkouts of file contents, like git-annex does.

Note: abdelsaid adds in the comments:
You can use git-annex with bup (bup allows you to have versions), see  git-annex/ special remotes/ bup (and Using bup)
I have presented bup in more details in "git with large files"

A: Use git-media for large binaries. It stores references to binaries as SHA1 sums and hosts the binaries themselves in a place (and protocol) of your choosing. When you do a clone, it only fetches the binaries necessary to checkout the working copy.

A: To just use native git, use a separate repo to house the binaries via git submodules. This has worked for me on IVR systems which had a ton of gigantic .wav files. If you need further clarification, feel free to contact me.
Here's a good write up on them:
http://progit.org/book/ch6-6.html
hope this helps

A: Yet another possibility is git-fat (or Cyan's fork of git-fat with some enhancements); it is even lighter weight (depends only on Python and rsync) than git-media (Ruby), and definitely lighter than git-annex (Haskell).  The cost of that is less configurability, but this may be the best solution in some cases.


text:
Q: Firebase FieldValue.arrayUnion() not working properly on client SDK When I try to create an array in firestore with this code
await store
    .collection("video")
    .doc(videoId)
    .set(
      {
        data: firebase.firestore.FieldValue.arrayUnion(userId),
      },
      {merge: true},
    )

The data created in firestore then look like

A: This behavior appear because I was using firestore from @react-native-firebase/firestore and importing firebase from firebase library instead of @react-native-firebase/app so i had to change this
import firebase from "firebase"

To this
import firebase from "@react-native-firebase/app"

A: First, omit the trailing comma after {merge:true}.
If that doesn't fix it, can you share how you define "userId" and "store"?


text:
Q: In Azure Pipelines, can I download a generated Azure CLI script? In an Azure DevOps pipeline, I have an Azure CLI task running a PowerShell script:
- task: AzureCLI@2
  inputs:
    azureSubscription: '$(azureServiceConnection)'
    scriptType: ps
    scriptLocation: inlineScript
    inlineScript: |
      $foo = az rest --method GET --uri 'https://graph.microsoft.com/v1.0/applications/000000-00000-00000-00000' | ConvertFrom-Json
      ... // etc

The pipeline run log gives me the path to the generated script file:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted
  -Command ". 'D:\a\_temp\azureclitaskscript1665123106628.ps1'"

Can I somehow download the generated script D:\a\_temp\azureclitaskscript1665123106628.ps1?

A: From the logs, we could see the cli script file is located with the path of "D:\a_temp"
So in my test, manage to get the script with steps below.
1.I define a variable with below (in case that if you use other type of agents, the path will be different).

2.Add a task of "Publish build artifats", and set the path to publish with below

3.With the success, you could see the published artifact in the pipeline summary page.

4.Click in and below is your generated script

With below is the full yaml.

pool:

  name: Azure Pipelines

variables:

  cliscriptpath: 'D:\a\_temp'

steps:

- task: AzureCLI@2

  displayName: 'Azure CLI '

  inputs:

    azureSubscription: '***)'

    scriptType: ps

    scriptLocation: inlineScript

    inlineScript: 'az account show'

- task: PublishBuildArtifacts@1

  displayName: 'Publish Artifact: drop'

  inputs:

    PathtoPublish: '$(cliscriptpath)'