text:
Q: What happens when a computer "goes to sleep"? What happens when a computer goes to sleep? Should I sleep my computer or should I power it down? Is there an appropriate use for each mode or is it just a matter of personal preference?

A: I'll cover the three common states of a machine: sleep, hibernation, and powered off.

Sleep Mode
Sleep mode is essentially like taking a nap. Your computer is still on, but it is in a low-power state. It will consume less power and often disable hardware and suspend software to assist in reducing power consumption. This often involves disabling USB, PS/2, S/PDIF, audio, video, and other ports. Certain pieces of hardware, such as a wireless card, could also be disabled during this time.
The current session is stored in memory (RAM) and then the memory is placed in a low-power state. The memory still requires a current as otherwise it will decay and the session would be corrupted or lost entirely. During this time, the CPU is not executing any instructions; the storage mediums are also not doing anything.
When you resume the session (often by pressing the power button, moving the mouse, or tapping a key on the keyboard), the system immediately re-enables all of the previously disabled hardware and is pretty much ready to go. There will be a one or two second wait on any modern machine, but that's hardly anything to complain about.

Hibernation
Hibernation is a slower, prolonged version of sleep. It writes the contents of memory and other critical instructions for the system to resume the session to disk and then powers off the machine properly. This is not to be confused with sleep mode, as while hibernating the computer could be unplugged and moved around and still preserve the session. This is safer than sleep mode, but obviously when you turn the machine back on, it is going to have to go through power-on self-test (POST) and then restore RAM contents from disk. It does not, however, have to boot the OS again. And just as with Sleep mode, when it comes back up all the programs you had open will still be open and in the state you left them in.

Shutting Down
Powering a machine off is pretty obvious. In Windows (and other operating systems), a check is made to ensure that other users are not logged in and whatnot. Applications are also informed that the system is shutting down and can possibly stop the shutdown from occurring if something needs attention. Afterwards, the system logs out the users and then the system begins to "unload" critical system components that the operating system needs to run in the first place. After all of that has wrapped up, the operating system halts the machine; in other words, it stops power reaching the components in a safe manner.

Hybrid Sleep Mode
I would like to note that there is a "hybrid sleep mode" that basically combines both hibernation and sleep mode properties. The system will do both actions: write the instructions to disk and store them in memory and place the machine in a low-power state. However, in the event of power loss, the machine can just be turned on again properly and the session will be resumed. If the machine doesn't lose power, then the session should restore as if it was in sleep mode.

Security (of Sleep Mode)
EDIT: this was suggested in a comment. Thanks!
Another concern you might have is security.
As sleep mode is the only option where the machine is technically on, I'll only talk about that. As well, hibernation should lock the session whenever the machine is resumed anyway, as it requires a restart of the machine and operating system.
Obviously, someone coming along and continuing your session without permission is bad. However, by default on Windows operating systems (on some Linux desktop environments, and probably on OSX too), sleep mode should automatically lock the machine on session resume after a specific period of inactivity. If it isn't set to default (it might be my Windows image that has this), then it's easy enough to go into Power Options and change how Windows/OSX/Linux handles sleep mode.
As mentioned above, it is unlikely your network interfaces are active during the period of sleep. In theory, it would be impossible for any kind of network traffic to interact with your machine as the network interfaces should simply be powered off in the first place. In short, it shouldn't be a problem.
Typically, the only concern here is someone else having physical access to the machine. If you live in an environment where no one else will disturb it (or you don't mind them disturbing it), then there's not much of a security concern with using sleep mode.

What is Best
If you're asking "what is best", then I would argue that nothing is better than a healthy shutdown. Hibernation, while it DOES shutdown the machine, does not do other critical housekeeping measures (such as completely purging memory and killing zombie processes). By properly shutting down your system, you are essentially cleaning out the "gunk" that amasses throughout the life of a session. The longer your session lives (so, the more sleeps/hibernations your computer goes through) is often bad for the performance of the system. I won't delve into that further, though, as it is outside of the scope of this question.
If you just scrolled down to the bottom to read what someone thinks you should use, here you go: be patient and just shut down your system.

A: In sleep mode the CPU powers down to it's minimum state, the hard drives are powered off, the screen is powered off, and the USB ports are either powered on or off depending on the BIOS and OS settings (you may want to leave the USB ports powered on so that you can wake up the computer by pressing a key on the keyboard).
The main component that stays powered up is RAM memory - this allows a fast restart because the OS and programs don't have to be reloaded from disk. Also, again depending on the BIOS and OS settings, the system can be woken up by a timed event or by special network packets.


text:
Q: Java - stuck and confused with if statement I'm a bit stuck. I want my program to accept 0 and non 0 numbers, but if that non 0 number is above or below a certain integer, it will not work. Hopefully that makes sense.
Here's what I have:
    if (pos != 0 || pos == 0)
    {

        System.out.println ("\nLength of int: " + len);
        System.out.println ("Position from right: " + pos);
        System.out.println ("Number selected: " + String.valueOf (nums).charAt (s));

    }

    else if (pos < len || pos > len)
    {
        System.out.println ("\n0");

    }

If anyone wants to see the full code, it's right here: http://pastebin.com/bFVYNhvr
Any help is appreciated

A: change your logic around the other way
if (pos < len || pos > len)
{
    System.out.println ("\n0");
}
else
{
    System.out.println ("\nLength of int: " + len);
    System.out.println ("Position from right: " + pos);
    System.out.println ("Number selected: " + String.valueOf (nums).charAt (s));
}

As @Vinod mentioned
if (pos < len || pos > len)

can be better written as
if (pos != len)

if that is indeed your intention

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get String value from other generated equivalent string How it will print welcome using following System.out.println.
Generated will give ac. But how should I make it as welcome (that ia ac value not "ac")
public class BrowserSample {

  public static void main(String[] args) {
    String generated = "ac";
    String ac = "welcome";
    System.out.println("value from generated is = " + generated);
  }
}

A: ok After a brief experiment here is the solution you want
String generated = "ac";

String ac = "welcome";  // declare as member of class

String s = (String) getClass().getDeclaredField(generated).get(this);

s will contain welcome

A: What about a map, key-value pair.
Map<String,String> map = new HashMap<>();
String generated = "ac";
map.put("ac","welcome")
System.out.println("value from generated is = "+map.get("ac"));

And what you are expecting that is not possible and also meaningless.


text:
Q: yii2 hasOne relation work wrong I have 2 tables : users and favorite the following :

now I establish a relation between them like the following in Favorite model
public function getUser()
{
    return $this->hasOne(User::className(), ['id', 'user_favorited']);
}

in Controller I find a list of user's favorites
public function actionGetList()
{
    $favorite = Favorite::find()->where([
              'user_favoriting' => Yii::$app->user->id
          ])->all();
    foreach ($favorite as $key => $item) {
        # code...
        echo "<pre>"; var_dump($item->user); echo "<br/>"; die('123');
    }
    return $favorite;
}

But when I make a request to this action I get an error
Column not found: 1054 Unknown column '0' in 'where clause'\nThe SQL being executed was: SELECT * FROM `users` WHERE (`0`, `1`) IN ((12, 80))",

Please help me!

A: According to documentation you have to use:
public function getUser()
{
    return $this->hasOne(User::className(), ['id' => 'user_favorited']);
}


text:
Q: ModalPopup Not Showing in ASP.Net I've done everything. Deleted the code and dragged new controls from the toolbox, renamed, tried from javascript -- I just can't get this freakin' modalpopupextender to show. Wasted 3 days.
I'm trying to show it via VB code-behind in the on-click even of the login button. Everything else executes in the button's code, just not this line:
Me.ModalPopupExtender2.Show()

But no matter what I try, it likes to stay hidden.
Any ideas would be welcome!!! Thanks,
Jason
PS -- here's the aspx coding
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Login.aspx.vb" Inherits="LetterWriterASP.Login" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Expires" content="-1" /><title>
Anchor General Insurance Agency, Inc.
</title><meta http-equiv="Expires" content="-1" /><link rel="shortcut icon" href="Images/favicon.ico" /><link href="App_Themes/Default/Calendar.css" type="text/css" rel="stylesheet" /><link href="App_Themes/Default/Default.css" type="text/css" rel="stylesheet" />

<form id="Form1" runat="server">

                                               Log In

                                               <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User
                                               Name:</asp:Label>

                                               <asp:TextBox ID="UserName" Width="150" name="UserName" runat="server" Font-Size="0.8em"></asp:TextBox>
                                               <asp:RequiredFieldValidator ID="UserNameRequired" runat="server"
                                                   ControlToValidate="UserName" ErrorMessage="User Name is required."
                                                   ToolTip="User Name is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>

                                               <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>

                                               <asp:TextBox ID="Password" Width="150" runat="server" Font-Size="0.8em" TextMode="Password"></asp:TextBox>
                                               <asp:RequiredFieldValidator ID="PasswordRequired" runat="server"
                                                   ControlToValidate="Password" ErrorMessage="Password is required."
                                                   ToolTip="Password is required." ValidationGroup="Login1">*</asp:RequiredFieldValidator>

                                               <asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>

                                               <asp:Button ID="LoginButton" runat="server" BackColor="#FFFBFF"
                                                   BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" CommandName="Login"
                                                   Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775"
                                                   onclick="LoginButton_Click1" Text="Log In" ValidationGroup="Login1" />

                Copyright © 2006 Anchor General Insurance Agency, Inc. All rights reserved.
For questions, please call: (800) 542-6246

<asp:ToolkitScriptManager ID="ToolkitScriptManager2" runat="server" EnablePageMethods="true">
                        </asp:ToolkitScriptManager>
<asp:button id="Button3" name="Button3" runat="server" text="Button" style="display: none;" />

<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server"
targetcontrolid="Button3" popupcontrolid="PopupPanel"
popupdraghandlecontrolid="PopupHeader2" drag="true"
backgroundcssclass="ModalPopupBG">
</asp:ModalPopupExtender>

<asp:Panel ID="PopupPanel" style="display: none" runat="server">

	     Please Wait...

</asp:Panel>

</form>

A: Come to find out (after a VERY long process of trial and error), there's a little something everybody should know about.
You cannot copy
<ToolkitScriptManager>

code from one aspx page to another. You MUST drag it from the toolbox onto your page. I guess it does some stuff we don't see or know about. Same probably goes for ModalPopupExtender.
Hope that helps somebody out there!


text:
Q: Linq - Is there a IEnumerable.ForEach extension method that I'm missing?
Possible Duplicates:
Lambda Expression using Foreach Clause…
Why is there not a ForEach extension method on the IEnumerable interface?

This seems pretty basic. I'm trying to iterate over each object of an IEnumerable. It appears that I would have to cast it to a list first. Is that right? It seems to me there should be an extension method on IEnumerable that does this. I keep having to right my own and I'm getting tired of it. Am I missing it somewhere?
myEnumerable.ToList().ForEach(...)

I want to do this:
myEnumerable.ForEach(...)

A: Nope, there isn't a built-in ForEach extension method. It's easy enough to roll your own though:
public static class EnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (action == null) throw new ArgumentNullException("action");

        foreach (T item in source)
        {
            action(item);
        }
    }
}

But why bother? As Eric Lippert explains in this blog post, the standard foreach statement is more readable -- and philosophically more appropriate -- than a side-effecting ForEach method:
myEnumerable.ForEach(x => Console.WriteLine(x));
// vs
foreach (var x in myEnumerable) Console.WriteLine(x);

A: No there isn't. Eric Lippert talks about why this feature was omitted in his blog:

A number of people have asked me why there is no Microsoft-provided "ForEach" sequence operator extension method.

As a summary the two main reasons are:

*

*Using ForEach violates the functional programming principles that all the other sequence operators are based upon - no side-effects.

*A ForEach method would add no new representational power to the language. You can easily achieve the same effect more clearly using a foreach statement.

A: No, there is no such extension method.  List<T> exposes a real method called ForEach (which has been there since .NET 2.0).

A: There's some talk about it here.  It's not build in to the frame work, but you can roll your own extension method and use it that way.  This is probably your best bet from what I can tell.
I've been in the same situation.
public static class Extensions {
  public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
    foreach (var item in source) {
      action(item);
    }
  }
}

A: IEnumerable do not have this extension method.
Read Eric Lippert's blog here for the reasoning behind it.
So if you need it, you will hav eto write it yourself :)


text:
Q: compare each row in two text file I hope i can have some help with this problem:
I have two text file made up of about 10.000 rows (let's say File1 and File2) comng from a FEM analysis. The structure of the files is:
File1
        ....
     Element           Facet            Node  CNORMF.Magnitude     CNORMF.CNF1     CNORMF.CNF2     CNORMF.CNF3          CPRESS         CSHEAR1         CSHEAR2  CSHEARF.Magnitude    CSHEARF.CSF1    CSHEARF.CSF2    CSHEARF.CSF3

         881               3            6619              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
         881               3            6648              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
         881               3            6653              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
         930               3            6452              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
         930               3            6483              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
         930               3            6488              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        1244               2            7722              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        1244               2            7724              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        1244               2            7754              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        2380               2            3757     304.326E-06    -123.097E-06    -203.689E-06    -189.663E-06     564.697E-06    -281.448E-06     22.5357E-06     152.710E-06     144.843E-06    -26.7177E-06    -40.3387E-06
        2380               2            3826     226.603E-06    -85.9859E-06    -161.270E-06    -133.967E-06     270.594E-06    -134.865E-06     10.7988E-06     117.700E-06     116.217E-06    -4.67318E-06    -18.0298E-06
        2380               2            3848     10.4740E-03    -2.01174E-03    -6.63900E-03    -7.84743E-03     771.739E-06    -384.638E-06     30.7983E-06     5.24148E-03     5.12795E-03    -541.446E-06    -940.251E-06
        2894               2            8253              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        2894               2            8255              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        2894               2            8270              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3372               2            5920              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3372               2            5961     52.7705E-03     12.2948E-03    -40.8019E-03    -31.1251E-03     7.36309E-03    -2.56505E-03    -502.055E-06     18.8167E-03     17.9038E-03     2.12060E-03     5.38774E-03
        3372               2            5996              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3936               3            6782              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3936               3            6852              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3936               3            6857              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3937               4            6410              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3937               4            6452              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3937               4            6488              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3955               2            6940              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3955               2            6941              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        3955               2            6993              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        4024               2            8027              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        4024               2            8050              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.              0.
        ....

File2
        ....
        Node  COORD.Magnitude     COORD.COOR1     COORD.COOR2     COORD.COOR3     U.Magnitude            U.U1            U.U2            U.U3
           1         131.691         14.5010        -92.2190        -92.8868         1.93638     188.252E-03        -1.64949    -996.662E-03
           2         131.336         10.9038        -92.2281        -92.8663         1.93341     188.250E-03        -1.64672    -995.468E-03
           3         132.130         18.7534        -92.4681        -92.5002         1.93968     188.190E-03        -1.65258    -997.959E-03
           4         130.769         1.97638        -92.5186        -92.3953         1.92580     188.179E-03        -1.63965    -992.387E-03
           5         130.560        -4.04517        -93.1433        -91.3993         1.92030     188.026E-03        -1.63459    -990.122E-03
           6         132.422         24.0768        -93.9662        -90.1454         1.94282     187.819E-03        -1.65564    -999.062E-03
           7         130.377        -8.39503        -94.1640        -89.7827         1.91586     187.774E-03        -1.63054    -988.235E-03
           8         126.321         13.6556        -88.0641        -89.5278         1.93579     192.554E-03        -1.64736    -998.202E-03
           9         125.963         4.31065        -88.6558        -89.3771         1.92786     192.145E-03        -1.64012    -994.852E-03
          10         130.037         3.02359        -94.4877        -89.2894         1.92501     187.692E-03        -1.63909    -991.871E-03
          11         126.692         18.5888        -88.1164        -89.1107         1.93970     192.653E-03        -1.65097    -999.810E-03
          12         125.751        -1.96189        -89.1238        -88.6928         1.92231     192.010E-03        -1.63500    -992.572E-03
          13         125.719        -3.46723        -89.2798        -88.4437         1.92094     191.971E-03        -1.63373    -992.005E-03
          14         130.026         7.42596        -95.0372        -88.4289         1.92818     187.556E-03        -1.64210    -993.086E-03
          15         130.736         16.3557        -95.3755        -87.9092         1.93527     187.472E-03        -1.64873    -995.891E-03
          16         130.251        -12.8122        -95.5572        -87.5783         1.91105     187.430E-03        -1.62618    -986.163E-03
          17         130.250         12.8770        -95.6602        -87.4548         1.93216     187.401E-03        -1.64586    -994.616E-03
          18         125.609        -7.73838        -90.1949        -87.0785         1.91668     191.718E-03        -1.62985    -990.191E-03
          19         124.466        -6.21492        -88.8834        -86.9075         1.91827     192.783E-03        -1.63095    -991.270E-03
          20         126.958         23.9470        -89.5421        -86.7584         1.94289     192.337E-03        -1.65406        -1.00096
          21         121.210         6.64491        -84.7929        -86.3587         1.92993     196.112E-03        -1.64059    -997.316E-03
          22         121.369         12.5781        -84.3620        -86.3434         1.93495     196.450E-03        -1.64514    -999.468E-03
        ....

I want to do the following step:

*

*remove the first two column from the File1

*compare the node label for the two files

*write an output text file in "rpt" format containing the rows having the same "node label" side by side

Here is the code I have used. It looks like it works for small file. But for large file, it takes a huge amound of time.
nodEl = open("P:/File1.rpt", "r")
uniNod = open("P:/File2.rpt", "r")

row_nodEl  = nodEl.readlines()
row_uniNod = uniNod.readlines()

nodEl.close()
uniNod.close()

output = open("P:/output.rpt", "w")

for index, line in enumerate(row_nodEl):
    if index > 23081 and index < 40572 and index !=23083 and index !=23084:
        temp  = line.strip()
        temp2 = " ".join(temp.split())
        var   = temp2.split(" ",3)
        for index2, line2 in enumerate(row_uniNod):
            if index2 > 11412 and index2 < 21258 and index2 != 11414 and index2 !=11415:
                temp3 = line.strip()
                temp4 = " ".join(temp3.split())
                var2  = temp4.split(" ",1)
                if var[2] == var2[0]:
                    output.write("%s" %var[2]) + " " + "%s" %var[3] + " " + "%s" %var2[1])

Any suggestion is more then welcome!

A: You are comparing each line of one file (with m lines) to each line of another file (with n lines). This leads to a time complexity O(m*n). What this means is that two files, each having 10,000 lines, will produce 100,000,000 comparisons.
You could speed up your code if you change how you read values. Consider reading a file into a dictionary instead into a list. Each key in the dictionary would be a node number and each value would be the complete line.
Using this approach, you could do the following:

*

*Load the first file into a dictionary

*Load the second file into a dictionary

*For each node from the first dictionary, find the corresponding node in the second dictionary

Using Python, it would look similar to this
file_contents_1 = load_file("P:/File1.rpt")
file_contents_2 = load_file("P:/File2.rpt")

for node_label in file_contents_1:
    # Skip processing node which doesn't have corresponding values in the second file
    if not node_label in file_contents_2:
        continue
    # Do something

The benefit of this approach is that you load the files separately, meaning that time complexity now becomes linear O(m+n). When looking for a corresponding node in the second file, you have a constant time complexity because of the way dictionaries are implemented (i.e. hash tables).
This should make your code a lot faster.


text:
Q: Yii2 get column from junction table and use in gridview Part of my schema is a pictured:
The junction table maps which items are in which category, with the "featured" column marking the item as featured in that category.
What I need to do is get a list of all items in a specific category, including the "featured" attribute from the junction table and pass that data for display into a gridview.
I have created a model for the category_item table and tried to implement the solution proposed here but how do I access and pass the data into the gridview?
Category Model
public function getCategoryItems()
{
    return $this->hasMany(CategoryItem::className(), ['category_id' => 'id']);
}

public function getItems()
{
    return $this->hasMany(Item::className(), ['id' => 'item_id'])->viaTable('{{%category_item}}', ['category_id' => 'id']);
}

CategorySearch Model
public function search($params)
{
    $query = Category::find()->with('items')->with('categoryItems');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

    if (!$this->validate()) {
        return $dataProvider;
    }

    $query->andFilterWhere([
        'id' => $this->id,
        'type' => $this->type,
    ]);

    $query->andFilterWhere(['like', 'title', $this->title])
        ->andFilterWhere(['like', 'description', $this->description]);

    return $dataProvider;
}

Item Model
public function getItemCategories()
{
    return $this->hasMany(CategoryItem::className(), ['item_id' => 'id']);
}

public function getCategories()
{
    return $this->hasMany(Category::className(), ['id' => 'category_id'])->viaTable('{{%category_item}}', ['item_id' => 'id']);
}

Controller
public function actionCategory($id = null)
{
    if($id == null) {
        $dataProvider = new ActiveDataProvider([
            'query' => Category::find()->all(),
        ]);

        return $this->render('category', [
                'dataProvider' => $dataProvider,
        ]);
    } else {

        $category = Category::findOne($id);

        if($category) {
            $searchModel = new CategorySearch();

            $itemsDataProvider = new ActiveDataProvider([
                'query' =>  $searchModel->search(['CategorySearch'=>['id'=>$id]]),
            ]);

            return $this->render('editCategory', [
                'itemsDataProvider' => $itemsDataProvider
                'model' => $category,
            ]);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}

View

Items

        <?= GridView::widget([
            'dataProvider' => $itemsDataProvider,
            'columns' => [

                'id',
                'name',
                'categoryItems.id',
                [
                    'attribute' => 'items.description',
                    'format' => 'html',
                    'value' => 'description',
                ],
                [
                    'label'=>'Highlights',
                    'format'=>'raw',
                    'value'=>function($data) use ($model) {
                        if(TagFeaturedItem::find()->where(['item_id'=>$data->id, 'tag_id'=>$model->id])->all()) {
                            return Html::a('Remove as Highlighted', ['/highlights/category/'.$model->id.'/remove/'.$data->id], ['class'=>'btn btn-xs btn-danger']);
                        } else {
                            return Html::a('Add as Highlighted',['/highlights/category/'.$model->id.'/add/'.$data->id], ['class'=>'btn btn-xs btn-primary']);
                        }
                    },
                ],
            ],
        ]); ?>

In general the view file is a mix and match from trying to find a solution.
The TagFeaturedItem model is from a previous version of the view, see here

A: In my opinion there may be some design flaws in your project that I will not explore; I will zero in on the question of how to get the related data into the gridview.
You can create a custom column in the gridview and then get the related data, you would add something like this to your gridview column array:
    [
            'label'=>'featured',
            'format'=>'raw',
            'value'=>function($data)
            {
                $categories = $data->categories;

                $content = "";
                foreach($categories as $category)
                    $content .= $category->title."
";

                return $content;
            }
    ],

Note that $data represents the model returned by the data provider, in the above example from your Item Model.


text:
Q: Trigger play/pause event One can configure the play/pause key on his/her keyboard to start/pause music of any music player that supports this function.
I'm writing a program that should trigger these events. Currently the program calls:
rhythmbox-client --play

To start playing music. The problem with this approach is that the user for instance can use Nuvola player.
How can I trigger a play/pause event?

A: Just tried this... Run:
xdotool key XF86AudioPlay

This just simulates the pressing of the keyboard's Play button - (In my case Fn+F9)
You may need to install Xdotool first - this might work... For the program you are making, it could be installed as dependencies.
For more commands see here


text:
Q: Having trouble with with if statements being accessed in python 3 I'm writing a test program that's a math game. I'm working on displaying if the user answers a question correctly that it displays 'correct' (in the shell for now), but it never displays correctly even if all the 10 questions are answered correctly. I have tried multiple things such as changing variables back and forth, which has not achieved anything, and added many print statements to see if the if statement was being accessed, which showed only one thing that was not being accessed.

    def addition_frame_fun (self): #Creates the frame where students will be answering addition questions with the labels and entry box.

        self.add_ans_entry=Entry (self.add_frame)
        self.add_ans_entry.grid (row=3,column=5,padx=5)

        next_btn=Button (self.add_frame,text="Next Question",command=self.generate_add_question)
        next_btn.grid (row=12,column=5,sticky=SE)

    def generate_add_question (self):

        self.count+=1

        if self.count <11:

            self.num1=random.randint (1,10)
            self.num2=random.randint (1,10)

            self.num1_str =str (self.num1)
            self.num2_str=str (self.num2)

            self.total= str(self.num1+self.num2)

    def check_ans (self):

        if self.count > 0:

            self.user_add_ans = str (self.add_ans_entry.get () )

        if self.user_add_ans == self.total:

            print (self.total)
            print (self.user_add_ans)

            print("correct")
            self.score+=1

A: Instead of converting self.total into a string ,it would be better to convert self.user_add_ans into float then do the comparison .


text:
Q: Difference between byte stream and bit stream So far I thought they are the same as bytes are made of bits and that both side needs to know byte size and endiannes of the other side and transform stream accordingly. However Wikipedia says that byte stream != bit stream (https://en.wikipedia.org/wiki/Byte_stream ) and that bit streams  are specifically used in video coding (https://en.wikipedia.org/wiki/Bitstream_format). In this RFC https://www.rfc-editor.org/rfc/rfc107 they discuss these 2 things and describe Two separate kinds of inefficiency arose from bit streams.. My questions are:

*

*what's the real difference between byte stream and bit stream?

*how bit stream works if it's different from byte stream? How does a receiving side know how many bits to process at a given time?

*why is bit stream better than byte stream in some cases?

A: A bit is a single 1 or 0 in computer code, also known as a binary digit.
The most common use for the bit stream is with the transmission control protocol, or TCP. This series of guidelines tells computers how to send and receive messages between each other. The World Wide Web and e-mail services, among others, rely on TCP guidelines to send information in an orderly fashion. Sending through the bit stream ensures the pieces arrive in the proper order and the message isn't corrupted during delivery, which could make it unreadable.So a bit stream sends one bit after another.

Eight bits make up a byte, and the byte stream transmits these eight-bit packets from computer to computer.

The packets are decoded upon arrival so the computer can interpret them.Thus a byte stream is a special case of bits sent together as a group in sequential order.For a byte stream to be most effective, it flows through a dedicated and reliable path sometimes referred to as a pipe, or pipeline.
When it comes to sending a byte stream over a computer network, a reliable bi-directional transport layer protocol, such as the transmission control protocol (TCP) used on the Internet, is required. These are referred to as a byte stream protocol. Other serial data protocols used with certain types of hardware components, such as the universal asynchronous receiver/transmitter (UART) technique, is a serial data channel that also uses a byte stream for communication. In this case, the byte, or character, is packaged up in a frame on the transmitting end, where an extra starting bit and some optional checking bits are attached and then separated back out of the frame on the receiving end. This technique is sometimes referred to as a byte-oriented protocol.

Taking a general life example,suppose you have a lot of match sticks to send.Then you could send them one stick after the other,one at a
  time.. or you could pack a few of them in a match box and send them
  together ,one matchbox after the other in sequence.the first is like
  bitstream and the latter like bytestream.

Thus it all depends on what the hardware wants or is best suited for..If your hand is small and you cant accept matchboxes but you still want matchsticks then you take them one at a time or else take the box.Also byte streams are better in a sense that every bit does not need to be checked and data can be sent in batches of 8,.if any of it fails the entire 8bits can be re sent.

A: This is a pretty broad question, I'll have to give the 10,000 feet view.  Bit streams are common in two distinct usages:

*

*very low-level, it is the fundamental way that lots of hardware operates.  Best examples are the data stream that comes off a hard disk or a optical disk or the data sent across a transmission line, like a USB cable or the coax cable or telephone line through which you received this post.  The RFC you found applies here.

*high-level, they are common in data compression, a variable number of bits per token allows packing data tighter.  Huffman coding is the most basic way to compress.  The video encoding subjects you found applies here.

what's the real difference between byte stream and bit stream?

Byte streams are highly compatible with computers which are byte-oriented devices and the ones you'll almost always encounter in programming.  Bit streams are much more low-level, only system integration engineers ever worry about them.  While the payload of a bit stream is often the bytes that a computer is interested in, more overhead is typically required to ensure that the receiver can properly interpret the data.  There are usually a lot more bits than necessary to encode the bytes in the data.  Extra bits are needed to ensure that the receiver is properly synchronized and can detect and perhaps correct bit errors.  NRZ encoding is very common.
The RFC is quite archeological, in 1971 they were still hammering out the basics of getting computers to talk to each other.  Back then they were still close to the transmission line behavior, a bit stream, and many computers did not yet agree on 8 bits in a byte.  They are fretting over the cost of converting bits to local bytes on very anemic hardware and the need to pack as many bits into a message as possible.

How does a receiving side know how many bits to process at a given time?

The protocol determines that, like that RFC does.  In the case of a variable length bit encoding it is bit values themselves that determine it, like Huffman coding does.

why is bit stream better than byte stream in some cases?

Covered already I think, because it is better match for its purpose.  Either because the hardware is bit-oriented or because variable bit-length coding is useful.

A: To add to the other good answers here:
A byte stream is a type of bit stream. A byte stream describes the bits as meaningful "packages" that are 8 bits wide.
Certain (especially low-level) streams may be agnostic of meaning in each 8 bit sequence. It would be a poor description to call these "byte streams"
Similar to how every Honda Civic is a car, but not every car is a Honda Civic...


text:
Q: Sorting keys in property list in iOS I have created a property list with the keys 1 to 11, all with the value 0.
The list is to be used as datasource for a picker view.
I have these property:
@property (nonatomic, strong) NSDictionary *erfaring;
@property (nonatomic, strong) NSArray *erfaringKeys;

And this in the implementation file:
NSString *erfaringFile = [[NSBundle mainBundle]
                         pathForResource:@"Erfaring" ofType:@"plist"];
erfaring = [[NSDictionary alloc] initWithContentsOfFile:erfaringFile];
erfaringKeys = [erfaring allKeys];

The problem is, that when the keys are loaded in to the picker view they are sorted wrong like: 7, 3, 8, 4, 11, 9, 5, 1, 6, 2, 10.
Any help?

A: You will need to sort the keys of the dictionary
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                     @"String 1", @"1",
                     @"String 4", @"4",
                     @"String 3", @"3",
                     @"String 2", @"2", nil];

NSArray *sortedKeys = [dic keysSortedByValueUsingSelector:@selector(compare:)];

Then iterate using sorted keys
for (NSString *sortedKey in sortedKeys) {
    NSString *value = [dic objectForKey:sortedKey];
}

A: You can sort your array before loading in picker-
erfaringKeys = [erfaring allKeys];
erfaringKeys = [erfaringKeys sortedArrayUsingSelector:@selector(compare:)];


text:
Q: Draw letters based on points on mouse click in action script 3 I asked to draw line between objects in stage (e.g points) on mouse click over 2 of these objects
example : if I want to write 'A' i need to set 5 point and connect them by clicking all these points like:
   *
  * *
 *   *

A: This question isn't very specific. Which part are you having problems with? The Graphics object provides methods for drawing lines. It's very easy to draw between points with drawTo(...)
For a quick intro see: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7dd9.html

A: First, you have to detect the user's mouse click and convert that into some sort of form of data that you can use to draw a line with.
Use the MouseEvent class and EventListeners to detect a user's mouse click. If you don't know how to use event listeners, refer to here.
The dispatched MouseEvent object has a stageX and stageY property which refers to the X and Y coordinates of where the mouse click occurred. These two pieces of data can be used to create a Point object. Instantiate and store this point object somewhere convenient - so that when you have more than 2 of them, you can then refer to AndySavage's answer on how to draw a line with those two Point objects.
Basically, you want to create a Point object every time a mouse click occurs, and then check internally the amount of Point objects you have. If you have one, don't do anything, because you need two points to draw a line. If you have more than one, then use the two latest Point objects you obtained to draw a line.
Tip:
If you store the points into a vector, then every time a mouse click occurs, you can push a Point object inside. Then, check the length of that vector, and if it is greater than 1, you can access the last two elements by using the it's length - 1 and length - 2 as indices.

You can read the documentation on the Vector and Point classes by searching on google. (Type something like "as3 api Vector") I'd add links but I can only add less than two per post right now.


text:
Q: How to insert a teaser breaker in the hexo post? Any idea how to add a teaser breaker or line breaker in the post in hexo?
So the list view which is by default the homepage will show for each post just what's before the teaser breaker? Seems by default, it shows everything in the homepage.

A: it depends on the theme you use.
if the theme does support it, in your post you can do:

title: post title
---
This part is the excerpt, get it with the <%- post.excerpt %>
<!-- more -->
This is the rest of the post. You can get it with <%- post.more %>

https://github.com/hexojs/hexo/issues/1143#issuecomment-102247129


text:
Q: Tratamento de erro na API Google maps Android Estou fazendo um cadastro de pessoas com endereço para mostrar no mapa onde determinada pessoa mora. Quando digito o endereço correto tudo funciona normalmente, mas quando erro o endereço, que não é válido para o Google Maps, o app fecha.
@Override
public void onResume() {
    super.onResume();

    FragmentActivity context = getActivity();
    LatLng local = new Localizador(context).getCoordenada("R. Eurita, 47 - Santa Teresa - Belo Horizonte - MG");
    centralizaNo(local);

    AlunoDAO dao = new AlunoDAO(context);
    List<Aluno> alunos = dao.getLista();

    for (Aluno aluno : alunos) {

        GoogleMap map = getMap();

        LatLng localAluno = new Localizador(context).getCoordenada(aluno.getEndereco());

        MarkerOptions options = new MarkerOptions().title(aluno.getNome()).position(localAluno);
        map.addMarker(options );

    }

    dao.close();
}

public void centralizaNo(LatLng local) {
    GoogleMap map = getMap();
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local , 15);
    map.animateCamera(update );
}

Queria uma ajuda para tratar o erro e se a pessoa digitar um endereço inválido não aparecer no mapa para fluir normalmente.
public class Localizador {
    private Context context;

    public Localizador(Context context){
        this.context = context;
    }

    public LatLng getCoordenada(String endereco) {
        Geocoder geocoder = new Geocoder(context);

        try {
            List<Address> enderecos = geocoder.getFromLocationName(endereco, 1);
            if (!enderecos.isEmpty()){

                Address enderecoLocalizado = enderecos.get(0);
                double latitude = enderecoLocalizado.getLatitude();
                double longitude = enderecoLocalizado.getLongitude();

                return new LatLng(latitude, longitude);
            } else {
                return null;
            }
        } catch (IOException e) {
            return null;
        }
    }
}

A: Como o seu método getCoordenada já retorna um valor nulo caso não encontre o endereço informado, basta você fazer uma verificação antes de utilizar uma coordenada para definir um local, independente de onde seja.
Assim mais ou menos:
Localizador localizador = new Localizador(context);
LatLng localAluno = localizador.getCoordenada(aluno.getEndereco());

if (localAluno != null) {
    MarkerOptions options = new MarkerOptions().title(aluno.getNome()).position(localAluno);
    map.addMarker(options);
}

Assim você previne qualquer exceção que de fato realmente ocorre caso a posição definida com position() seja nula.


text:
Q: AzureML schema "list index out of range" error I developed a machine learning model using Azure ML's clustering. Few of the requests made from the cluster are triggering 404 HTTP error. I followed the document to do modifications in my swagger.json file. Finally ended up with "list index out of range" error. It seems to be having issue with the global parameter but I am no sure about it. I am using the API from postman with some default headers like mentioned in the body below
{
    "Inputs": {
         "input_1" : "content"
         "input_2: : "content"
         ......
    },
    "GlobalParameters": 0
}

A: Change the "GlobalParameter" value to any floating number other than 1.0 or even you can remove it and execute. Sometimes, Global parameter will cause the issue. Check the below documentation.
https://learn.microsoft.com/en-us/answers/questions/746784/azure-ml-studio-error-while-testing-real-time-endp.html


text:
Q: How to select multiple checkboxes with 'value' attribute in a webpage getting data from an excel file using selenium webdriver I am new to selenium. And I wanted to select checkboxes in my webpage using selenium webdriver, by getting the data from a local excel sheet. I achieved this for all the radio buttons, but these checkboxes I wanted to select has no 'id' attribute. They are distinguished only by 'value'.
The HTML code is:
    <input type="hidden" value="1" name="%%Surrogate_Competitors"/>

    <input type="checkbox" title="Competitors" value="HP (Servers)" name="Competitors"/>
    HP (Servers)

    <input type="checkbox" title="Competitors" value="Sun (Servers)" name="Competitors"/>
    Sun (Servers)

    <input type="checkbox" title="Competitors" value="HP (Storage)" name="Competitors"/>
    HP (Storage)

    ............
    ............

I tried using this code to select those checkboxes:
String Competitors=sh.getCell(column,1).getContents();
String delims = "[,]";
String[] Competitor = Competitors.split(delims);

for(int i=0;i<Competitor.length;i++) {
    //to select competitors
    driver.findElement(By.cssSelector("input[value="+Competitor[i]+"]")).click();
}

when I run this code, an error message is getting generated as below:

The given selector input[value=HP (Storage)] is either invalid or does
  not result in a WebElement.

Please let me know how to overcome this, and get the check boxes selected.

A: please check the css identifier, you may need to add quote for the value:
 driver.findElement(By.cssSelector("input[value='" + Competitor[i] + "']"))

This stack post must be helpful


text:
Q: Issue in MongoDB document search I am new to MongoDB. And I have the following issue on currently developing web application.
We have an application where we use mongoDB to store data.
And we have an API where we search for the document via text search.
As an example: if the user type "New York" then the request should send the all the available data in the collection to the keyword "New York". (Here we call the API for each letter typed.) We have nearly 200000 data in the DB. Once the user searches for a document then it returns nearly 4000 data for some keywords. We tried with limiting the data to 5 – so it returns the top 5 data, and not the other available data. And we tried without limiting data now it returns hundreds and thousands of data as I mentioned. And it causes the request to slow down.
At Frontend we Bind search results to a dropdown. (NextJs)
My question:

*

*Is there an optimizing way to search a document?

*Are there any suggestions of a suitable way that I can implement this requirement using mongoDB and net5.0?

*Or any other Implementation methods regarding this requirement?
Following code segment shows the query to retrieve the data to the incomming keyword.
        var hotels = await _hotelsCollection
            .Find(Builders<HotelDocument>.Filter.Text(keyword))
            .Project<HotelDocument>(hotelFields)
            .ToListAsync();

        var terminals = await _terminalsCollection
            .Find(Builders<TerminalDocument>.Filter.Text(keyword))
            .Project<TerminalDocument>(terminalFeilds)
            .ToListAsync();

        var destinations = await _destinationsCollection
            .Find(Builders<DestinationDocument>.Filter.Text(keyword))
            .Project<DestinationDocument>(destinationFields)
            .ToListAsync();

A: So this is a classic "autocomplete" feature, there are some known best practices you should follow:

*

*On the client side you should use a debounce feature, this is a most. there is no reason to execute a request for each letter. This is most critical for an autocomplete feature.

On the backend things can get a bit more complicated, naturally you want to be using a db that is suited for this task, specifically MongoDB have a service called Atlas search that is a lucene based text search engine.
This will get you autocomplete support out of the box, however if you don't want to make big changes to your infra here are some suggestions:

*

*Make sure the field your searching on is indexed.

*I see your executing 3 separate requests, consider using something like Task.WhenAll to execute all of them at once instead of 1 by 1, I am not sure how the client side is built but if all 3 entities are shown in the same list then ideally you merge the labels into 1 collection so you could paginate the search properly.

*As mentioned in #2 you must add server side pagination, no search engine can exist without one. I can't give specifics on how you should implement it as you have 3 separate entities and this could potentially make pagination implementation harder, i'd consider wether or not you need all 3 of these in the same API route.


text:
Q: To fix scatter sizes in Excel (scatter plot made from Table) Small dataset in Excel as a Table. A slicer is added. And, I made a scatter plot from it.
The scatter size is set to larger than default but when I choose from slicer, the size of scatters jumped back to default size (smaller).
For example, Kate's in the screenshot.
What's the way to fix the scatter sizes?

Excel file: Scatter plot.xlsx

A: Select Kate > Select the graph > Format > Current Selection : Vertical/Horintal Axis > Try Fix the value here (no Auto)
Does it work on ur excel version?


text:
Q: Dropdown in emails I want to know if we can allow a drop down within a HTML mailer for iOS/Android devices. I want to show a dropdown based selection with which I can show data in the emailer. The data would be static and the user would have the liberty to choose to hide or show the data after choosing from the dropdown.
Is it possible?

A: You would need javascript for that, but that is not available in the iOS Mail app (possibly not on Android either, but I wouldn't know) for security reasons.
And it will absolutely not work in any webmail client. That would be a huge security issue, since it would be really simple to write a worm.
Your best option is probably to have a link to a regular website, or just dump all the data on the email.


text:
Q: RenderDelegate not being called I have set up a RenderDelegate to draw the cell text in a different color. I have also set the OwnerDraw property to true.
This is the render code:
this.olvInvoiceType.RendererDelegate = delegate (EventArgs re, Graphics g, Rectangle r, object rowObject)
{
    var item= rowObject as MyItem;
    var brush = Brushes.Red;

    g.DrawString(item.Name, olvItems.Font, brush, r);
    return false;
};

However, nothing is being displayed.
What am I missing?

A: Despite what the example on the ObjectListView website says it seems that you actually have to return true, and not false.
Other examples I found also return true.
Also, don't forget to check that your object is null before rendering, else it will throw an exception!
this.olvInvoiceType.RendererDelegate =  delegate (EventArgs re, Graphics g, Rectangle r, object rowObject)
            {
                var item = rowObject as MyItem;
                if (item != null)
                {
                    //g.FillRectangle(new SolidBrush(this.olvItems.BackColor), r);
                    g.DrawString(item.Name, olvItems.Font, brush, r);
                }
               return true;
            };

When I tried this I seemed to have the strange issue that the text was rendered twice, once originally by the control in black and then another time by me in red!
This might be a bug, or I might have missed something.
To get around this then I had to paint the background will fillrectangele, but then you have the issue if the row in selected so you would need to handle this separately.
I also found that OwnerDraw made no difference!

A: I know it's an old question, but I had the same problem and couldn't find any correct answers. I'll leave my answer, maybe it helps somebody.
nameColumn.RendererDelegate is not called no matter what I do or which OwnerRender mode I'm in.
nameColumn.Renderer = SomeCustomIRenderer is also not called completely no matter what I do.
I managed to fix the issue by adding:
treeListView.CellRendererGetter = (object rowObject, OLVColumn column) => new MyCustomIRenderer(); And only after that, my custom renderer was actually called.
Easiest way is to override your own BaseRenderer or just copy one from here http://objectlistview.sourceforge.net/cs/ownerDraw.html#owner-draw-label


text:
Q: Unable to edit files and folders over Samba I am running Samba v4.2.10-Debian on my Raspberry Pi 2B (running Raspbian Jessie) and have set up a fstab file to mount my external drive on /dev/sda1 to /media/ECHO:
/dev/sda1 /media/ECHO auto noatime 0 0.
My Samba configurations are default except SECURITY = USER and my share definition.
[ECHO]
comment = ECHO NAS
path = /media/ECHO/
valid users = @users
force group = users
create mask = 0660
directory mask = 0771
read only = no
writeable = yes
I can read/write /media/ECHO from my account through SSH, however, when I connect through Samba, I am not allowed to modify anything. However this works if I set uid=justin in the fstab (which is not ideal because it wouldn't work for other users).
/media/ECHO is exFAT (exfat-fuse is installed) and mounted as drwxr-xr-x owned by root (group and user).
Any help would be appreciated, thanks!

A: in your mount command, provide the Group with Write permission, and change the owner-group to Users, or alternately, allow the Other group write permissions.
Normally you would use the commands below:
sudo chown -R root:users /media/ECHO; sudo chmod -R 775 /media/ECHO
or
sudo chmod o+w /media/ECHO
but since you are using ex-fat, you will have to edit it in FSTAB instead.
samba permissions stack atop filesystem permissions, so even if you tell samba to allow write, it won't unless the filesystem also provides that user the same write permissions. Based on your permissions (755), only the owner (root) could write.
Adding an umask to the fstab does this if you're using exfat-fuse.


text:
Q: Needing an object reference for my Method? I have to make a program which generates lotto ticket then checks to see if there is a winner. I am having problems even calling my method which is only a simple menu function.
This is the error:

Error    1   An object reference is required for the non-static field,
  method, or property

I am not sure where i have went wrong but i think its to do with visibility.
I have tried changing some functions to public static but that has not worked.
class Program
{

    bool quitFlag = false;
    SortedSet<int> winningNumbers = new SortedSet<int>();
    List<CTicket> ticketList = new List<CTicket>();

    static void Main(string[] args)
    {

        DoMenu();
    }

    public static void GenerateTickets(List<CTicket> l)
    {

        Random Rand = new Random();

        for(int i=0; i <1000; i++)
        {
            SortedSet<int> num = new SortedSet<int>();

            do
            {

                num.Add(Convert.ToInt32(Rand.Next(1,42)));
            }
            while(num.Count <=6);

            CTicket ticket = new CTicket(i,num);
            l.Add(ticket);
            ticket.printTicket();
        }
    }

    public static void DrawWinningNumbers(SortedSet<int> winningNumbers)
    {

        for(int i=1; i <6; i++)
        {

            Random Rand = new Random();
            winningNumbers.Add(Convert.ToInt32(Rand.Next(1,42)));

            while(winningNumbers.Count <=6);
            Console.Write("The winning numbers are: {");

            foreach (int x in winningNumbers)
            {
                Console.Write(x + ", ");
            }

            Console.WriteLine();
        }
    }

    void DoQuit()
    {

        quitFlag = true;
    }

    int ShowMenu()
    {

        int option;

        Console.WriteLine("\t-------------------------------------------------\n");
        Console.WriteLine( "\t\t\t Queue Application\n\n");
        Console.WriteLine("\t1. \tGenerate tickets\n");
        Console.WriteLine("\t2. \tDisplay all tickets\n");
        Console.WriteLine("\t3. \tGenerate Winning Numbers\n");
        Console.WriteLine("\t4. \tPrint queue\n");
        Console.WriteLine("\t5. \tReverse queue\n");
        Console.WriteLine("\t6. \tExit\n");

        option = Convert.ToInt32(Console.ReadLine());

        Console.WriteLine();
        Console.WriteLine();
        return option;
    }

    public static void DoMenu()
    {

        do
        {
            int option;

            option = ShowMenu();

            switch (option)
            {
                case 1:
                    GenerateTickets(ticketList);
                    //system("cls");
                    break;
                case 2:
                    //system("cls");
                    break;
                case 3:
                    DrawWinningNumbers(winningNumbers);
                    //system("cls");
                    break;
                case 4:
                    break;
                case 5:
                    //system("cls");
                    break;
                case 6:
                    DoQuit();
                    break;
                default:
                    //system("cls");
                    Console.WriteLine("invalid option!\n");
                    break;
            }
        } while (quitFlag != true);
    }
}

A: The error should be clear - you are accessing non-static items (quitFlag, winningNumbers, ticketList) from a static method.
Either change the items above to static (if they should be shared by ALL instances of the Program class), or make the methos non-static and call it on an instance of Program.


text:
Q: Mysql database connection file errors I am on an Amazon ec2 instance and I have a database that I am trying to access via a PHP script.  I am echoing out tests through the script so i seem to get to the end but I am not getting any errors.  Whenever I change my localhost to my IP it says: Connection error: Can't connect to MySQL server on 'MY IP' (110).  I have tried binding my localhost and server server IP to my.cnf file and still the same result.  Are there any other configurations I am missing?  I have never had this much trouble before but this is my first time working on an amazon ec2 Linux instance.
<?php
$con=mysqli_connect("localhost","root","password","database");

if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
echo "testing1";

$query = "SELECT id, email FROM user_key ORDER BY email DESC LIMIT 10;";

echo "here";

$result = mysql_query($query);

echo "here2";

while($row = mysql_fetch_assoc($result))
{
 echo $row['id']." ";
 echo $row['email']." ";
}

echo "last";
?>


text:
Q: What's the best pattern to synchronise a Room table with a RecyclerView? I have:

*

*a table for my entity, obj.

*a (model) class, Obj.

*a Room Entity, ObjEntity.

*a Room DAO, ObjDao.

*and finally a RecyclerView for my model, Obj.

Within my Obj class, I've added an insert method - Obj#Post, which handles storing this Obj to the app's database (handles converting to ObjEntity, foreign keys for child entities / lists, etc.)
The first thought is to requery the obj table for all objs, before taking this ObjEntity[], mapping it to a Obj[] before updating the (cached) in memory version of all objs - and notifying the recycler view adapter of an update.

This obviously doesn't seem like the best approach, as it would only update on an insert, and not a delete etc. This also doesn't follow the pattern of separation of concerns.

What I ideally want is for the RecyclerView to dynamically query the database itself, and update accordingly. However, the implementation of the adapter works based off of an ordered list structure. Now, the objs won't always have nicely contiguous ids - so unless I did some funky hack to map from the value returned by RecyclerView.Adapter#getItemCount to each ID , this doesn't seem like it would work. Also, most importantly, there's no notifying of changes to the adapter with this solution. It'd just be querying whenever it usually does - I don't know the implementation, I'm guessing some form of polling, or user interaction trigger.

Does Room have some form of callback API, i.e. ObjDao#onTableUpdated?

A: What you need is exactly designed in Android architecture component.
The LiveData notifies the view whenever there is a change in the Room Database.
The ViewModel handle the data operation independent to UI, that is complete CURD operation.
The Repository modules handle data operations. They provide a clean API so that the rest of the app can retrieve this data easily. They know where to get the data from and what API calls to make when data is updated. You can consider repositories to be mediators between different data sources, such as persistent models, web services, and caches.

App using these components
If you want to use it for pagination purpose in the recyclerview use PagedListAdapter instead of RecyclerView.Adapter


text:
Q: How can I hide xamarin label to property or something

I want to show this step1 text in android form.
So I declare
public bool VisibleCheck { get; set; } = true;

but I can't understand how to use it

A: You must bind the property from your view model to the IsVisible property in the label.


text:
Q: TypeScript Inheritance and Injected Constructor Arguments Using Angular 5 and TypeScript, in the following inheritance scenario, is it possible to not have to include MyService as an argument to the constructor of MyComponent?
export class CBasic {
    // properties and methods
}

export class CAdvanced extends CBasic {

    // constructor
    constructor(
        public myService: MyService
    ) {
        // call constructor of super-class (required)
        super();
    }

    // more properties and methods
}

export class MyComponent extends CAdvanced {

    // constructor
    constructor() {
        // call constructor of super-class (required)
        super(); // Error: [ts] Expected 1 arguments, but got 0.
    }
}

The error I am getting is [ts] Expected 1 arguments, but got 0. in MyComponent.
The point is I want to include MyService in CAdvanced to avoid code-duplication in classes that inherit from it, e.g. MyComponent.

A: You can make the injectable service a property.
export class CAdvanced {
    @Inject(MyService)
    public myService: MyService;

    constructor() {
    }
}

export class MyComponent extends CAdvanced {
    constructor() {
         super(); // no more error
    }
}

Angular will inject the service to the base class via the @Inject decorator.
Alternatively, you can make the parameter optional.
This will silence the error, but the value will be undefined.
export class CAdvanced {
    constructor(public myService?: MyService) {
        console.log(this.myService);
        // above will print undefined
    }
}

export class MyComponent extends CAdvanced {
    constructor() {
         super(); // no more error
    }
}


text:
Q: youtube video not working using intent, yet it does using browser I am using the following code to start an intent to run a youtube video:
Intent intent = new Intent(
               Intent.ACTION_VIEW,
               Uri.parse("vnd.youtube:" + YOUTUBE_VID_ID)
                          );
startActivity(intent);

My only problem is that some videos give me the error (on some devices) "Not available in your country" although if I use the browser, the videos are displayed normally.
All the videos are not listed but I am still able to view some of them. I can not find the link. I might have access to the youtube channel if I know where to fix this.

A: Don't force your users to use the youtube application. Doing so limits them and the fundamental design around sharing and cross app communication of android. In the end they will not like the usability of your app.
Instead launch an intent to let them choose what video application to use:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(MY_YOUTUBE_URL)));

That way if they have an app that will do things like stream it to their TV then they can use that instead of the youtube player.

edit by Sherif
Just use:
Intent intent = new Intent(Intent.ACTION_VIEW,
               Uri.parse("http://www.youtube.com/watch?v=" + YOUTUBE_VID_ID));
startActivity(intent);


text:
Q: Sublime Snippet, if no regex match use "null" string I'm trying to write a snippet. For this post I super simplified it. If I run it on this selection:
arg1

the snippet should output:
doFunc('arg1', 'null');
if I run it on this selection:
arg1, arg2

the snippet should output
doFunc('arg1', arg2);
I can't figure out how to use null string if no regex match is found. This is what I have so far:
 doFunc('${SELECTION/([^,]+)(,.*)?/\1/}', ${SELECTION/([^,]+)(,.*)?/\2/});

So the problem here is ${SELECTION/([^,]+)(,.*)?/\2/} I want to do like a tertiary so like \2 ? \2 : null is this possible?
Thanks

A: Sublime Text Snippets use the Boost library, which actually supports ternary operators in the format part. Hence you can just write (?{2}(\2):'null') like a ternary operator.
If you change your snippet to this it will have the specified behavior:
doFunc(${SELECTION/^([^,]+)(?:,\s*(.*))?/'\1', (?{2}(\2):'null')/});


text:
Q: Collection_select helper cannot build disabled html tag in ruby on rails erb Ruby on rails docs says you can add html options to tag helpers. The code below is not working. My select box cannot shown disabled. Is there anybody knows why?
<%= form.fields_for :journal_doc_analytics do |analytics| %>

      <%= analytics.label :select_personel %>
      <%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, disabled: true %>

I also tried to write like
<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, options = {disabled: true} %>

Or
<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, html_options={disabled: true} %>

https://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_select
Generated HTML code doesn't include disabled option. See below.
[1]: https://i.stack.imgur.com/HuIWE.jpg
Any ideas will accepted.

A: TLDR:
invoke the function like that (note the additional {})
<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, {}, disabled: true %>

Explanation:
So this one was a bit tricky.
From the docs you can see that the function accepts following params:
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

You are invoking the function like that:
<%= analytics.collection_select :personel_id, Personel.all, :id, :name_with_initial, html_options={disabled: true} %>

so if you look closely at the params, the html_options should be the last param that is passed and before it there is options param. So all the time you were passing disabled: true as options instead of html_options


text:
Q: Pythons 'with'-statement: correctly nest/derive classes with __enter__/__exit__ How should I correctly nest the with-related behavior of classes (e.g. when deriving or instantiating)?
This works for me but I wonder if there's a dedicated way to do it:
class class_a:
    def __init__(self):
        print('class_a::__init__')

    def __enter__(self):
        print('class_a::__enter__')
        return self

    def __exit__(self, type, exit, tb):
        print('class_a::__exit__')

class class_b(class_a):
    def __init__(self):
        class_a.__init__(self)
        print('class_b::__init__')

    def __enter__(self):
        class_a.__enter__(self)
        print('class_b::__enter__')
        return self

    def __exit__(self, type, exit, tb):
        class_a.__exit__(self, type, exit, tb)
        print('class_b::__exit__', type, exit, tb)

with class_b():
    print('ready')
    try:
        signal.pause()
    except:
        pass

One way to do this differently would be to implement class_b like this:
class class_b:
    def __init__(self):
        self._class_a_inst = class_a()
        print('class_b::__init__')

    def __enter__(self):
        self._class_a_inst.__enter__()
        print('class_b::__enter__')
        return self

    def __exit__(self, type, exit, tb):
        self._class_a_inst.__exit__(type, exit, tb)
        print('class_b::__exit__', type, exit, tb)

Is there any difference regarding the __enter__() / __exit__() behavior?

A: Ideally, use contextlib.contextmanager. For the case of deriving:
import contextlib

class context_mixin:
    def __enter__(self):
         self.__context = self.context()
         return self.__context.__enter__()
    def __exit__(self, *args):
         return self.__context.__exit__(*args)

class class_a(context_mixin):
    @contextlib.contextmanager
    def context(self):
         print('class_a enter')
         try:
             yield self
         finally:
             print('class_a exit')

class class_b(class_a):
    @contextlib.contextmanager
    def context(self):
        with super().context():
            print('class_b enter')
            try:
                yield self
            finally:
                print('class_b exit')

In Python 2, super() needs to be super(class_b, self).
There is a change in behaviour compared with your code: this code exits b before exiting a, meaning that the scopes nest. You've written your code to do them in the other order, although that's easy enough to change. Often it makes no difference, but when it does matter you usually want things to nest. So for an (admittedly-contrived) example, if class_a represents an open file, and class_b represents some file format, then the exit path for class_a will close the file, while the exit path for class_b will write any buffered changes that have yet to be committed. Clearly b should happen first!
For the case of holding another object:
class class_b(context_mixin):
    def __init__(self):
        self.a = class_a()
    @contextlib.contextmanager
    def context(self):
        with self.a:
            print('class_b enter')
            try:
                yield self
            finally:
                print('class_b exit')


text:
Q: Select Data Frame based on the timerange in R I have tried to filter data frame based on the time range, I can't able to achieve it. It keeps on result null data frame.

What i have tried so far,
 previous_day <- Sys.Date()-1
    last_week <- Sys.Date() -7

    count_visit_data$visited_time <- as.Date(count_visit_data$visited_time, format = "%d.%m.%Y")

    count_visit_data <- data.table(count_visit_data)
count_visit_data <- count_visit_data[which(count_visit_data$visited_time >= previous_day && count_visit_data$visited_time<= last_week),]

Tried other approaches as well:
count_visit_data[visited_time %between% c(previous_day, last_week)]

Also some other approaches, but didn't get desired. I can't able to figure when am i making wrong.
Can anybody help me with this?
Thanks


text:
Q: How to implement morris.js to laravel dompdf bladepageI have installed laravel 5.8 and installed barryvdh/laravel-dompdf package. I have used some jquery chart plugin to show chart on blade file, it's works fine. By using dompdf package , I am trying to shown this piechart on pdf, but chart's are not showing on pdf. How to show charts on pdf, Is there any solution to show charts on streaming/download pdf.?
I want to attach the above blade file to my PDF
My second Question:
I have installed laravel-snappy
and i got below error while generating pdf.....
The exit status code '1' says something went wrong:
stderr: "Loading pages (1/6)
[>                                                           ] 0%\r[======>                                                     ] 10%\r[=======>                 ▶
Counting pages (2/6)
[============================================================] Object 1 of 1Resolving links (4/6)
[============================================================] Object 1 of 1Loading headers and footers (5/6)
Printing pages (6/6)
[>                                                           ] Preparing\r[============================================================] Page 1 of 1\rDone       ▶
Exit with code 1 due to network error: ProtocolFailure
"
stdout: ""
command: C:\xampp\htdocs\geetha\vendor\wkhtmltopdf\bin\wkhtmltopdf --lowquality --enable-javascript --javascript-delay "5000" --enable-smart-shrinking --no-stop ▶
"""
Is there any solution to show charts on streaming/download pdf.?


text:
Q: Find_path in Cmake doesn't work I have a custom package named bitstream and want to use it in upstream project.
--upstreamProject
|
|--src
    |-- ...(many .cpp)
    |--CmakeLists.txt
|--include
    |-- ... (..many .hpp)
|--bitstream
    |--CMakeLists.txt
    |--bitstreamConfig.cmake
    |--src
        |-- bitstream.cpp
    |--include
        |-- bitstream.hpp

So I write bitstreamConfig.cmake:
find_path(BITSTREAM_INCLUDE_DIR NAMES bitstream.hpp)
MESSAGE(STATUS "bitstream_include_dir: ${BITSTREAM_INCLUDE_DIR}")
find_library(BITSTREAM_LIBRARY NAMES bitstream)
MESSAGE(STATUS "BITSTREAM_LIBRARY: ${BITSTREAM_LIBRARY}")

include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(BITSTREAM REQUIRED_VARS BITSTREAM_LIBRARY BITSTREAM_INCLUDE_DIR)

if(BITSTREAM_FOUND)
    set(BITSTREAM_LIBRARIES ${BITSTREAM_LIBRARY})
    set(BITSTREAM_INCLUDE_DIRS ${BITSTREAM_INCLUDE_DIR})
endif()

mark_as_advanced(BITSTREAM_INCLUDE_DIR BITSTREAM_LIBRARY)

and in upstream project I add:
SET(bitstream_DIR "${CMAKE_SOURCE_DIR}/bitstream")
FIND_PACKAGE(bitstream)
INCLUDE_DIRECTORIES(${BITSTREAM_INCLUDE_DIRS})

in upstream project src I add:
TARGET_LINK_LIBRARIES(${...} ${BITSTREAM_LIBRARIES})

but when run cmake I got that:
-- bitstream_include_dir: BITSTREAM_INCLUDE_DIR-NOTFOUND
-- BITSTREAM_LIBRARY: BITSTREAM_LIBRARY-NOTFOUND
-- Could NOT find BITSTREAM (missing:  BITSTREAM_LIBRARY BITSTREAM_INCLUDE_DIR)

Please tell me why cmake cannot find the correct path, thanks in advance!

A: You haven't give any hint to find_path about possible location of the searched file. By default, it searches only in system-wide dirs, and definitely does not look into bitstream/.
find_path documentation page describes search algorithm, where all possible hints are explicitely listed.
Also, you are confused between module and config mode of find_package.
Your bitstreamConfig.cmake  actually implements module mode: it uses find_* commands for locate items and calls find_package_handle_standard_args at the end for final verdict (whether package is found or not).
But naming *Config.cmake implies config mode, which (normally) fills all variables with hardcoded values and automatically succeed.


text:
Q: MDX - Top X Sales People by Total Sales for Each Date I'm trying to do this, but with MDX in my cube:
select
    *
from
(
    select
        Date, SalesPerson, TotalSales, row_number() over(partition by Date order by TotalSales desc) as Num
    from SalesFact as ms
) as x
where
    Num < 5
order by
    Date, SalesPerson, Num desc

Let's say I have a cube with these dimensions:
Date (Year, Month, Date) - date is always 1st of month
SalesPerson
The fact table has three columns - Date, SalesPerson, TotalSales - ie, the amount that person sold in that month.
I want, for each month, to see the top 5 sales people, and each of their TotalSales. The top 5 sales people can be different from one month to the next.
I am able to get the results for one month, using a query that looks like this:
select
      [Measures].[TotalSales] on columns,
      (
            subset
            (
                  order
                  (
                        [SalesPerson].children,
                        [Measures].[TotalSales],
                        bdesc
                  ),
                  0,
                  5
            )
      ) on rows
from
      Hypercube
where
      (
            [Date].[Date].&[2009-03-01T00:00:00]
      )

What I'm after is a query that puts Date and SalesPerson on rows, and TotalSales on columns.
I want to see over time each month, and for each month, the top 5 sales people, and how much they sold.
When I try to do it this way, it doesn't seem to filter / group the sales people by each date (get top 5 for each date). The values returned are all over the place and include very low and null values. Notably, the SalesPerson list is the same for each date, even though TotalSales varies a lot.
select
    [Measures].[TotalSales] on columns,
    (
        [Date].[Hierarchy].[Date].members,
        subset
        (
            order
            (
                [SalesPerson].children,
                [Measures].[TotalSales],
                bdesc
            ),
            0,
            5
        )
    ) on rows
from
    Hypercube

It seems that everything inside "subset" needs to be filtered by the current [Date].[Hierarchy].[Date], but using CurrentMember gives a crossjoin / axis error:
select
    [Measures].[TotalSales] on columns,
    (
        [Date].[Hierarchy].[Date].members,
        subset
        (
            order
            (
                ([SalesPerson].children, [Date].[Hierarchy].CurrentMember),
                [Measures].[TotalSales],
                bdesc
            ),
            0,
            5
        )
    ) on rows
from
    Hypercube

Error:     Executing the query ... Query (3, 2) The Hierarchy hierarchy
  is used more than once in the Crossjoin function.
Execution complete

I've tried several variations of the last query with no luck.
Hopefully the answers will be helpful to others new to MDX as well.

A: I eventually found out how to do what I was looking for. The solution revolved around using the Generate function, and starting with the basic example on MSDN and modifying the dimensions and measure to be the ones in my cube got me going in the right direction.
From http://msdn.microsoft.com/en-us/library/ms145526.aspx
Is there a better way?
Also, be wary of trying to refactor sets into the with block. This seems to change when the set is evaluated / change its scope and will change the results.
with

set
Dates as
{
    [Date].[Hierarchy].[Date].&[2009-02-01T00:00:00],
    [Date].[Hierarchy].[Date].&[2009-03-01T00:00:00],
    [Date].[Hierarchy].[Date].&[2009-04-01T00:00:00]
}

select
    Measures.[TotalSales]
    on columns,
    generate
    (
        Dates,
        topcount
        (
            [Date].Hierarchy.CurrentMember
            *
            [SalesPerson].Children,
            5,
            Measures.[TotalSales]
        )
    )
    on rows
from
    Hypercube


text:
Q: How do I split two columns in two separate tables into joined multiple rows in a view? I have two separate tables, each containing character-separated cells. One table contains all the key data, the other all the val data. In the application, both tables are loaded into recordsets, the two cells are split into two arrays and the arrays are then used 'side-by side' to create key/val pair.
Trying to decouple the database from the application, I will basically create a view that emulates this behavior.
I created some sample tables and data to better illustrate it.
/* Create tables */
CREATE TABLE [dbo].[tblKeys](
    [KeyId] [int] NOT NULL, /*PK*/
    [KeyData] [nvarchar](max) NULL
)
CREATE TABLE [dbo].[tblValues](
    [ValId] [int] NOT NULL, /*PK*/
    [KeyId] [int] NOT NULL, /*FK*/
    [Language] [nvarchar](5) NOT NULL,
    [ValData] [nvarchar](max) NULL
)

/* Populate tables */
INSERT INTO [dbo].[tblKeys] ([KeyId], [KeyData]) VALUES
    (1, '1|2|3'),
    (2, '1|2|3|4'),
    (3, '2|1')
INSERT INTO [dbo].[tblValues] ([ValId], [KeyId], [Language], [ValData]) VALUES
    (1, 1, 'en',    'Apple|Orange|Pear'),
    (2, 1, 'sv-se', 'Äpple|Apelsin|Päron'),
    (3, 2, 'en',    'Milk|Butter|Cheese|Cream'),
    (4, 2, 'sv-se', 'Mjölk|Smör|Ost|Grädde'),
    (5, 3, 'en',    'Male|Female'),
    (6, 3, 'sv-se', 'Man|Kvinna')

The desired end result in the view looks like this:
| KeyId | KeyData | Language | ValData
+-------+---------+----------+----------+
|     1 |       1 |       en | Apple    |
|     1 |       2 |       en | Orange   |
|     1 |       3 |       en | Pear     |
|     1 |       1 |    sv-se | Äpple    |
|     1 |       2 |    sv-se | Apelsin  |
|     1 |       3 |    sv-se | Päron    |
...

etc.
I've seen similar questions here on StackOverflow, but they all deal with a single table being tilted in similar ways. I need to tilt both tables while using the positions of the data in the two columns KeyData and ValData as siginficants when recombining them into proper key/val pairs.
How would I do this in an efficient manner?
[Edit]: The database design is not mine. It's some old crap I inhereted. I know it's bad. Bad as in horrendous.

A: This would work for you. But: you really should change your data design!
;WITH Splitted AS
(
    SELECT v.Language
          ,v.ValData
          ,v.ValId
          ,k.KeyData
          ,k.KeyId
          ,CAST('<x>' + REPLACE(v.ValData,'|','</x><x>') + '</x>' AS XML) AS ValData_XML
          ,CAST('<x>' + REPLACE(k.KeyData,'|','</x><x>') + '</x>' AS XML) AS KeyData_XML
    FROM tblValues AS v
    INNER JOIN tblKeys AS k ON v.KeyId=k.KeyId
)
,NumberedValData AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY KeyId,Language ORDER BY (SELECT NULL)) AS RowNumber
      ,KeyId
      ,Language
      ,A.B.value('.','varchar(max)') AS ValD
    FROM Splitted
    CROSS APPLY Splitted.ValData_XML.nodes('/x') AS A(B)
)
,NumberedKeyData AS
(
    SELECT ROW_NUMBER() OVER(PARTITION BY KeyId,Language ORDER BY (SELECT NULL)) AS RowNumber
      ,KeyId
      ,Language
      ,A.B.value('.','varchar(max)') AS KeyD
    FROM Splitted
    CROSS APPLY Splitted.KeyData_XML.nodes('/x') AS A(B)
)
,Combined AS
(
    SELECT nk.KeyId
          ,nk.KeyD
          ,nk.Language
          ,nv.ValD
    FROM NumberedKeyData AS nk
    INNER JOIN NumberedValData AS nv ON nk.KeyId=nv.KeyId AND nk.Language=nv.Language AND nk.RowNumber=nv.RowNumber
)
SELECT Combined.KeyId
      ,Combined.KeyD AS KeyData
      ,Splitted.Language
      ,Combined.ValD AS ValData
FROM Splitted
INNER JOIN Combined ON Splitted.KeyId=Combined.KeyId AND Splitted.Language=Combined.Language
ORDER BY Splitted.KeyId,Splitted.

The result
KeyId   KeyData Language    ValData
   1    1       en          Apple
   1    2       en          Orange
   1    3       en          Pear
   1    1       sv-se       Äpple
   1    2       sv-se       Apelsin
   1    3       sv-se       Päron
   2    1       en          Milk
   2    2       en          Butter
 [...]


text:
Q: Protecting and Hiding Columns same as "Very Hidden" Sheets I am trying to hide some columns and prevent the user to have any access to them; while they can edit other parts of the sheet.
What I am seeking is something like:
ActiveWorkbook.Sheets("Name").Visible = xlSheetVeryHidden

So user cannot see them. I am aware that one option is adding another sheet and move those columns to there and hide that one sheet; but as I am working on a relatively large data-set and it has a standard format within the company, I prefer not to do so.
I already tried locking the columns and protecting the sheets and checking all the boxes except the ones for selecting locked cells, inserting and deleting both rows and columns (code below).
Function VeryHideColumn(myColumn As Range)

    myColumn.Locked = True
    myColumn.FormulaHidden = True
    myColumn.Hidden = True
    'myColumn.Hidden = xlVeryHidden 'I already tried this

    ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
        False, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
        AllowFormattingRows:=True, AllowInsertingHyperlinks:=True, AllowSorting:= _
        True, AllowFiltering:=True, AllowUsingPivotTables:=True
    ActiveSheet.EnableSelection = xlUnlockedCells

End Function

This is the problem: users still can select a range containing these hidden and locked columns and unhide them. Is there any method or trick like VeryHidden for sheets available for ranges?

A: Original Answer:
If the users don't need to format the columns and rows, then there's a work around for this:
If AllowFormattingColumns and AllowFormattingRows were false (which is default if not stated), then user would not be able to hide or unhide them.
Update:
Function below "very hides" only the columns based on above idea;
Function VeryHideColumn(myColumn As Range)
'By M--, April 2017

    myColumn.Locked = True
    myColumn.Hidden = xlVeryHidden
    myColumn.FormulaHidden = True

    ActiveSheet.Protect DrawingObjects:=False, Contents:=True, Scenarios:= _
        False, AllowFormattingCells:=True, AllowFormattingRows:=True, _
        AllowInsertingHyperlinks:=True, AllowSorting:=True, AllowFiltering:=True _
    , AllowUsingPivotTables:=True

End Function

If you want to very hide the rows, then set the AllowFormattingRows to false.


text:
Q: How to print a html table in a separate window I want to print a HTML table using some PHP data, in a separate window when I press a button. What is the best way to do it?

        MODEL
        <?php echo $modelNo ?>
        MODEL
        <?php echo $modelNo ?>

        QTY
        <?php echo $box ?>
        QTY
        <?php echo $box ?>

A: Have the button open the new window, and set its location to the PHP file that prints the table.
Something as simple as this could work:
Click

(You can optionally style this link to look like a button)

A: You will need to have this table returnable from a PHP script, or available somewhere (I assume you already do).
Here is a purely html method:
Open Table!

Here is a javascript method:

<form>
<input type="button" onClick="myPopup()" value="Open table!">
</form>

CLICK ME TOO!

A: You can also have the html in a hidden input and use a form submit to the other page and retrieve it from there with $_POST like assuming $table_data is your html:
<form action="new_window.php">
<input type="hidden" value="$table_data" name="data">
<input type="submit" value="Open Table">
</form>

Then in new_window.php:
if(isset($_POST['data'])){
echo $_POST['data'];
}

A: You can also create the entire solution in javascript by creating a new window and by writing the content in the window.
see the basic approach writing in a new window here:
http://www.w3schools.com/jsref/met_win_open.asp
and
Print the contents of a DIV
You would have to add an id attribute to your table
Then playing with DOM functions such as :
https://developer.mozilla.org/en-US/docs/DOM/document.getElementById
and
https://developer.mozilla.org/en/docs/DOM/element.innerHTML
You will have to wrap your table into a html. The main advantage of this method is that it can be called later on any table without the need to add a line of php.


text:
Q: My table in postgresql is truncating these strings I have a table in VMobjects like this
MGRCONFIG_DB=# select * from vmobjects;
               guid                |   ipaddress   | username | password |  hostid  |     vmname      | guestostype | guestos
name
-----------------------------------+---------------+----------+----------+----------+-----------------+-------------+--------
-----
 7728235734dcd25700e7c02.96324791  | gsdag         | gsdasd   |          | Physical | rag             | windows     |
 3642656604dcd343d3bcd11.54875889  | fsd           |          |          | Physical | derde           | windows     |
 17714467484dcd35dd0fa677.27764184 | dsf           |          |          | Physical | fdsfd           | windows     |
 1837080764dcd362fafe404.83675706  | fgf           |          |          | Physical | fgf             | windows     |
 2791118544dcd363df11bf1.21924610  | fdghhg        |          |          | Physical | $%^             | windows     |
 7716352574dcd365c9eb777.30236042  | dsffd         |          |          | Physical | ^               | windows     |
 10753160514dcd366631f5b6.48505657 | gfdgd         |          |          | Physical | @               | windows     |
 8253046164dcd366f177bc3.85542378  | ghgfdhg       |          |          | Physical | @@@@@@@@@@@@@@  | windows     |
 9126180214dcd367a5b42e0.23605256  | fsdfdsfdsf    |          |          | Physical | fdsaj;(         | windows     |
 11086632854dcd36f62f7e79.14470771 | dfsdfsd       |          |          | Physical | ^               | windows     |

Now I have a php page addvm.php, when I add username/ip/password/ or anything it gets truncated
gets truncated on entering data as '~!@#$%^&*()_+=-`{}|\][:"';<>?/.,' for all fields.

After using pg_escape_string
i am able to insert '~!@#$%^()_=-`{}|][:"';<>?/. all strings except + and &.
@Emil Vikström: say that i have to use urlencode for this. but i don't no, How & whr it is used?

A: Use pg_escape_string on the data before entering it into your SQL query:
$data = '~!@#$%^&*()_+=-';
$data_escaped = pg_escape_string($data);
$query = 'INSERT INTO table (data) VALUES("'. $data_escaped .'");';


text:
Q: If PHP shell_exec() works too long or executed program hangs... how to catch error? If I execute with shell_exec() an external program (unix) and it works for more than 30 seconds, PHP dies with Fatal error. That's because external program hanged/crashed or I don't know.
I want to catch this error. try{}..catch{} does not work in here. How can I tell if an external program has hanged? Usually my external program runs under 2 seconds.

A: You can use this function system_with_timeout defined in the "run-tests.php" script, included in the source distribution:
(the key is the last parameter passed to stream_select)
function system_with_timeout($commandline, $env = null, $stdin = null)
{
    global $leak_check, $cwd;

    $data = b'';

    $bin_env = array();
    foreach((array)$env as $key => $value) {
        $bin_env[(binary)$key] = (binary)$value;
    }

    $proc = proc_open($commandline, array(
        0 => array('pipe', 'r'),
        1 => array('pipe', 'w'),
        2 => array('pipe', 'w')
        ), $pipes, $cwd, $bin_env, array('suppress_errors' => true, 'binary_pipes' => true));

    if (!$proc) {
        return false;
    }

    if (!is_null($stdin)) {
        fwrite($pipes[0], (binary) $stdin);
    }
    fclose($pipes[0]);

    $timeout = $leak_check ? 300 : (isset($env['TEST_TIMEOUT']) ? $env['TEST_TIMEOUT'] : 60);

    while (true) {
        /* hide errors from interrupted syscalls */
        $r = $pipes;
        $w = null;
        $e = null;

        $n = @stream_select($r, $w, $e, $timeout);

        if ($n === false) {
            break;
        } else if ($n === 0) {
            /* timed out */
            $data .= b"\n ** ERROR: process timed out **\n";
            proc_terminate($proc);
            return $data;
        } else if ($n > 0) {
            $line = (binary) fread($pipes[1], 8192);
            if (strlen($line) == 0) {
                /* EOF */
                break;
            }
            $data .= $line;
        }
    }

    $stat = proc_get_status($proc);

    if ($stat['signaled']) {
        $data .= b"\nTermsig=" . $stat['stopsig'];
    }

    $code = proc_close($proc);
    return $data;
}

The timeout is given by passing an array like this: array('TEST_TIMEOUT' => 200) as the second parameter.


text:
Q: Nginx rate limiting at server level excluding a particular IP My server is constantly being flooded and I am looking to limit the connections. I want to do this at the server level (because I have multiple websites) but every now and then I run a cache warm script from a particular IP.
limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m;
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_req zone=one;
limit_conn addr 10;

How I can do rate limiting but exclude this particular IP (or set of IPs)


text:
Q: Packaging a python project which requires non-python packages I'm following the python documentation about "distributing packages using setuptools". It doesn't mention what to do if a python package you want to include in your install_requires requires a system installation. For example:
I'd like to include the package pysoundfile, but this requires me to install libsndfile1 via my system package manager, e.g. sudo apt-get install libsndfile1.
I've got as far as understanding I need to make a binary distribution, given advice in the docs here, but that sends me to the docs listed above.
How do I automate this process such that users of my package can simply pip install my_package and not have to apt-get install libsndfile1?

A: TL/DR; Use Python's distutils module in setup.py in order to bundle libsndfile together with your application in a single binary Wheel.
Python packages can come as source distributions or as binary distributions (Python Wheels, .whl). When a package requiring a native library (e.g. libsndfile) is installed from source, the installing system needs to have the native library installed and a corresponding toolchain (e.g. gcc) to link the Python package with the native library.
To avoid the need for a compile toolchain and for apt-get install …, you can use Python's distutils module. Especially distutils.build_clib is what you are looking for. This allows you to build libsndfile as a static library inside setup.py and bundle it into a Python Wheel together with your application. You might want to have look at other projects that use this method, such as argon2_cffi.
Note that bundling native dependencies together with your Python application has drawbacks as well:

*

*Since the native libraries are statically linked, users of your application will not get any security updates when they update their OS version of libsndfile. You have to take care of that.

*Python Wheels are specific to a platform (i.e. combination of CPU architecture and OS). If you intend to support many different platforms, you need to build many different wheels. Take a look at the many wheels produced by the Pillow project