text:
Q: How do I show hidden files in Finder with a keyboard shortcut? What is Ubuntu's CTRL+H equivalent in OSX Lion Finder to toggle display hidden files?
My all searches point me to use: defaults write com.apple.finder AppleShowAllFiles TRUE which is not exactly the same and its effect is somewhat permanent.

A: defaults write com.apple.finder AppleShowAllFiles FALSE reverse it. And there is no such functionality (online hide/show without restart) built in into Finder.
That is probaly because anyone who need it will prefer ls -a anyway.)
BTW If you only need to list hidden files use ls -ld .??*

A: There is a simple keyboard shortcut, at least since Sierra (macOS 10.12). Ensure that Finder is the active app and use this keyboard shortcut:
CommandShift. (that's a full stop/period at the end)

A: You could buy TotalFinder. It is a finder replacement that supports this feature (and many other nice features like tabs). TotalFinder features the ⇧⌘. shortcut as seen here:

See more details about this particular feature on their site

A: The keyboard shortcut
CommandShift.
does not work with international keyboards in Finder window, although it works in "open file" dialogs.
At least this is true with French keyboard.
The shortcut to use then is
fnCommandShift.
It works in both "open file" dialogs and in Finder windows, however you can avoid pressing the extra key fn and use CommandShift. in those dialogs.

A: ⇧⌘. shows hidden files in file dialogs and in some third party applications like TotalFinder. Transmit also has a menu item for toggling hidden files, but it's assigned to ⇧⌘B by default.
There's nothing equivalent to that in Finder though. But you could assign a shortcut to a script like this with FastScripts or by creating an Automator service.
k="com.apple.finder AppleShowAllFiles"
[[ "$(defaults read $k)" == 0 ]] && b=true || b=false
defaults write $k -bool $b
osascript -e 'quit app "Finder"' && open -a Finder

A: Wow, the above sounds really complex, why not open a terminal, and

*

*type defaults write com.apple.Finder AppleShowAllFiles YES and press return

*Now Ctrl-Opt-Click on the Finder icon and select Relaunch

To un-hide run defaults write com.apple.Finder AppleShowAllFiles NO the same way.

A: Here's a tutorial for setting up a contextual menu item to toggle visibility of hidden files.
http://www.macosxtips.co.uk/index_files/quickly-show-hidden-files.php
Still not as good as a keyboard shortcut. Filing a duplicate of radar://7096650 at http://bugreport.apple.com is the best way to tell Apple that you want this feature.


text:
Q: php firebase api - delete children element from nested document I'm using php sdk to delete some fields from firestore database,
i want to delete a map from an array inside a document, but instead the function used delete all maps inside the parent array.
My firestore database looks like this

What i'm trying to do is remove a specific index ex: index 0 with it's children from imageUrls array not all the maps inside it.
I tried these 2 functions :
$usersRef->update([
        ['path' => 'imageUrls.image_url', 'value' => FieldValue::arrayRemove(['image.png'])]
    ]);

and this one
$usersRef->update([
    ['path' => 'imageUrls.image_url', 'value' => FieldValue::deleteField()]
]);

The first function remove all imageUrls childrens and change imageUrls type from array to map, while the second one nothing happened. All the fields still exist in the document and no deletion occurd
<?php

namespace App\Services;
use Google\Cloud\Firestore\FirestoreClient;
use Google\Cloud\Firestore\FieldValue;
use Google\Cloud\Firestore\FieldPath;

class FirebaseService
{
    public function delete()
    {
        // Create the Cloud Firestore client
        $db = new FirestoreClient(
            ['projectId' => 'MyProjectId']
        );

        $usersRef = $db->collection('NewStories')->document('1');

        $usersRef->update(
                         [
                              ['path' =>'imageUrls.image_url',
                              'value' => FieldValue::arrayRemove(['image.png'])]
                         ]);
    }
}

A: This can be achieved using the arrayRemove() method. As the PHP Client for Firestore says

Returns a special value that can be used with set(), create() or update()
     that tells the server to remove the given elements from any array value
     that already exists on the server. All instances of each element
     specified will be removed from the array. If the field being modified is
     not already an array it will be overwritten with an empty array.

Update:
Firebase does not support updating an existing element in an indexed array.
More information can be found in the Official Documentation.
Workaround:
Reading the entire array out of the document, make modifications to it in memory, then update the modified array field entirely.**
Credits to this Firestore Update single item in an array field case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql Timestamp difference results I have a table with a TIMESTAMP field (lastHonored).
I ran this query:
SELECT NOW(), lastHonored,
    TIMESTAMPDIFF(SECOND, lastHonored, NOW()), NOW()-lastHonored
FROM db.table

I get the result:
NOW()               | lastHonored         | DIFF  | SUBTRACT
2014-10-27 14:07:22 | 2014-10-26 19:49:51 | 65851 | 945771
Where DIFF is the result of the TIMESTAMPDIFF function, and SUBTRACT is the result of the NOW()-lastHonored expresssion.
DIFF looks right, but can anyone tell me what NOW()-lastHonored calculates? It is not the right order of magnitude, and I'm stumped.

A: One would think that NOW() returns a datetime or similar type.  But no.  For some historical reason, NOW() returns either a number or a string.  To quote the documentation:

Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS'
  or YYYYMMDDHHMMSS format, depending on whether the function is used in
  a string or numeric context. The value is expressed in the current
  time zone.

That means that NOW() gets converted to a value based on its context.  The - suggests a numeric context, so NOW() is a number whose digits are YYYYMMDDHHMMSS.  My guess is that lastHonored gets similarly converted, so the result is the difference between two numbers.

A: You can see why by running:
SELECT CAST(NOW() AS UNSIGNED), CAST('2014-10-26 19:49:51' AS UNSIGNED);

By doing simple subtraction, MySQL is turning both values into numbers. NOW() the DATETIME becomes 20141027141923, but 2014-10-26 19:49:51 the STRING becomes 2014.
If you first cast the date to a DATETIME it gives you results more along the lines of what you expect:
SELECT CAST(NOW() AS UNSIGNED), CAST(CAST('2014-10-26 19:49:51' AS DATETIME) AS UNSIGNED);

A: You can't subtract dates like you are with NOW()-lastHonored. Dates/datetimes are not directly "subtractable":
MariaDB [test]> select '2014-10-27 08:18:00' - '2014-10-27 08:17:00';
+-----------------------------------------------+
| '2014-10-27 08:18:00' - '2014-10-27 08:17:00' |
+-----------------------------------------------+
|                                             0 |
+-----------------------------------------------+
1 row in set, 2 warnings (0.00 sec)

MariaDB [test]> show warnings;
+---------+------+---------------------------------------------------------+
| Level   | Code | Message                                                 |
+---------+------+---------------------------------------------------------+
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:18:00' |
| Warning | 1292 | Truncated incorrect DOUBLE value: '2014-10-27 08:17:00' |
+---------+------+---------------------------------------------------------+
2 rows in set (0.00 sec)

Note the warnings. You'll get results, but they almost always be totally useless/incorrect results, because MySQL is casting the date values as doubles.

A: They do different things, substraction does not take into account that you are dealing with times.
If you do:
SELECT NOW(), lastHonored,
TIMESTAMPDIFF(SECOND, lastHonored, NOW()) THE_DIFF, NOW()-lastHonored THE_SUBSTRACTION,
NOW()+0 NOW_NUMBER_REPRESNTATION,
lastHonored+0 lastHonored_NUMBER_REPRESENTATION
FROM db.table

You will see the numeric difference is represented with the substraction and the time differente with TIMESTAMPDIFF.


text:
Q: "Property Not Found" Access Error When Querying With a Null Field I have an odd problem with MS Access 2013 at the moment. It keeps returning "Property Not Found" when I query it with a null field.
The query I've created should allow users to enter some, all or none of a postcode and return the matching records. On my laptop (running Access 2016) this query runs fine in all forms, but returns the aforementioned error when the field is left blank.
The query (in SQL mode) is:
WHERE ((Left([Carer Contact Details]![Postcode],Len([Forms]!
[AgeRangeQueryForm]![PostcodeSearch])))=[Forms]![AgeRangeQueryForm]![PostcodeSearch])) OR ((([Forms]![AgeRangeQueryForm]![PostcodeSearch]) Is Null));

There are some extra parts to the query, relating to other parts of the form but they are not relevant here as all other parts of the query are functioning.
I suspect this is an compatibility issue between Access 2016 and 2013. The database was originally made in Access 2016, but I had to port it onto an older system which runs 2013. This is the only difference I can ascertain, and I can't figure out any other reason why it might work on one machine and not the other!
Any help would be appreciated!

A: Try using Nz:
WHERE
    (Left([Carer Contact Details]![Postcode], Len(Nz([Forms]![AgeRangeQueryForm]![PostcodeSearch]))) = Nz([Forms]![AgeRangeQueryForm]![PostcodeSearch]))
    OR
    ([Forms]![AgeRangeQueryForm]![PostcodeSearch] Is Null);


text:
Q: Blow-up along singularity of the degeneracy locus Let $X$ be a smooth, projective variety, $E$ a rank $r$ locally free sheaf on $X$. Fix a closed embedding $i:X \hookrightarrow \mathbb{P}^N$ and denote  by $\mathcal{O}_X(m)=i^*\mathcal{O}_{\mathbb{P}^N}(m)$. For $d \gg 0$, take $r$ general global sections $s_1,...,s_r \in H^0(E(d))$. Denote by $Z$ the locus of points on $X$ at which the sections $s_1,...,s_r$ are linearly dependent. Denote by $D$ the singular locus of $Z$, $\tilde{X}$ the blow up of $X$ along $D$ and $\tilde{Z}$ the strict transform of $Z$ in $\tilde{X}$. Denote by $E$ the exceptional divisor in $\tilde{X}$, $F:=\tilde{Z} \cap E$ and $\pi:F \to D$ the natural morphism.
I am looking for conditions under which the morphism $\pi$ is smooth and projective. The vector bundle $E$ I am interested in, is the dual of the normal bundle $\mathcal{N}_{X|\mathbb{P}^N}$. Any idea/reference in this direction will be very helpful.


text:
Q: iCloud on Mountain Lion: one account per Mac or one per user? Before installing Mountain Lion and using iCloud for the first time, I would like to know how it can be configured.
My iMac has three standard user accounts and one admin account. If I understand correctly the John Siracusa review, the install procedure asks for an Apple ID for iCloud. Here are my questions:

*

*Does that Apple ID apply for the whole Mac, for the admin account alone or for one standard account to be specified?

*Is it possible to assign a distinct Apple ID to each user account?

A: That apple ID applies only to the user account that is created during the setup process. If you look in System Preferences, you'll notice the following option called "Apple ID", under a test account I created:

Additionally, when logging into the new test account, I was presented with the iCloud login screen which you saw during initial setup of the OS install on your Mac.
If you restored your iMac from a backup, or installed Mountain Lion over Lion,
you will already have access to those accounts without seeing the iCloud setup screen. In that case, open System Preferences, click on Users & Groups, and set up your iCloud account as you wish.
So, one iCloud account per local account. This would appear to be the case on Lion as well.

A: One aspect of iCloud can only be active for one account per hardware device.  Find My Mac is exclusive - no matter how many accounts or even how many OS installs you run (say booting from multiple OS - Lion externally and Mountain Lion internally), only one iCloud account gets to find your Mac's location.
Apart from that, each account can use it's own iCloud account fully with no restrictions. In fact, one user account on OS X can have multiple iCloud accounts with the qualification that only the "primary" iCloud account gets these features:

*

*Bookmarks

*Photo Stream

*Find My Mac

*iCloud storage of files and settings

It looks like another answer has covered the Apple ID part of registration (normally this runs once, but you can always re-register hardware by re-installing the OS) and you may elect to use your iCloud account to redeem any software that was shipped with that Mac when it was new. You can do that in the App Store from the Purchases tab.


text:
Q: How can I make a kit that has Unbreakable Items in it? I'm trying to make kits with Unbreakable Items in it for my Kit PvP server.
To make the items Unbreakable, I use this command:
 /give (Name) minecraft:(item) 1 0 {Unbreakable:1}

For proof that the command worked, I hovered over the item and it clearly said Unbreakable at the bottom of the lore. For example:

Problem is, when I do /createkit, it transfers the item but not the Unbreakable effect.
When I hover over the item after I create the kit, it does not say Unbreakable at the bottom of the lore. Again, for example:

A: Instead of using the unbreakable attribute, use the ench attribute to add almost infinite unbreaking to the item. (It is still possible to break it, but it would have to deal the damage of killing about 130,000 ender dragons) The command is /give (Name) minecraft:(item) 1 0 {ench:[{id:34,lvl:10000}]}.The item now has unbreaking level 10,000.

A: By the command it seems like you're using a plugin. If you have essentialsx on your server, which is a pretty common and good to have plugin (in addition to its capable kit system), the following kits.yml is valid and works as expected.
kits:
  tools:
    delay: 10
    items:
      - stonesword 1 Unbreakable:true


text:
Q: jquery ajax post method giving internal server error  $("[id$=_btnPostReminder]").click(function(){
     var a = $find("<%=Editor1.ClientID%>");
     var remindertext = a.get_content();
     var re=$("#<%=hiddReminderTicketId.ClientID%>").text();
     var res= $("#<%=txtReminderon.ClientID%>").val();
     $.ajax({
        type: "POST",
        url: "AllTickets.aspx/btnPostReminder",
        data: '{TicketId: ' + re + ',remindertext: ' +  remindertext  + ',reminderon: ' +  res  + '}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success:
        function Ret(response) {
        var Result=response.d
        alert(Result)
        $("#<%=txtReminderon.ClientID%>").val("")
        $('#<%=hiddReminderTicketId.ClientID %>').text("")
        $('#<%=lblAlert.ClientID %>').text("Set Successfully");
        return false;
        },
        error: function(data, status, jqXHR) {
        alert(jqXHR);
        }
    });
    return false;
});

C# code behind :
[System.Web.Services.WebMethod()]
public static string btnPostReminder(Int64 TicketId, string remindertext, string reminderon)
{
    Common objCommon = new Common();
    DAL objDal = new DAL();
    SqlParameter[] para = new SqlParameter[4];
    para[0] = new SqlParameter("@ticketid", DbType.Int64);
    para[0].Value = TicketId;
    para[1] = new SqlParameter("@REMINDERTEXT", DbType.String);
    para[1].Value = remindertext;
    para[2] = new SqlParameter("@REMINDERON", DbType.DateTime);
    para[2].Value = objCommon.ReturnDate(reminderon);
    para[3] = new SqlParameter("@CREATEDBY", DbType.Int64);
    para[3].Value = Convert.ToInt64(1);

    objDal.ExecuteSP("CREATE_REMINDER", para);

    return   " successfully";
}

A: Ok Found your problem, you are passing Int64 as parameter which should be string otherwise so when changing it to below I get success message :
 [System.Web.Services.WebMethod()]
 public static string btnPostReminder(string TicketId, string remindertext, string reminderon)
    {
        return " successfully";
    }

Also your data should look like below:
 data: '{"TicketId":"' + re + '","remindertext":"' + remindertext + '","reminderon":"' + res + '"}',

Pass as string for parameter and to TryParse to see if it is of type int.


text:
Q: Set div height equal to screen size I have a div element in twitter-bootstrap which will have content that will overflow vertically outside the screen.
I would like the div to take the height of the size of the browser window and let the rest of the content scroll vertically within the window.
I have a sample that is not working @jsFiddle
#content {
    border: 1px solid #000;
    overflow-y:auto;
    height:100%;
}

Side Bar

            Content Bar Example Content

I am posting this question after reading so questions like SO Questions
EDIT--
Sorry guys I guess I got my question wrong.
What I would like is that my div must fill the rest of the vertical space in the screen.
It would be great if someone can suggest a responsive solution

A: Using CSS {height: 100%;} matches the height of the parent. This could be anything, meaning smaller or bigger than the screen. Using {height: 100vh;} matches the height of the viewport.
.container {
    height: 100vh;
    overflow: auto;
}

According to Mozilla's official documents, 1vh is:

Equal to 1% of the height of the viewport's initial containing block.

A: You need to give height for the parent element too! Check out this fiddle.
CSS:
html, body {height: 100%;}

#content, .container-fluid, .span9
{
    border: 1px solid #000;
    overflow-y:auto;
    height:100%;
}

JavaScript (using jQuery) Way:
$(document).ready(function(){
    $(window).resize(function(){
        $(".fullheight").height($(document).height());
    });
});

A: try this
$(document).ready(function(){
    $('#content').height($(window).height());
});

A: use             $(document).height()
property  and set to the div from script and set

  overflow=auto
for scrolling

A: This worked for me JsFiddle
Html
..bootstrap

    First Col

    Column-8

css
.row {
   background: #f8f9fa;
   margin-top: 20px;
}

 .col {
   border: solid 1px #6c757d;
   padding: 10px;
}

JavaScript
var elements = document.getElementsByClassName('window-full');
var windowheight = window.innerHeight + "px";

fullheight(elements);
function fullheight(elements) {
    for(let el in elements){
        if(elements.hasOwnProperty(el)){
            elements[el].style.height = windowheight;
        }
    }
}

window.onresize = function(event){
     fullheight(elements);
}

Checkout JsFiddle link
JsFiddle


text:
Q: How can I make my PowerShell script wait for the first command to finish and then run the second command I have this PowerShell script that I want to run for my angular project.
I can only get it to run the first command or I can only get it to run the first command and then immediately run the second command.
Start /wait /b   rmdir  node_modules /S

 Start npm install /b /wait

I've looked on stack overflow and googled different stuff and have seen some good suggestions but haven't been able to get it to work correctly.  It does currently run the first command and then finish.
I've tried to remove some of the parameters like /b or /S with no luck.

A: *

*Your primary problem is that you're using syntax for cmd.exe's internal start and rmdir commands, which doesn't work in PowerShell.

*

*While PowerShell does have commands with the same names, they're aliases of PowerShell cmdlets, Start-Process and Remove-Item, and therefore require different syntax.

*While you could fix your Start commands to use Start-Process instead, there's no reason to use it to begin with, given that invoking cmdlets and (console) programs directly executes them synchronously, in the same console window, with the output streams connected to PowerShell's, by default.
Therefore:
Remove-Item -Force -Recurse node_modules  # Equivalent of rmdir /S /Q node_modules
npm install

Note: In older versions of Windows, including versions of Windows 10 prior to release 20H2, file and directory removal is inherently asynchronous, so on occasion the removal may not have fully completed yet by the time Remove-Item returns; it seems that calling via cmd /c - cmd /c rmdir /S /Q node_modules - lessens the chances of that happening (but still doesn't fully eliminate the problem). A reliable workaround is far from trivial, unfortunately - see this answer.

Update: As it turns out, you were actually running a batch file (.cmd or .bat), not a PowerShell script (.ps1), but the above points apply analogously; the batch-file solution is:
rmdir /S /Q node_modules
npm install


text:
Q: Solving Differential Equation about rate of infected computers I am having some trouble solving this differential equation for the rate of infected computers in a botnet at time t
$$\frac{\mathrm{d}x }{\mathrm{d} t} = \frac{1}{c\nu (1-x) + \beta x(1-x) - \gamma x}$$
with $$x(0) = 1$$ i.e at time 0, there is one computer in the botnet.
I am trying to get this in terms of x(t) but the algebra is becoming quite complex for me, can anyone assist?
Thanks!

A: Notice, use variable separable method as follows $$\frac{dx}{dt}=\frac{1}{c\nu(1-x)+\beta x(1-x)-\gamma x}$$
$$(c\nu(1-x)+\beta x(1-x)-\gamma x)\ dx=dt$$
$$c\nu\int \ dx+(\beta-c\nu-\gamma)\int x\ dx-\beta\int x^2\ dx=\int \ dt$$
$$c\nu x+(\beta-c\nu-\gamma)\frac{x^2}{2}-\beta\frac{x^3}{3}=t+C$$
now, setting $x=1$ at $t=0$, we get $$c\nu \cdot 1+(\beta-c\nu-\gamma)\frac{1^2}{2}-\beta\frac{1^3}{3}=0+C\implies C=c\nu+(\beta-c\nu-\gamma)\frac{1}{2}-\beta\frac{1}{3}$$
I hope you can take it from here


text:
Q: Where can I ask this question about programming language? Question:

How first programming language made?

Description:

I want to know how first programming language made?

A: Well, I'm going to be that guy and suggest you Google it. You are going to find lots of great starting points there, and might find your answer already there.
For example you would find it was asked on SO and closed as off topic years ago.
I would also suggest taking note of something on many of the site help

You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page

The question without a lot of context might not do so well. Picking a specific proto language or context might help as would using SE to augment your own basic research


text:
Q: Добавление .ico 16x16 на сайт в меню html Как добавить иконку в менюшку на сайт? Как на картинке точки перед: новости, пресса и.т.д
Что можно добавить в код чтоб появились иконки перед каждой ссылкой в меню?

A: Для этого нужно установить свойство list-style-image: для списка. Это свойство как раз определяет изображение, которое будет использоваться в качестве маркера.
Пример страницы с подобным списком
<!DOCTYPE html>

  <meta charset="utf-8">
  <title></title>

Новости

Пресса

Анкета


text:
Q: Can WiX source refer to NuGet packages from another projects in solution? I have a solution with two projects:

*

*.NET application

*WiX setup project.

I know, that it is possible to refer to project output in WiX source ($(var.WindowsFormsApplication1.TargetFileName)).
Now I've added a NuGet package reference to my .NET application. So, I want to bring NuGet package content into my setup.
Is there any way to do this instead of adding files manually?

A: I don't believe there is any linkage.  I know what nuget is but I haven't used it much because it's more about brining your .NET dependencies into scope then software distribution.  Depending on how nuget lays the files down you might be able to do something like $(var.SomeProject.TargetDir)nuget_fetched.dll.
This is assuming that SomeProject uses nuget in such a way that the references are copied locally and available in the Outdir of the project.

A: I wrote a Resharper live template to cut out a lot of the typing involved in adding the files, but essentially I've just added the files manually. Creating a Wix component per nuget package keep things neat.


text:
Q: Identifying a time travel TV series I have a vague memory about a TV series I saw as a kid (mid-late 1990's). It was about a male teenager, traveling alone, who had time travel adventures. I loved it to bits, but I haven't seen or heard of it since. It would have been in English.
Anyone know what I'm talking about? I don't remember any further details, but I'm hoping someone remembers it. I'm a big fan of time travel, so hate to miss out on decent time travel stuff.

A: It might have been Voyagers. I loved that show too.
A member of a league of time travelers and a boy travel through time repairing errors in world history.


text:
Q: Using an input variable in a 'For Loop' in Bash I am trying to use the #REPLY input variable in the following for loop code below;
If I use syntax such as for i in {60..0} then it works fine however; trying the input variable from the read statement "for i in {$REPLY..0}" it fails. It appears that the read does not recognize the input as an integer value; can someone assist please?, thank you.
#!/bin/bash
clear
tput cup 5
read -p "What is the number of seconds? "
echo "Started:" $(date)
echo " "
echo " "
echo "Countdown Timer"
echo " "

for i in {$REPLY..0}
do
  tput cup 10 $1
  printf '%dh:%dm:%ds\n' $(($i/3600)) $(($i%3600/60)) $(($i%60))
  tput civis
  sleep 1
done
tput cnorm
echo " "
echo "Finished:" $(date)

A: Yes, you can't use a variable in brace expansion. So, the solution is simple bash arithmetic form loop :
for ((i=REPLY; i>=0; i--)); do
    [...]

...and please, no responses with the evil eval, thanks


text:
Q: Which Hook is running after Woocommerce update cart button action i need to know which hook is running after clicking the update cart button in the cart page .
That is in cart page we have 4 button , update cart , continue shopping, proceed to checkout , apply coupon .
So i want to know which hook is run after update cart button is clicked . When customer click the update cart button after changing the quantity then i have to run a special function that can change total price in the cart , If some condition met , i will change the total price in the cart , and this total price need to pass to the checkout page also /
Please help  .
For example
add_filter('after_update_cart_function_finished', 'special_function');

function special_function(){
   $applied_coupons= WC()->cart->get_applied_coupons();
   if(!empty($applied_coupons)){

   $new_value=WC()->cart->get_cart_subtotal();
   $discounted=WC()->cart->coupon_discount_totals;
   $discounted_value=array_values($discounted)[0];
   $new_value=$new_value-$discounted_value+100;
    WC()->cart->set_total_price($new_value);
    After this update all post_meta value that regarding to order total
   }

}

Please see the following custom function that i write for to change value in cart
 function action_woocommerce_cart_totals_after_order_total(  ) {
          $applied_coupons= WC()->cart->get_applied_coupons();
          if(!empty($applied_coupons)){

        $new_value=WC()->cart->get_cart_subtotal();
        $discounted=WC()->cart->coupon_discount_totals;
        $discounted_value=array_values($discounted)[0];
        $new_value=$new_value-$discounted_value;
        if($new_value<100){
            $new_value=$new_value+5;
        }

         ?>

         <?php
      }
    else{
        ?>

    <?php }

};

add_action( 'woocommerce_cart_totals_after_order_total', 'action_woocommerce_cart_totals_after_order_total', 10, 0 );

And this function have many problems , i write this function because of some reason or some other function woocommerce is not calculating coupon price correctly , so i write this function for to manually update the product price in cart .Here if the cart value is more than 100 we provide free shipping other vise we will add 5 .  Even this function is not working properly .
Woocommerce Create new discount functionality

A: You should try woocommerce_update_cart_action_cart_updated action hook. I have revisited your code a bit. Try this:
add_action( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ){

    $applied_coupons = WC()->cart->get_applied_coupons();

    if( count( $applied_coupons ) > 0 ){
        $new_value        = WC()->cart->get_cart_subtotal();
        $discounted       = WC()->cart->coupon_discount_totals;
        $discounted_value = array_values($discounted)[0];
        $new_value        = $new_value-$discounted_value + 100;

        WC()->cart->set_total( $new_value );

        if ( $cart_updated ) {
            // Recalc our totals
            WC()->cart->calculate_totals();
        }
    }
}

Code goes in function.php file of your active child theme (or active theme). Untested. It could work.
Update: The WC_Cart set_total_price() method doesn't exist… I have replaced it by existing WC_Cart set_total()


text:
Q: Convert data type of percent fields to number in Carto Builder I have a dataset in Carto Builder with a column that lists percentage values with a percent symbol (e.g. "10%", "50%", "35%"). By default Carto has categorized the fields in this column as strings. I want to use this column to apply shading to a choropleth map based on percent. Is there any way to get Builder to process this column numerically?
If I try to convert the data type of the column from String to Number all the fields become null. I can do the conversion in my source program but I am looking for a way to do this all in Carto Builder.

A: You can achieve this using simple SQL:
SELECT
  *,
  substring(string_field FROM '[0-9]+')::numeric as num_field
FROM
  table_name

Remember to apply this query to the node data source. If you have some analysis attached, you would need to drag that node out. More about substring Postgres function here, and BUILDER analysis workflow here.

A: You need to remove % char. I'd try these two options, replace table and field names with yours:
a) before changing field type remove them with update <table> set <field> = rtrim(<field>,'%')
b) use custom SQL to get data, something like select *,to_number(<field> ,'999%') from <table>


text:
Q: xml schema complextype I'm trying to write a Schema for a xml similar to this
<?xml version="1.0" encoding="ISO-8859-1"?>
<store>
    <book>title1</book>
    <poster>some text</poster>
    <poster>some text</poster>
    <book>title1</book>
    <poster>some text</poster>
</store>

I'd like to know if there is a complexType in Schema that allows the "book" and "poster" tags to appear a minumum of 0 times and an unlimited maximum number of times.  I need them to be able to appear in a casual order like: book, poster, book poster, poster.
I though I could simply not put a sequence, and write a schema like this
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <xs:element name="store" type="TStore"/>

    <xs:complexType name="TStore">
        <xs:element name="book" type="xs:string" maxOccurs="unbounded"/>
        <xs:element name="poster" type="xs:string" maxOccurs="unbounded"/>
    </xs:complexType>
</xs:schema>

But this just isn't valid schema. The "xs:all" would be good if the book and poster tags appeared in a casual order, but only once. How can I fix it?
EDIT: a xs:choice with maxOccurs="unbounded" does the trick nicely.
I also don't understand why a simple repetition like this should require a sequence.
I consulted some tutorial, but I can't find a reference for this simple case.
<?xml version="1.0" encoding="ISO-8859-1"?>
<tags>
    <tag>text1</tag>
    <tag>text2</tag>
    <tag>text3</tag>
</tags>

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="tags" type="complexType">
        <xs:sequence>
            <xs:element name="tag" type="xs:string" maxOccurs="unbounded"/>
        </xs:sequence>
    </xs:element>
</xs:schema>

A:
I also don't understand why a simple repetition like this should require a sequence

Is this your actual question? The simple answer is that the specification requires it.
The more detailed answer is that the validator wants an unambiguous specification of what it should look for. The <xs:sequence> unambiguously tells the validator that its contents represent an expected sequence of elements in the instance document. Just like <xs:choice> tells the validator that it should see only one of the contained elements.


text:
Q: How to install Percona Server on Ubuntu 9.10 Karmic? I followed the instructions on this page:
~$ gpg --keyserver  hkp://keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
gpg: requesting key CD2EFD2A from hkp server keys.gnupg.net
gpg: key CD2EFD2A: public key "Percona MySQL Development Team <mysql-dev@percona.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1

So far so good. But the next command gave an error:
~$ gpg -a --export CD2EFD2A | apt-key add -
gpg: no writable keyring found: eof
gpg: error reading `-': general error
gpg: import from `-' failed: general error

What went wrong?
Also after I'm done with this, how exactly do I install Percona Server? There are many packages for Karmic and I don't know what to do.
I'm new to this and any help would be greatly appreciated. Thanks

A: You need to run apt-key as the user root. For your second command, try
gpg -a --export CD2EFD2A | sudo apt-key add -

Actually, it appears that the install instructions assume you are typing all your commands as the root user (note the prompt is a #). You may want to start over again, but first get a root prompt by running this:
sudo -i

A: The key is also directly available from the Percona website.
Import it as following:
wget -O - http://www.percona.com/redir/downloads/RPM-GPG-KEY-percona | gpg --import
gpg --armor --export 1C4CBDCDCD2EFD2A | apt-key add -

Edit: Percona is going to change their SSH key before the end of this year.
See instructions on their website http://www.percona.com/ssh-key-rotation/instructions


text:
Q: How to hide scroll bar on page load? I have developed a single page website with 4 sections. Here is what my client wants:

*

*The scrollbar should be hidden on page load

*If the user scrolls past the second section, the scrollbar should appear.

My client gave me this website as an example: http://diagnosite.com/
How can I do this?

A: you can set overflow:hidden; for your body and have a javascript to detect scroll down from viewer mouse or pagedown button from keybiard. then remove overflow attribute from body.


text:
Q: How to push/pop controller by swipe in iPhone SDK? Currently i am developing an iPhone application in which navigation between two controls by swipe gesture recognizer.
Applicaiton structure is like this
For this i first load calendar screen and on it's view did load, i load home screen by using PushViewController. On home screen if user swipe's his left then calendar screen shows using PopViewController or if user swipe's his right then listview screen shows by PushViewController. This is working fine.
Now problem is that on my listview screen i am using a UITableViewController where Gesture Recognizer will not working perfectly, some time it cannot swipe.
How can i swipe between these screen perfectly, I want to swipe same as scrollview scrolling.
Please provide me some solution.

A: Provided your app is on iOS 3.2 or above, you can do this with a UISwipeGestureRecognizer as follows.
//Add Table
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 460)];
    table.dataSource=self;
    table.delegate=self;
    [table reloadData];
    [self.view addSubview:table];
    [table release];

    //Add Gesture Recognizer
    swipeLeftRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom)];
    [table addGestureRecognizer:swipeLeftRecognizer];
    [swipeLeftRecognizer release];

And somewhere in your controller;
-(void)handleSwipeFrom {

    if (swipeLeftRecognizer.direction == UISwipeGestureRecognizerDirectionRight) {

        // Your code here to go back to the main view

    }

}

This will react only for a right swipe and will let your table behave the normal way. Hope this helps! :)

A: After a long googling i found a solution. I am taking a scrollview with width of 3 screens and add calendar xib view on it's first screen frame, add home xib view on it's second screen frame and then add list xib view on it's third screen frame, with this i create a UINavigationController *navigationHome;
 id parentController;
 on home screen for managing home screen navigation from scrollview and make same technique for rest of the controllers this will work me fine.


text:
Q: Cannot set LED monitor to native resolution I cannot get windows 7 pro to set my monitor to its native resolution of 2650x1440.
I have Windows 7 pro, an NVIDIA GT730 and two monitors(AOC e2752She, BenQ GW2765) attached to the NVidia card using the DVI ports using this cable: (http://www.amazon.com/AmazonBasics-HDMI-DVI-Adapter-Cable/dp/B00NH11X64?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_search_detailpage). I originally only had the AOC with a native resolution of 1920x1080. Then I got the BenQ, but on setting it up Windows would only allow 1920x1080 for it. So I went into the Nvidia control panel and created a custom resolution 2560x1440 and set it to that. Superficially it looks like it did it as the background got small for it and the conrol panel/display/screen resolution setting SAYS 2650x1440, but the image is "soft", not crisp and when I look at the information panel on the display itself, the monitor says it is being driven at 1920x1080 and its recommended setting is 2650x1440, so I'm thinking that windows must be doing some emulation of 2560x1440 and not actually pushing it natively at 2560x1440. Even if I set the monitor to 1920x1080 the image is really "soft".
I want to use this monitor (gw2765) for graphic design and video editing, so I really need it to show it's true resolution. I have searched for quite a long time and have not found anything that seems to address this issue.
Any suggestions?
Thanks!!


text: Q: On which island can I find an abundance of Strawberry Bushes? I've been tasked with finding three strawberries from bushes scattered around the islands. Unfortunately, I've pulled up every bush on three islands now and only found one strawberry. IN the interest of minimizing the time I spend waiting around for them to grow back, which island has the most fruit-bearing bushes for me to pluck?


text:
Q: ReactJS - Waiting for user to finish multiple inputs I just started learning ReactJS so any help would be appreciated. I'm trying to make a form where user inputs his/her address into multiple input fields. When the user finishes typing into ALL input fields, then a function will be triggered to validate the address. Through research, I found out about onChange and onBlur but it seems like that only works for one input field. Is there any other way to keep track of all five inputs and trigger a function after the user finishes? Or if there is any way to use onChange to do so, I would love to know. The following is the code for my form. Thank you in advance.
<form>
      <label>
        <DebounceInput
          name="addressLine1"
          placeholder="Address Line 1"
          debounceTimeout={300}
          onChange={ (e) => this.handleChange(e, name)}
        />
      </label>
      <label>
        <DebounceInput
          name="addressLine2"
          placeholder="Address Line 2"
          debounceTimeout={300}
          onChange={ (e) => this.handleChange(e, name)}
          value={this.state.address.addressLine2}
        />
      </label>
      <label>
        <DebounceInput
          name="city"
          placeholder="City"
          debounceTimeout={300}
          onChange={ (e) => this.handleChange(e, name)}
          value={this.state.address.city}
        />
      </label>
      <label>
        <br />
        <DebounceInput
          name="state"
          placeholder="State"
          debounceTimeout={300}
          onChange={ (e) => this.handleChange(e, name)}
          value={this.state.address.state}
        />
      </label>
      <label>
        <DebounceInput
          name="postalCode"
          placeholder="Postal Code"
          debounceTimeout={300}
          onChange={ (e) => this.handleChange(e, name)}
          value={this.state.address.postalCode}
        />
      </label>
    </form>

A: Maybe you can incorporate a condition inside of your handleChange function, where you check if your currentstate is sufficient to do a validation, if so you can trigger the validation.


text:
Q: Send logs directly to Loki without use of agents Is there a way to send logs to Loki directly without having to use one of it's agents?
For example, if I have an API, is it possible to send request/response logs directly to Loki from an API, without the interference of, for example, Promtail?
Thanks in advance!

A: Loki HTTP API
Loki HTTP API allows pushing messages directly to Grafana Loki server:

POST /loki/api/v1/push
/loki/api/v1/push is the endpoint used to send log entries to Loki.
The default behavior is for the POST body to be a snappy-compressed
protobuf message:

*

*Protobuf definition

*Go client library
Alternatively, if the Content-Type header is set to application/json,
a JSON post body can be sent in the following format:
{
  "streams": [
    {
      "stream": {
        "label": "value"
      },
      "values": [
          [ "<unix epoch in nanoseconds>", "<log line>" ],
          [ "<unix epoch in nanoseconds>", "<log line>" ]
      ]
    }
  ]
}

You can set Content-Encoding: gzip request header and post gzipped
JSON.
Example:
curl -v -H "Content-Type: application/json" -XPOST -s "http://localhost:3100/loki/api/v1/push" --data-raw \
 '{"streams": [{ "stream": { "foo": "bar2" }, "values": [ [ "1570818238000000000", "fizzbuzz" ] ] }]}'

So it is easy to create JSON-formatted string with logs and send it to the Grafana Loki.
Libraries
There are some libraries implementing several Grafana Loki protocols.
There is also (my) zero-dependency library in pure Java 1.8, which implements pushing logs in JSON format to Grafana Loki. Works on Java SE and Android platform:

*

*https://github.com/mjfryc/mjaron-tinyloki-java
Security
Above API doesn't support any access restrictions as written here - when using over public network, consider e.g. configuring Nginx proxy with HTTPS from Certbot and Basic Authentication.

A: Yes. You can send logs directly from a Java application to loki.
It can be done using the loki4j configuration in your java springboot  project. Add these below dependencies to pom.xml
    <dependency>
        <groupId>com.github.loki4j</groupId>
        <artifactId>loki-logback-appender</artifactId>
        <version>1.2.0</version>
    </dependency>

Run loki either directly or from docker depending on how you have installed loki on your system. I use docker instances of loki and grafana.
Create a logback.xml in your springboot project with the following contents
    <property name="HOME_LOG" value="app.log" />

    <appender name="FILE-ROLLING"
        class="com.github.loki4j.logback.Loki4jAppender">
        <http>
            <url>http://localhost:3100/loki/api/v1/push</url>
        </http>
        <format>
            <label>
                <pattern>app=my-app,host=${HOSTNAME},level=%level</pattern>
            </label>
            <message>
                <pattern>l=%level h=${HOSTNAME} c=%logger{20} t=%thread | %msg %ex
                </pattern>
            </message>
            <sortByTime>true</sortByTime>
        </format>
    </appender>

    <logger name="com.vasanth.loki" level="debug" additivity="false">
        <appender-ref ref="FILE-ROLLING" />
    </logger>

    <root level="error">
        <appender-ref ref="FILE-ROLLING" />
    </root>

</configuration>

Configure your logger names in the above example and make sure you have given the proper loki URL - You are basically telling the application to write logs into an output stream going directly to the loki URL instead of the traditional way of writing logs to a file through log4j configuration and then using promtail to fetch these logs and load into loki.


text:
Q: Как обновить часть страницы? Есть файл с функциями где записано следующее:
function myPoll_v_1(){
global $user_ID; if ($user_ID) {//если залогинен то показываем
?>

//сюда подгружаем

<?
    }else{//если незалогинен ничего не показываем
     echo  ' ';
    }
}

Содержимое файла ххх.хтмл:
** удалил эти три строчки**

Poll

<form id='poll' action="/p/myPoll/poll.php" method="post" accept-charset="utf-8">

Pick your favorite Javascript framework:

<input type="radio" name="poll" value="opt1" id="opt1" /> jQuery

<input type="radio" name="poll" value="opt2" id="opt2" /> Ext JS

<input type="radio" name="poll" value="opt3" id="opt3" /> Dojo

<input type="radio" name="poll" value="opt4" id="opt4" /> Prototype

<input type="radio" name="poll" value="opt5" id="opt5" /> YUI

<input type="radio" name="poll" value="opt6" id="opt6" /> mootools

<input type="submit" value="Vote →" />

</form>

Функция вызывается в сайд баре вордпресса (из меню виджетов).
В данный момент при нажатии на кнопку, происходит переход на poll.php.
Как сделать так, чтобы перехода не происходило, вся работа осуществлялась в

(Что же я пытаюсь сделать? Пытаюсь прикрутить это голосование к вордпрессу.)
upd
хм... действительно две строчки там были левые (ссылка на несуществующий джеквери и плагина для него), убрал еще и  poll.js (он ведь прописан в хедере страницы, где должна показываться форма) вернулся опять к тому что было, теперь форма не реагирует ни на что.
UPD2
проблема окончательно решена  тут

A: Дело наверное <input type="submit" value="Vote →" />, при сабмитте он переходит на обработчик формы, нужно добавить ему onclick="return false", но вы, наверное, что-то неправильно делаете, поскольку в демо перезагрузки нет. Если не можете нормально установить, создайте отдельную хтмл страницу и грузите ее через iframe в нужное место - это самый простой и быстрый способ, но конечно лучше разобраться с этим плагином.
A: Хе-хе, аяксом-то вы голосование подгрузили, а скрипты, которые с ним идут, забыли. В итоге, poll.js не работает, а с ним не работает и плавная отправка формы. Грузите его на главной странице, до подгрузки формы голосования.
A: вобщем то выяснилось, что в некоторых ситуациях кнопка сабмит перестает работать(в ае 67 стопудово), но от чего то кнопка не работает и у меня в хроме, так что можно эту кнопку заменить на
Vote ---->

а на функцию повесить
$("#poll a").click(function() {
        $(this).parents().filter("form").trigger("submit");
    });

переписал код в шаблон и теперь функция выглядит так:
function myPoll_v_1(){

global $user_ID; if ($user_ID) {

?>

Poll

<form id="poll" action="/p/myPoll/poll.php" method="post">

Pick your favorite Javascript framework:

<input type="radio" name="poll" value="opt1" id="opt1" /> jQuery

<input type="radio" name="poll" value="opt2" id="opt2" /> Ext JS

<input type="radio" name="poll" value="opt3" id="opt3" /> Dojo

<input type="radio" name="poll" value="opt4" id="opt4" /> Prototype

<input type="radio" name="poll" value="opt5" id="opt5" /> YUI

<input type="radio" name="poll" value="opt6" id="opt6" /> mootools

<input type="submit" value="Vote →" onclick="return false" />

Vote ---->
</form>

<?

    }else{
     echo  ' ';

    }

}

строчку
define('HTML_FILE', 'файл_возврата.хтмл');

можно заменить на:
define('HTML_FILE', $_SERVER['PHP_SELF']);

в результате, у нас есть форма, в которой можно что то выбрать, и нажимать на vote после чего происходит смена формы на результаты голосования с анимацией, но не происходит самого голосования. будем разбираться дальше.


text:
Q: Re-arrange array elements if they meet a condition The array:
array(
  '354' => array(
             'parent' => 0
           ),

  '370' => array(
             'parent' => 0
           ),

  '420' => array(
             'parent' => 354
           ),

)

How can I move all elements that have the 'parent' value != 0, just after the element to which the key is the same as that parent value?
For example, the element with the 420 keys above needs to go after the element with the 354 key...

A: That's impossible in the general case. In your example it would work.
But here's another example:
Number | Parent
10     | 1
11     | 1
100    | 10
101    | 10
102    | 10
1000   | 100
1001   | 100

So you want that all the three rows 100, 101, 102 come directly after the row 10, which is impossible.
And between row 100 and 101 you probably want the rows 1000 and 1001, since their parent is 100.
[Update]
So there remain these questions:

*

*Do you just need the nodes ordered so that each node is defined somewhere before it is used as a parent?

*Do the direct children have to follow their parent directly, oder may there be some other nodes in between?

*Is the parent ID always smaller than the node ID?

A: Maybe you're looking at a way to make a flat array have some sort of hierarchie?
This is a very simple case which will do that asuming your children always have a higher id than their parent.
<?php
$array = array(
  '354' => array(
             'parent' => 0
           ),
  '370' => array(
             'parent' => 0
           ),
  '420' => array(
             'parent' => 354
           ),
  '550' => array(
             'parent' => 420
           ),
);

/**
 *
 * This function will convert a flat array with elements to the proper hierarchy structure
 * @param array $array
 */
function hierarchy(&$array) {
    arsort($array);
    foreach($array as $key => $value)
    {
        if($value['parent'])
        {
            $array[$value['parent']]['children'][$key] = $value;
            unset($array[$key]);
        }
    }
    asort($array);
    return $array;
}

(print '<pre>' . print_r(hierarchy($array), true) . '</pre>');

Heres a testcase:
http://codepad.org/RT51uOfn


text:
Q: How to record human voice and display as text on command line? I am looking tool or a script that records human voice and displays as text purely on command line.
I am not looking for text to speech, but rather speech to text.
I do not want to work at all with a UI; all command line.
EDIT :
I am actually saying to record voice (speech) and displays on terminal.
Say my command is 'speak'
then when i do
$ speak

now whatever i speak is supposed to be printed like this.
say i speak. "I am application to record your voice and displays on the terminal"
should be visible as this :
$speak
I am application to record your voice and displays on the terminal

It should again wait for new words and print on the go.
Very similar as google does (BUT i want the same on command line) :
https://www.google.com/intl/en/chrome/demos/speech.html
You can consider the same as VICE-VERCA of say command. say is text-to-speech but here i want speech-to-text

A: Apple's terminal does this.
Press the function key twice to start dictation. If that doesn't work, open Speech and Dictation system preferences and enable it/select the sound input you prefer to dictate to.


text:
Q: How to customize tailwind typography blockquotes Tailwind typography, In order to add opening and closing quotes, add an after and before pseudo elements to blockquotes:

    :after

Lorem ipsum.

    :before

I want to customize the style removing just the closing quotes to match this pattern:

Is it possible customize it from tailwind.config.js or should I override styles with CSS and !important?

A: As described in this issue: https://github.com/tailwindlabs/tailwindcss-typography/issues/66#issuecomment-756834635
You can add following configuration to your tailwind.config.js:
module.exports = {
  theme: {
    // ...
    extend: {
      typography: {
        quoteless: {
          css: {
            'blockquote p:first-of-type::before': { content: 'none' },
            'blockquote p:first-of-type::after': { content: 'none' },
          },
        },
      },
    },
  },
  //...
}

and add the class prose-quoteless to your prose element afterwards to remove all quotes.


text:
Q: C++: which is the appropriate constructor to be called: the constructor or the copy constructor? The code
class ElisionTest
{
public:
    int n;
    // ElisionTest(ElisionTest& other): n(other.n) {cout<<"copy constructor"<<endl;}
    ElisionTest(int n): n(n) {cout<<"constructor"<<endl;}
};

int main(int argc, char const *argv[])
{
    ElisionTest et = 10;

}

prints "constructor" and that's fine. Now, when I uncomment the copy constructor, I get a compile time error:
cpp_test.cpp: In function 'int main(int, const char**)':
cpp_test.cpp:140:19: error: no matching function for call to 'ElisionTest::ElisionTest(ElisionTest)'
cpp_test.cpp:140:19: note: candidates are:
cpp_test.cpp:135:2: note: ElisionTest::ElisionTest(int)
cpp_test.cpp:135:2: note:   no known conversion for argument 1 from 'ElisionTest' to 'int'
cpp_test.cpp:134:2: note: ElisionTest::ElisionTest(ElisionTest&)
cpp_test.cpp:134:2: note:   no known conversion for argument 1 from 'ElisionTest' to 'ElisionTest& {aka ElisionTest&}'

Which probably goes on to show that here the copy constructor will be called with a temporary ElisionTest(10). And since you can't have a non-const reference to a temporary, making the argument of the copy constructor a const& should resolve the error.
But, if I modify the copy constructor to take const ElisionTest& instead of ElisionTest&, there's no error and the output is "constructor" again. Why didn't it print "copy constructor"?

A: ElisionTest(ElisionTest& other);

A constructor with that signature allows the initialization of an ElisionTest instance through an lvalue. When you do this:
ElisionTest et = 10;

This will construct an instance of ElisionTest from a temporary. Your code is equivalent to:
ElisionTest et = ElisionTest(10);

This will call your constructor that takes a non-const reference and initialize et with that. But a non-const reference cannot be bound to a temporary. That's why we will need to add const to your copy-constructor so that it can support both lvalues and rvalues:
ElisionTest(ElisionTest const& other);
//                      ^^^^^

The reason you are seeing no output is because of something called copy-elision. The compiler can omit the call to the copy/move constructor. In GCC, you can use -fno-elide-constructors to turn off copy-elision.

A: It outputs "constructor" because it needs to convert from 10 to ElisionTest.
It didn't also print "copy constructor" because it got optimized away (copy elision). That's the only possible optimization that is allowed to alter the observable behavior of a program.


text:
Q: How to do axios.get in react native? I am new to react native. I am trying to do axios.get(). But I am getting this in console:
        serverData: serverData
      })', '_this.setState' is undefined)]

_this.setState is not a function. (In '_this.setState({
    serverData: serverData
  })', '_this.setState' is undefined)

This my code:
export function FriendRequests ( ) {

state = {
    serverData: [],
};

axios.get('http://api.myslambook.in/swagger/#/users/', {
    auth: {
        username: 'xxxx',
        password: 'xxxxx'
    }
    }).then(res => {
        const serverData = res.data;
        this.setState({serverData});
    }).catch(err => console.log(err));
}

return (
    <SearchableDropdown
        items={this.state.serverData}
        defaultIndex={1}
        resetValue={false}
        textInputProps={
                    {
                        placeholder: "placeholder",
                        underlineColorAndroid: "transparent",

                    }
                    }
                    listProps={
                    {
                        nestedScrollEnabled: true,
                    }
     }
    />

)

}
I have edited my code and provided more details. Can anyone help? Thanks.

A: Hey you can handle axios in below approaches
Promise approach
componentDidMount(){
    axios.get('http://api.myslambook.in/swagger/#/users/', {
        auth: {
            username: 'xxxx',
            password: 'xxxxx'
        }
    }).then(res => {
        this.setState({
            serverData: res.data.serverData
        });
    }).catch(err => console.log(err));
}

Async/await approach
async componentDidMount(){
    try {
        let response = await axios.get('http://api.myslambook.in/swagger/#/users/', {
            auth: {
                username: 'xxxx',
                password: 'xxxxx'
            }
        })
        this.setState({
            serverData: response.data.serverData
        });
    } catch (error) {
        console.log(error)
    }
}

For more information check below example code.
import React from 'react';
import { FlatList, ActivityIndicator, Text, View  } from 'react-native';
import axios from 'axios';

export default class FetchExample extends React.Component {
    state = {
        isLoading: true
    }

  componentDidMount(){
    return axios.get('https://facebook.github.io/react-native/movies.json')
      .then(res => {
        this.setState({
          isLoading: false,
          dataSource: res.data.movies,
        });
      })
      .catch((error) =>{
        console.error(error);
      });
  }

  render(){
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.title}, {item.releaseYear}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}

Hope this helps you. Feel free for doubts.


text:
Q: Android. update ExpandableListView
I have the following problem:
I would like to change value of ExpandableListView's cell on click. How should I do that?
Here is what I'm using:
    public class TemplateActivity extends ExpandableListActivity {

     private SimpleExpandableListAdapter expListAdapter = null;

     protected void onCreate(Bundle savedInstanceState) {
  setContentView(R.layout.template_create);
     expListAdapter = new SimpleExpandableListAdapter(
    this, createGroupList(),
    R.layout.template_create_group_row,
    new String[] { KEY_GROUP },
    new int[] { R.id.create_template_groupname },
    createChildList(),
    R.layout.flower_template_create_child_row,
    new String[] { KEY_ATTRIBUTE_VALUE },
    new int[] { R.id.flowerx_text_attr }
  );

  setListAdapter(expListAdapter);

     }

 private List<HashMap<String, String>> createGroupList() {
  ArrayList<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();

  for (String entryKey: <ArrayOfGroupTitles>) {
   HashMap<String, String> m = new HashMap<String, String>();
   m.put(KEY_GROUP, entryKey);
   result.add(m);
  }

  return result;
 }

 private List<ArrayList<HashMap<String, Object>>> createChildList() {
  ArrayList<ArrayList<HashMap<String, Object>>> result = new ArrayList<ArrayList<HashMap<String, Object>>>();
  for (String entryKey: fieldsInList.keySet()) {
   ArrayList<HashMap<String, Object>> secList = new ArrayList<HashMap<String, Object>>();

   HashMap<String, Object> attrVal = new HashMap<String, Object>();
   attrVal.put(KEY_ATTRIBUTE_VALUE, String.valueOf(fieldsInList.get(entryKey).getFieldValue()));
   secList.add(attrVal);
   result.add(secList);
  }

  return result;
 }

Application is in progress stage, so attrVal will contain several attributes ( which can be put or not depend on some logic), so I'm using this type of adapter and this way of filling cells' data.
fieldsInList - external variable of LinkedHashMap type.
I have a function which can change one of the member's of fieldsInList variable.
How should I notify my expListAdapter or ExpanableListView to be refreshed?

A: expListAdapter.notifyDataSetChanged(); - to notify adapter that data has changed :
For onclick :
OnChildClickListener myOnChildClick = new OnChildClickListener() {

        @Override
        public boolean onChildClick(ExpandableListView arg0, View arg1, int arg2, int arg3,
                long arg4) {
            // TODO Auto-generated method stub
            return false;
        }

    };

and setOnChildClickListener(myOnChildClick); in onCreate

A: To update cells for expanableListView you should use List<ArrayList<HashMap<Object, Object>>> variable during creating adapter. It doesn't work for me first time, because I use internal method, which created new list. Maybe this fact is the cause of problem. As Alex said, you need call adapter.notifyDataSetChanged() to make the changes applied to the ExpandableList. Thanks


text:
Q: xpath for html table values I have a HTML like this:

       Text before Text1
       Text1
       Text after Text1

       Text before Text2
       Text2
       Text after Text2

I'm using lxml and Python. I want to use XPath to find Text after Text1 and Text after Text2
I tried XPath /html/body/table/tr and get the text of relative path ./td, but I can only get Text before Text1 and Text before Text2.
So how can I achieve this?
One example:

  海航HU7605
首都T1-虹桥/td>

I can find 海航 but can't find 首都T1-虹桥.

A: Pretend you file is in data.xml.
from lxml import etree

data = etree.parse('data.xml')

for row in data.xpath('/html/body/table/tr'):
    before, after = row.xpath('text()')
    print before, after

A: You can get Xpath Values like this
             "//tr"  or "//tr/td"


text: Q: What are the pros and cons of transforming data to unit variance (just scaling by std) vs standardizing ? This is prior to use it PCA on stock returns I am working with dataset of stock returns and plannig to use PCA. I need to decide on standardizing (centering the returns and then dividing by standard deviation) or simply dividing by std. The question is what are the pros and cons of both methods. Standardizing seems to be the default option, but by centering the data, I am getting rid of the "trend" on returns which I believe contains valuable information.


text:
Q: Python 3.x: Problems writing utf-8 strings to binary txt file I am currently working through "Learning Python the hardway" and try to alter one Excercise.
Objective: Write the binary equivalents of the languages in a new .txt file
import sys
script, encoding, error = sys.argv

def main(language_file, encoding, errors):
    line = language_file.readline()

    if line:
        print_line(line, encoding, errors)
        return main(language_file, encoding, errors)

def print_line(line, encoding, errors):
    next_lang = line.strip()
    raw_bytes = next_lang.encode(encoding, errors=errors)
    cooked_string = raw_bytes.decode(encoding, errors=errors)
    bin_file.write(raw_bytes + "\n".encode("utf-8"))
    print(raw_bytes, "<===>", cooked_string)

languages = open("languages.txt", encoding="utf-8")
bin_file = open("bin_languages.txt", "wb")
main(languages, encoding, error)

The majority of this code is from the learning example, that is why there is for understanding purposes an encode/decode of raw_bytes to cooked_strings and back again.
Unfortunately, the output file contains the same content as the original file. Is my approach not possible?
Thanks!


text:
Q: Jade render an array of strings as an array of string I'm passing data to render template:
res.render 'index', {data: ['a', 'b']}, function(err, html) {
});

in the template, I'd like to render the array ['a', 'b'] as an array in javascript:
script(type='text/javascript').
  var arr = #{data};

but they are rendered as [a, b], an array of variables, what I want is variable names: ['a', 'b'].
Thanks

A: First you need to JSON.stringify the data property object.
...
data: JSON.stringify(['a', 'b'])
...

Then in your Jade Template use !{}.
var arr = !{data}; // ["a","b"];


text:
Q: How to store Android keyboard activity like any text type by other app and send it across Internet in background? I would like to know how to store other application's keyboard activity  like capture passwords or userid as the user types and send it across Internet? Is there any mechanism built into Android that would do that?

A: Another methods are also there to identify a user is typing
For example if you implement TextWatcher you can get it the facility like when user type somethings you can call any webservice to get notified.
For TextWatcher follow the link :How to use the TextWatcher class in Android?
For Web Service implement your own or use third party.
Thanks hope this will help you.

A: What you're referring to is known as a remote keylogger. It would be highly unlikely for Google, or the maintainers of Android operating systems to implement any malicious code into their work.
If you're referring to purchasing items from the App store and using them, then it's possible, but I have not heard of it. App store apps found to be malicious in nature would be quickly outed and their producer(s) would be outed.


text:
Q: what does that statement mean about the relation? what does this mean about P?
$$\forall x \exists y (p(x,y) \rightarrow p(y,x)) $$
i know that
$$\forall x \forall y (p(x,y) \rightarrow p(y,x)) $$
means that P symmetric
but what does the first statement means?
and what does the last statement mean about the relation P?
$$\forall y (\exists x P(x,y) \rightarrow \exists x P(y,x)) $$

A: $\forall x \exists y (p(x,y) \rightarrow p(y,x))$ says that for each $x$ there is a $y$, which may depend on $x$, such that if $p(x,y)$, then also $p(y,x)$. Let me write $xPy$ to mean $p(x,y)$.
Suppose that the statement is true, and fix a particular $x$. Then there's some $y$, perhaps only one, such that $xPy\to yPx$. Under what circumstances is this true? The only time it's false is when $xPy$ is true and $yPx$ is false; it's true whenever $xPy$ is false, or $yPx$ is true, or both. Thus, if you can find a $y$ such that $x(\lnot P)y$, that $y$ works: $xPy\to yPx$ is vacuously true, because $xPy$ is false.
What if $xPy$ for every $y$, so that you can't find such a $y$? If you can find a $y$ such that $yPx$, you can use it, because then $xPy\to yPx$ is true.
The only time you're out of luck is when $xPy$ for every $y$, and there is no $y$ such that $yPx$: then no matter what $y$ you pick, $xPy$ is true and $yPx$ is false, so $xPy\to yPx$ is false.
$\forall x \exists y (p(x,y) \rightarrow p(y,x))$ therefore says that for each $x$ there is a $y$ such that either $x(\lnot P)y$, or $yPx$ (or both). Alternatively, it says that there is no $x$ such that for every $y$, $xPy$ and $y(\lnot P)x$: there is no $x$ that is related to everything but not from anything.
In fact, though, this is trivially true. Pick any $x$; if $xPx$, then $xPx\to xPx$, and we can simply let $y=x$. If $x(\lnot P)x$, then again $xPx\to xPx$, this time vacuously (because the antecedent is false), and we can let $y=x$. Thus, $\forall x \exists y (p(x,y) \rightarrow p(y,x))$ is true of any relation, because for each $x$ we can take $y=x$ and have $p(x,y) \rightarrow p(y,x)$.
The statement $\forall y (\exists x P(x,y) \rightarrow \exists x P(y,x))$ is quite different. In terms of relations it says that each $y$ that is related from something is also related to something, but not necessarily the same thing. Consider, for instance, the relation $P$ on $\{0,1,2,3,4\}$ defined by $0P1P2P3P4P0$; that is, under $P$ the elements $0,1,2,3$, and $4$ form a circular chain. This relation satisfies the statement in question: for each $k\in\{0,1,2,3,4\}$, if there is some $m$ such that $mPk$, then there is some $n$ such that $kPn$. I could throw $5$ into the set without changing $P$, and $P$ would still have the property: there is no $m$ such that $mP5$, so the statement $\forall y (\exists x P(x,y) \rightarrow \exists x P(y,x))$ says nothing about $5$. But if I also add $3P5$, say, in order to keep the property I have to add $5Pk$ for at least one $k$.


text:
Q: Difference in speed between "not in " and "except " in PostgreSQL Forgive me for the vague title. I couldn't think of anything better, do feel free to suggest a better title.

I have been using this query in a web application with PostgreSQL for a really long time (7 Years).
asset_snapshot is the read data from a lot of IoT devices, and it truncates and reinserts data into that table every 1 minute. The maximum size (now of rows) of asset_snapshot data is 5000-10000 rows.
The aim of this query to is to return the most recent time of devices that has never been seen before.
query 1
        select *
        from location_aasset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifiter, max(last_seen) as last_seen from
                    location_asset_snapshots
                    where unique_identifier not in (select unique_identifier from location_assets)
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen

A couple of weeks ago the time to execute this query started to become 10 seconds. The reason we found that is the size of the assets table crossed to 200,000 records.
We found out that if we used except instead of not in the query retuned back to its normal speed again.
query 2:
        select *
        from location_asset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifier, max(last_seen) as last_seen from
                    location_asset_snapshots
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen
      except
      select *
        from location_asset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifier, max(last_seen) as last_seen from
                    location_asset_snapshots
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen
        where t1.unique_identifier in
        (select unique_identifier from location_assets)

Was curious to learn if there was something built in PostgreSQL that makes the second query runs faster with a growing dataset.
plan for query 1:
Hash Join  (cost=4413874.90..4413897.95 rows=2 width=90)
  Hash Cond: (((t1.unique_identifuer)::text = (location_asset_snapshots.unique_identifuer)::text) AND (t1.last_seen = (max(location_asset_snapshots.last_seen))))
  ->  Seq Scan on location_asset_snapshots t1  (cost=0.00..19.93 rows=593 width=57)
  ->  Hash  (cost=4413870.76..4413870.76 rows=276 width=33)
        ->  GroupAggregate  (cost=4413863.02..4413868.00 rows=276 width=33)
              Group Key: location_asset_snapshots.unique_identifuer
              ->  Sort  (cost=4413863.02..4413863.76 rows=296 width=33)
                    Sort Key: location_asset_snapshots.unique_identifuer
                    ->  Seq Scan on location_asset_snapshots  (cost=0.00..4413850.87 rows=296 width=33)
                          Filter: (NOT (SubPlan 1))
                          SubPlan 1
                            ->  Materialize  (cost=0.00..14344.52 rows=216768 width=25)
                                  ->  Seq Scan on location_assets  (cost=0.00..11778.68 rows=216768 width=25)

Plan for query 2:
HashSetOp Except  (cost=39.88..141.00 rows=3 width=176)
  ->  Append  (cost=39.88..140.88 rows=6 width=176)
        ->  Subquery Scan on "*SELECT* 1"  (cost=39.88..63.02 rows=3 width=94)
              ->  Hash Join  (cost=39.88..62.99 rows=3 width=90)
                    Hash Cond: (((t1.unique_identifuer)::text = (location_asset_snapshots.unique_identifuer)::text) AND (t1.last_seen = (max(location_asset_snapshots.last_seen))))
                    ->  Seq Scan on location_asset_snapshots t1  (cost=0.00..19.98 rows=598 width=57)
                    ->  Hash  (cost=32.63..32.63 rows=483 width=33)
                          ->  HashAggregate  (cost=22.97..27.80 rows=483 width=33)
                                Group Key: location_asset_snapshots.unique_identifuer
                                ->  Seq Scan on location_asset_snapshots  (cost=0.00..19.98 rows=598 width=33)
        ->  Subquery Scan on "*SELECT* 2"  (cost=40.30..77.82 rows=3 width=94)
              ->  Nested Loop  (cost=40.30..77.79 rows=3 width=90)
                    ->  Hash Join  (cost=39.88..62.99 rows=3 width=90)
                          Hash Cond: (((t1_1.unique_identifuer)::text = (location_asset_snapshots_1.unique_identifuer)::text) AND (t1_1.last_seen = (max(location_asset_snapshots_1.last_seen))))
                          ->  Seq Scan on location_asset_snapshots t1_1  (cost=0.00..19.98 rows=598 width=57)
                          ->  Hash  (cost=32.63..32.63 rows=483 width=33)
                                ->  HashAggregate  (cost=22.97..27.80 rows=483 width=33)
                                      Group Key: location_asset_snapshots_1.unique_identifuer
                                      ->  Seq Scan on location_asset_snapshots location_asset_snapshots_1  (cost=0.00..19.98 rows=598 width=33)
                    ->  Index Only Scan using for_upsert_unique_identifuer on location_assets  (cost=0.42..4.93 rows=1 width=25)
                          Index Cond: (unique_identifuer = (t1_1.unique_identifuer)::text)

A: There is no inherent difference between EXCEPT vs NOT IN logically, and one is not necessarily more performant than the other. Additionally 200,000 rows is a relatively small amount of data.
You likely had a Cardinality Estimate (also known as Row Estimation) issue or your query started using a different index or index operation (e.g. scan instead of seek). When you switched to EXCEPT that likely caused a recompilation of the query plan to a more performant plan.
Without having the EXPLAIN of both queries, it's hard to say exactly what changed, but that's generally likely the two cases that you could've experienced.

A: While not an answer to your question as posed, if your ultimate goal is to improve the performance of the query then perhaps rewriting the query would be a better long term solution (basically, I'm trying to answer the question that I think lies behind the question asked).
Not knowing anything about your table structure or data, the following example is speculative but may still be of benefit. Note that, for the purpose of of this example, I've created a much larger test table (in order to amplify any differences) so YMMV, etc.
CREATE TABLE location_asset_snapshots AS
    SELECT ( random () * 1000000 )::integer AS unique_identifier,
            now () - ( ( ( random () * 1000 )::integer )::text || ' day' )::interval AS last_seen
        FROM generate_series ( 1, 100000000, 1 ) ;

SELECT 100000000
Time: 286039.624 ms (04:46.040)

CREATE TABLE location_assets AS
    WITH x AS (
        SELECT unique_identifier
            FROM location_asset_snapshots
            WHERE random () < 0.5
    )
    SELECT DISTINCT unique_identifier
        FROM x ;

SELECT 1000001
Time: 90950.436 ms (01:30.950)

Attempting the original (NOT IN) query:
select count (*) from (
     select *
        from location_asset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifier, max(last_seen) as last_seen from
                    location_asset_snapshots
                    where unique_identifier not in (select unique_identifier from location_assets)
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen
) x ;

For what it is worth, I cancelled the operation after having let it run for the better part of a half-hour.
Next up was testing the second (EXCEPT) query:
select count (*) from (
       select *
        from location_asset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifier, max(last_seen) as last_seen from
                    location_asset_snapshots
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen
      except
      select *
        from location_asset_snapshots t1
        INNER JOIN (
                    SELECT unique_identifier, max(last_seen) as last_seen from
                    location_asset_snapshots
                    group by unique_identifier
                    ) t2
        on t1.unique_identifier = t2.unique_identifier and t1.last_seen = t2.last_seen
        where t1.unique_identifier in
        (select unique_identifier from location_assets)
) x ;

This query did finish but still took just over 8 minutes. So, much better but still not great.
Then there is using NOT EXISTS as suggested by @a_horse_with_no_name :
select count (*) from (
    SELECT *
        FROM location_asset_snapshots t1
        INNER JOIN (
            SELECT las.unique_identifier,
                    max ( las.last_seen ) AS last_seen
                FROM location_asset_snapshots las
                WHERE NOT EXISTS (
                    SELECT 1
                        FROM location_assets la
                    WHERE la.unique_identifier = las.unique_identifier )
                GROUP BY las.unique_identifier
            ) t2
            ON ( t1.unique_identifier = t2.unique_identifier
                AND t1.last_seen = t2.last_seen )
) x ;

This took between 30 seconds to just over a minute to run.
Another option is to rewrite the query is to make use of a LEFT OUTER JOIN as follows:
select count (*) from (
    SELECT *
        FROM location_asset_snapshots t1
        INNER JOIN (
            SELECT las.unique_identifier,
                    max ( las.last_seen ) AS last_seen
                FROM location_asset_snapshots las
                LEFT JOIN location_assets la
                    ON ( la.unique_identifier = las.unique_identifier )
                WHERE la.unique_identifier IS NULL
                GROUP BY las.unique_identifier
            ) t2
            ON ( t1.unique_identifier = t2.unique_identifier
                AND t1.last_seen = t2.last_seen )
) x ;

Using the LEFT OUTER JOIN consistently took ~ 1:15 to run.
Finally, one other approach that could be taken is to use the row_number windowing function as follows:
select count (*) from (
    SELECT *
        FROM (
        SELECT las.*,
                row_number () OVER (
                    PARTITION BY las.unique_identifier
                    ORDER BY las.last_seen desc
                    ) AS rn
            FROM location_asset_snapshots las
            LEFT JOIN location_assets la
                ON ( la.unique_identifier = las.unique_identifier )
            WHERE la.unique_identifier IS NULL
        ) x
        WHERE rn = 1
) y ;

Which showed performance similar to the NOT EXISTS approach.
In summary:

Approach
Time

NOT IN
> 28:00

EXCEPT
~ 8:00

NOT EXISTS
0:30 - 1:15

LEFT OUTER JOIN
~ 1:15

row_number ()
0:30 - 1:15


text:
Q: mysql statement for adding multiple columns whether they exist or not I'm trying to write an update mysql statement for a software program. Currently this is what I have for the statment, but I don't now how to add multiple columns to update.
This code currently adds the column whether it's there or not.

/*delimiter '//'
CREATE PROCEDURE addcol() BEGIN
IF NOT EXISTS(
SELECT * FROM information_schema.COLUMNS
WHERE COLUMN_NAME=`top_status` AND TABLE_NAME='categories'
)
THEN
ALTER TABLE `categories`
ADD COLUMN `top_status` tinyint(1) NOT NULL default '1';
END IF;
END;
delimiter ';'
CALL addcol();
DROP PROCEDURE addcol;*/

Can someone supply me with the correct statement to get something like this to work...ie. WHERE COLUMN_NAME = column1, column2 etc..
I've tried all kinds of variations and all of them return an error in phpmyadmin except the above.

A: Use ALTER TABLE statement to add multiple columns to a table:
ALTER TABLE TableName
ADD (column1 col_definition,
column2 col_definition,
column3 col_definition,
....      ......
....      ......
columnN col_definition);

A: Surely you want to individually test for the existence of the new columns, and add each one individually if it doesn't already exist?
If you want the INFORMATION_SCHEMA query to test for the existence of any of the columns column1, column2 etc. you can use an IN statement. If you want to test whether they all exist then you can use IN and instead of checking whether the resultset is empty, select a COUNT(*) and check whether the count returned is the expected number (the number of columns involved).


text:
Q: How can I remove displays that don't actually exist? I have an MSI gaming laptop, on which I am running the latest version of Windows 10 Pro.  I plug in an additional 34-inch ultra-wide-screen monitor via HDMI, so I have two monitors.  But in my Display Settings I see something quite strange:

I do not have, nor have I ever had, six monitors.  I have tried everything to remove the references to those monitors by opening the Multiple Displays drop-down and disabling monitors 3, 4, 5 and 6--all to no avail.
While the set-up works well, it suffers from one problem.  Occasionally when I open a new window, it goes to one of the non-existent monitors, and I have to use the Windows and arrow keys to bring it to one of my existing monitors.
How can I remove the references to these ghost monitors?
Thanks in advance for your help.

A: On the rare occasions that I have seen this happen before, it is usually caused by the display driver.
Faced with the same scenario, I would manually create a System Restore point as a potential fall-back and then check for an updated graphics driver to install.  If you are already running the latest version, try dropping back to an older version and see if it alleviates the problem.


text:
Q: How many singular values to keep in the R package lsa I used the function lsa in the R package lsa to get the semantic space. The input is a term-document matrix. The problem is that the dimcalc_share() function used by lsa by default seems to be wrong. The help page of the function says the function "finds the first position in the descending sequence of singular values where their sum meets or exceeds the specified share." I understand the words as the function keeps the nth largest singular values such that the sum of these values exceeds a certain percentage of the sum of all singular values.
The function's source code is
function(share=0.5)
{
    function(x){
        if(any(which(cumsum(s/sum(s))<=share))){
            d=max(which(cumsum(s/sum(s))<=share))+1
        }
        else{
            d=length(s)
        }
        return(d)
    }
}

I have two questions with the source code:
1. why plus 1 to the d?
2. if the fraction of the first singular value is larger than share, the function will keep all singular values, while I suppose the function should just keep the first one.

A: Your first question is "why the + 1?"
Let's look at how these functions work:
# create some files
td = tempfile()
dir.create(td)
write( c("dog", "cat", "mouse"), file=paste(td, "D1", sep="/") )
write( c("ham", "mouse", "sushi"), file=paste(td, "D2", sep="/") )
write( c("dog", "pet", "pet"), file=paste(td, "D3", sep="/") )

# LSA
data(stopwords_en)
myMatrix = textmatrix(td, stopwords=stopwords_en)
myMatrix = lw_logtf(myMatrix) * gw_idf(myMatrix)
myLSAspace = lsa(myMatrix, dims=dimcalc_share())
as.textmatrix(myLSAspace)

             D1         D2         D3
cat   0.3616693  0.6075489  0.3848429
dog   0.4577219  0.2722711  1.2710784
mouse 0.5942734  1.3128719  0.1357196
ham   0.6075489  1.5336529 -0.1634938
sushi 0.6075489  1.5336529 -0.1634938
pet   0.6099616 -0.2591316  2.6757285

So, lsa gets dimensions from dimcalc_share() based on the input matrix and a given share (.5 by default) and runs a Singular Value Decomposition to map the original TDM to a new LSAspace.
Those dimensions are the number of singular values for the dimensionality reduction in LSA.
dimcalc_share() finds the first position in the descending sequence of singular values s where their sum (divided by the sum of all values) meets or exceeds the specified share.
The function is written such that it d is equal to the max() position <= share:
> # Break it apart
> s <- myMatrix
> share <- .5
>
> any(which(cumsum(s/sum(s)) <= share)) #TRUE
[1] TRUE
> cumsum(s/sum(s)) <= share
 [1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> d = max(which(cumsum(s/sum(s)) <= share)) + 1
> d
[1] 10

If you only used d -1, which would give you 9 instead of 10, then you'd instead have a position where the cumsum is still <= to share. That wouldn't work:
> myMatrix = lw_logtf(myMatrix) * gw_idf(myMatrix)
> myLSAspace2 = lsa(myMatrix, dims=d-1)
Error in SVD$u[, 1:dims] : subscript out of bounds

Equivalently
> dims = 9
> myLSAspace = lsa(myMatrix, dims)
Error in SVD$u[, 1:dims] : subscript out of bounds

So the function dimshare_calc() is correct in using + 1.
Your 2nd question, modified for this example, is "would dimcalc_share() = 18 instead of = 1 if the first value was > share?"
If the first value were > share then the first if condition would return false and, as you hypothesized, would instead use length(s) which is 18.
You might follow up with a question on CrossValidated to confirm that your intuition that it should = 1 is correct (though that makes sense to me). If so, it would be simple to re-write the function with d = 1 as the else.


text:
Q: How to delete a line from files in subfolders using Unix commands? I've a folder structure where the starting folder is test. test has two folders in it. test1 and test2, plus a bunch of files. There's a word welcome in these bunch of files as well as the files in test1 and test2. I tried this and it did not work
sed 's/\<welcome\>//g' **/*

What am I doing wrong? How can this be done?

A: This might work for you (GNU sed):
find test -type f -exec sed -i '/welcome/d' '{}' \;

A: Try doing this (GNU sed):
sed -i '/welcome/s/\<welcome\>//g' test/*

The -i switch modify the files, so take care.
If -i switch is not supported on your Unix :
for i in test/*; do
    sed '/welcome/s/\<welcome\>//g' "$i" > /tmp/.sed && mv /tmp/.sed "$i"
done

A: sed -e 's/welcome//g' test > test2
The file test has several entries including welcome.
This above sed line deletes welcome from test.
You could put it in a loop..
And I see that sputnick has just answered your question to a large extent! :P

A: find . -type f|xargs perl -ni -e 'print unless(/<welcome>/)'


text:
Q: Translate IP address at router I'm not sure if this is possible, and if it is possible surely it is frowned upon but... is it possible to perform dynamic translation of an IP address on a Cisco 3650 L3 router?
Here is the scenario:

*

*Multiple clients exist on subnets 10.0.1.0/24 to 10.0.100.0/24.

*Clients transmit data to server 10.101.0.1/24.

*The server's IP address will change to 10.201.0.1/24.

*The clients must continue to transfer data to the server, but the server IP setting cannot be changed on the client (i.e. clients will continue to send data to 10.101.0.1/24).

*Routing between these three networks is carried out by a Cisco 3650 L3 router.

*The clients do not have DNS configured.

*Basically, the client settings cannot change.

I am thinking that maybe there is some funky layer three magic could happen at the Cisco switch that would allow for dynamic translation between 10.101.0.1 and 10.201.0.1 so that clients would be able to continue to send data to the server without modifying any client settings.
Is this scenario possible? If it is, what specific Cisco configuration would be needed, and what strange drawbacks/ramifications could be expected?


text:
Q: Redo method using Activator.CreateInstance how might I redo this method with Activator.CreateInstance
    Public Overridable Function setCreditType() As CreditType
    Select Case creditTypeId
        Case Is = 0
            Return New NewCredit(Me)
        Case Is = 1
            Return New ExecutiveProducer(Me)
        Case Is = 2
            Return New Producer(Me)
        Case Else
            Return New NullCredit(Me)
    End Select
End Function

A: The most literal response is something like this:
Dim t As Type = GetType(Foo) 'Get Foo from somewhere
Dim ctorArgs() New As Object { Me }
Return (CreditType)Activator.CreateInstance(t, ctorArgs)


text:
Q: ¿Como puedo abrir el CMD sin el proceso "explorer.exe", o desde el menu Ctrl+Alt+Supr? Muy buenos días a todos.
Últimamente estoy intentando conseguir abrir el CMD desde un menú de teclas rápido, o intentando añadirlo al menu de Ctrl+Alt+Supr, Pero todavia no he conseguido nada.
Mi objetivo es abrir el CMD con un atajo de teclas, y que funcione aun con el proceso explorer.exe eliminado.
Muchas gracias, y buenos días.

A: Puedes abrirlo con las teclas "Windows + R" después escribiendo cmd y enter.

A: Pues, presionando shift + click derecho te sale la opción abrir ventana de comando


text:
Q: Can ASP.NET performance be improved with modules/static classes? Can using Modules or Shared/Static references to the BLL/DAL improve the performance of an ASP.NET website?
I am working of a site that consists of two projects, one the website, the other a VB.NET class library which acts as a combination of DAL and BLL.
The library is used to communicate with  databases and sometimes transform/validate the data going into/coming from the DBs.
Currently each page on the site that needs db access (vast majority) will create an instance of the relevant class in the library to access specific tables.
As I understand it this leads to a class from the library being instantiated and garbage collected for each request, with the possibility of multiple concurrent instances if multiple users view the same page.
If I converted the classes to modules (shared/static class) would performance increase and memory be saved as only one instance of each module exists at a time and a new instance is not having to be created for each request?

(if so, does anyone know if having TableAdapters as global variables in the modules would cause problems due to threading?)
Alternatively would making the references to the Library class it the ASP.NET page have the same effect? (except I would have to re-write a lot less)

A: I'm no expert, but think that the absence of examples of this static class / session object model in books and online is indicative of it being a bad idea.
I  inherited a Linq-To-Sql application where the db contexts were static, and after n requests the whole thing just fell apart. The standard model for L2Sql is the Unit-of-Work pattern (define a task or set of tasks - do them and close). Let the framework worry about connection pooling and efficient GC.
Are you just trying to be efficient or do you have performance issues? If the latter it's usually more effective to look at caching or improving query efficiency (use stored procedures, root out queries in loops) than looking at object instantiation.
Statics don't play well with unit tests either (another reason why they have dropped out of fashion).

A: instances are only a problem if they are not collected by the CG (a memory leak). Instances are more flexible than static as well because you can configure the instance to the specific context you are using.
When an application has poor performance or memory problems its usually a sign that

*

*instances are not properly released (IDisposable)

*the amount of data retrieved is too big (not paging large sets of data)

*a large number of queries are executed (select n+1, or just a lot of queries)

*poorly constructed sql statements (missing indexes, FK, too many joins, etc)

*too many remote calls (either to other servers, or disk)

These are first things I would check. then start looking at the number of instantiated objects. Chances are that correcting the above mentioned list will solve most performance bottlenecks.

A:
Can using Modules or Shared/Static references to the BLL/DAL improve
  the performance of an ASP.NET website?

It's possible, but it depends heavily on how you use your data. One tradeoff in using a single shared instance of an object instead of one per request is that you will need to apply locking unless the objects are strictly read-only, and locking can both slow things down and complicate your code (not to mention being a common source of bugs).
However, if each object is going to contain the exact same data, then the tradeoff may be worth it -- even more so if it can save a DB round-trip.
You might consider using either a Singleton or a small number of parameterized objects rather than a static, though -- and use caching to manage them. That would give you the flexibility to let go of objects that you no longer need, which is harder to do when you're dealing with statics.


text:
Q: How does Dynamo DB handle pagination So I am using Pagination with the latest DynamoDBEnhancedAsyncClient.
I had a doubt as to how does the DynamoDB handle pagination? Is it that it queries DDB and gets back the result for the 1st page and then again hits DDB to fetch records for the 2nd fetch? Does it the DB as many times as the number of pages? I couldn't find any information related to this in AWS docs.

A: Yes it hits the database for each page of data. There are limits of how much data DynamoDB will return in a single result, so it has to do it this way. The general mechanism for pagination in DynamoDB is documented here.


text:
Q: Managing Code Written for learning I want to ask about the different techniques they used to remember various programming techniques. We go through various books and various online tips and tutorials we also get so many ideas from the code written by somebody else.
Now all these inputs are memorized or stored in some format so that it can be found easily when referred. Absence of such storage may result in rewriting the code or reinventing the wheel.
I use to create one Working folder where I keep all my trial code but sometime after few days / months since the code is not tagged or named properly its difficult to find it out again.

A: For Perl, I have a module I call staging.pm, and use staging; is a pragma in my code which allows me to use experimental, not fully developed code in my development. This developmental code will be placed in a branch called "staging" off of the user library directory. The main thing that the module does is put my staging directory at the head of @INC. Once my code is mature--if it ever is--it will be moved into my user lib directory.
As for scripts, they can be run from wherever they are and I use a directory named test off of the bin directory.
So that's kind of my approach. I don't know how useful that is for you.

A: Well, for me, when I am trying to learn, I focus on learning the approach to solve the program, rather than a technique. That is important to me. Also, with regular day to day programming some techniques become ingrained.
The other thing I do is to maintain a notebook with my notes in it, code snippets, comments, shortcuts I have learnt over the years. This helps too.
Recently I have taken to maintaining my notes in Evernote, this makes is easy to search for and tag.

A: For web, I use Delicious + Firefox plugin to store what I already read.
When looking for a solution to something I can't solve, I got used to ask / search here.
And for my own solutions, I try to create reusable components and remember in which project I solved what and eventually get back to it later when I need it.

A: Whenever you study one programming technique like java you always map the corresponding things with C++ and perl.Java and C++ remain same in more concepts.And better you store your working folder in your mails so that whenever you need you can download and have it.

A: You could try a program like Surfulater. I don't know how well it works with code samples, but I do know that the developer was (is still?) active on the Joel on Software forums, so I'm sure he could be contacted with any specific questions.

A: If you use Windows, you can use Google Desktop to index part of your harddrive, including your program snippets.
If you can recall just some of it, Google will find it.
(Spotlight does the same automatically on a Mac)

A: It's like learning any other language or learning any other technique. When you read a book and you find it interesting you start associating what you are reading with real life situations and problems that you might have had before which the new learnt stuff will solve for you.
You might, after a couple of days or so forget what you have learned, untill you stumble upon the problem which you related to when reading the book or looking at the lecture. This specific type of memory is called something like association memory technique.
There are a lot of other different techniques to remember things by but a lot of them come down to relationships with other parts of what you already know.
Another example is Math which is something you force your brain to understand but once you quit using it on a daily basis you will slowly degenerate the math-genious-cells.
Programming for me at least is just another way to express myself and when i learn new features it's just a new way to express things that might not have been easy to do before.
Edit
I might have missunderstood the question.. did i?

A: On Mac OS X, TextMate provides a near perfect solution to this problem. TextMate is a programming editor that offers support for hundreds of programming languages and is customizable via the bundle editor. Through the bundle editor, you can add any snippet of code that you may want to memorize, and appropriately categorize it under its respective language. You can also assign hot-keys or character sequences to invoke a snippet and copy it to your current editing context.
I believe that Notepad++ is a similar tool for Windows, but I am unsure if it is as customizable as TextMate.