text:
Q: Can't push to remote repository in github I'm new to github so for the sake of testing I've been modifying my .gitconfig file (adding some useful aliases, etc.) and pushing it to my "Config Files" repository on github.
I have 2 computers, a desktop and a laptop. When I modify the local file in the desktop, commit and push to the remote repository it works fine.
However, when I try to do the same from the laptop I get this error.
     ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/User/Config-Files.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Aditionally I get this error if I try to pull first like the message suggests:
$ git pull origin master
remote: Enumerating objects: 6, done.
remote: Counting objects: 100% (6/6), done.
remote: Compressing objects: 100% (1/1), done.
remote: Total 4 (delta 2), reused 4 (delta 2), pack-reused 0
Unpacking objects: 100% (4/4), 355 bytes | 8.00 KiB/s, done.
From https://github.com/User/Config-Files
 * branch            master     -> FETCH_HEAD
   627ab06..b327e2b  master     -> origin/master
fatal: refusing to merge unrelated histories

The remote repository only has the .gitconfig file, the same file I'm trying to push from the laptop so why am I getting this error?

A: The answer is in your terminal, it is telling you to fetch first.
You pushed to master already from your desktop, and your commit on your laptop is behind. So you have to fetch, merge, and then you'll be able to push from your laptop..
This is bad practice but can always force it in.. (--force) but then any of the changes made on your desktop would be gone.


text:
Q: Why do I need this. keyword to reference a variable with the same name? Good evening,
This is my first post on stack overflow. I'm a newbie in programming and I can do many things in C++ - a language I love.
However, recently I've moved on to javascript with the mission of getting hired.
I'm creating a snake game and I'm automatizing its moves.
I just do not understand why a variable I created inside a function, just above a few if statements, isn't
used inside the statements. I had to use this. keyword to change its state.
Thank you!
document.getElementById("action").addEventListener("keydown", function (event) {
  let interval = null; // the culprit

  if (event.key === "ArrowDown") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowDown, 1000);
  } else if (event.key === "ArrowRight") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowRight, 1000);
  } else if (event.key === "ArrowUp") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowUp, 1000);
  } else if (event.key === "ArrowLeft") {
    clearInterval(this.interval);
    this.interval = setInterval(ArrowLeft, 1000);
  }
});

A: Because this.interval and let interval are not the same thing at all.
The first is a property of whatever object this is, and the second is a block-scoped local variable with a lifetime of just that function; just like a local function (without static) would have in C++.
Since you're using a regular function() (and not an arrow function), the caller decides what this is bound to at call time (see the aforelinked this page).

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Get a Pointer by using a Thread ID EDIT3:
I need a list from all windows a thread has. Not FindWindowsEnum() because it only returns Top level Windows.... I need the window handle befor it's visible
END EDIT3
EDIT2:
Short desciption: I need a method, where i can get a "window handle" from a thread.
END EDIT2:
EDIT:
First of all i can't use FindWindowsEnum()!!!
Because it only returns the top windows. I have to kill the window befor it is visible. So i have to get The Handle of the window by a Thread ID.
EDIT END:
I got a problem by a window which i have to close which is not focused or something like that. I have to close the window as it pops up. I only use code.
What i got:
This is the extern class where I import one dll and some functions which use the functions from the dll.
    class FindWindowApi
{
    //[DllImport("user32.dll", SetLastError = true)]
    //public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

    public IntPtr[] GetWindowHandlesForThread(int threadHandle)
    {
        _results.Clear();
        EnumWindows(WindowEnum, threadHandle);
        return _results.ToArray();
    }

    public  delegate int EnumWindowsProc(IntPtr hwnd, int lParam);

    [DllImport("user32.Dll")]
    public static extern int EnumWindows(EnumWindowsProc x, int y);

    public List<IntPtr> _results = new List<IntPtr>();

    public int WindowEnum(IntPtr hWnd, int lParam)
    {

        _results.Add(hWnd);
        return 1;
    }

    [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
    public static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int GetWindowText(
        IntPtr handle,
        [MarshalAs(UnmanagedType.LPWStr)] StringBuilder caption,
        int count);

    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int GetWindowTextLength(IntPtr handle);

    public const UInt32 WM_CLOSE = 0x0010;
}

at this class i use the functions from the extern class.
I start a Thread which runs every 10 milli secounds and kill a window in another method.
    public Disk_UC()
    {
        InitializeComponent();
        Thread killit = new Thread(this.killIt);
        killit.Start();
        comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
        comboBox2.DropDownStyle = ComboBoxStyle.DropDownList;
        Thread nt = new Thread(this.fillData);
        nt.Start();

    }

    //Thread Method
    private void killIt()
    {
        bool blac = false;
        Int32 oldThreadID = threadID;
        FindWindowApi api = new FindWindowApi();
        while ((!blac)
            && (!MainDiag.isGoingDown))
        {
            if (oldThreadID != threadID)
            {

                IntPtr[] windows = api.GetWindowHandlesForThread(threadID);
                if (windows != null && windows.Length > 0)
                    foreach (IntPtr hWnd in windows)
                    {
                        killWindow(hWnd, threadID);
                    }

            }
            Thread.Sleep(10);
        }
    }

    //Method which calls all the extern dll stuff
    private bool killWindow(IntPtr handle, int param)
    {
        var length = FindWindowApi.GetWindowTextLength(handle);
        var caption = new StringBuilder(length + 1);
        FindWindowApi.GetWindowText(handle, caption, caption.Capacity);

        IntPtr windowPtr = FindWindowApi.FindWindowByCaption(IntPtr.Zero, caption.ToString());
        if (windowPtr == IntPtr.Zero)
        {
            return false;
        }
        FindWindowApi.SendMessage(windowPtr, FindWindowApi.WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        return true;
    }

My Problem is now how can i get this specific window handle.
when the Thread "fillData" pops up the window. So i save the thread ID from this Thread fillData.
Now i call the other Methods with this thread id. I got the Thread ID and i get so many windows from the Process. But i need this specific window from that thread.


text:
Q: In Azure DevOps which ticket was a branch created for? In Azure DevOps you can select a ticket on the Sprint task board and there is a menu option Create Branch which you can use to create a branch in the repo to work on that ticket.
Having done this, if you go to the Branches view in DevOps, how on earth do you see which ticket each branch was created for?

A: Based on your concern and description, currently, on the Branches view in DevOps, there is no optioned field for which ticket each branch was created for, also, regarding this limit for your "Branches view show which ticket each branch was created for" requirement, you could create a feature request via: https://developercommunity.visualstudio.com/report?space=21&entry=suggestion . That will allow you to directly interact with the appropriate Product Group, and make it more convenient for the product group to collect and categorize your suggestions.
Besides, a workaround for your scenario is that it is suggested that you could name the branch with the related WIT ID to help recognize it, for example, you can name the new created branch like WIT ID "Task6" to help specify the branch when creating it.
Pic1:

Pic2:

You could also check the related branch name in "Details" and "History" section when opening the WIT.
In "Details" section.

In "History" section.

Hope it's helpful to you.


text:
Q: Predicting next 60 days using pytorch (LSTM) I am trying to use pytorch to make predictions on time-series dataset.
1- First, I splitted the dataset into training and test.

2- Then, I created the model.
import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

        self.rnn = nn.LSTM(input_size=1,hidden_size=50,num_layers=3,batch_first=True,dropout=0.2)
        self.out = nn.Linear(50, 1)

    def forward(self, x):

        r_out, (h_n, h_c) = self.rnn(x, None)
        x = r_out[:,-1,:]                    #last hidden output!
        x = self.out(x)
        return x

model = Model()

if cuda:
    model.cuda()

3- After training the model, I made the validation step.
mse = mean_squared_error(dataset['y'].iloc[60:].values,predicted)
print("RMSE:", np.sqrt(mse))

# RMSE: 0.10680269716212222

Question: I would like to know, how can I use this model to predict the next 60 days ?
I read that is necessary to: Take the last prediction value(i.e predicted[-1]) from my predictions and add it to the last array of total_x, excluding the first timestep.
So, I tried this:
#array --> List
today = total_x[-1].reshape(-1).tolist()

# scaling last price
last_price = scaler.transform(infered['y_pred'][-1].reshape(-1, 1))

# adding last price to list.
today.append(last_price[0])

# Exclude first(0th index) element
today = today[1:]

#reshape
today = np.array(today).reshape(-1,60,1)

today = torch.Tensor(list(today))

#predict!
tomorrow = predict_with_pytorch(model, today)

#inverse transform.
tomorrow = scaler.inverse_transform(tomorrow)[0]

This Variable tomorrow is my tomorrow prediction, however, how to do this, for the next 60 days ?


text:
Q: how we can install java and mysql on one click installation? how multiple software install on single click?

A: A whole bunch of scripts, turned into a program.

A: If you're looking for an application that takes care of downloading and installing your basic sofware for a computer check out:
http://ninite.com
The only problem is, it doesn't install MySQL, probably because usually installing MySQL server requires quite a bit of configuration to make sure it fits your needs.
Good luck!

A: I'm going to guess you are looking at a hosting service that has "one-click install" services.  In that case, go to your control panel, find the one-click application menu, and click the applications you want to install.
Please note that this is a terrible system.  These web applications from automatic service installers are rarely updated, and are hard to apply updates yourself after the fact (and you WILL need to update them).  It is much better to go through the trouble of learning the install yourself, so when upgrade time comes you stand at least a chance of getting it done.


text:
Q: Celery tasks through view (Django) returned as pending, but okay via Terminal This issue has been discussed before and looking over numerous posts, I am so far unable to find a solution to this problem. I'm new to celery so my learning curve is still fairly steep. Below my current scripts:
myapp.__init__.py
from __future__ import absolute_import, unicode_literals
from .celery_main import app as celery_app # Ensures app is always imported when Django starts so that shared_task will use this app.

__all__ = ['celery_app']

myapp.celery_main.py
from __future__ import absolute_import
from celery import Celery
from django.apps import apps

# Initialise the app
app = Celery()
app.config_from_object('myapp.celeryconfig')  # WORKS WHEN CALLED THROUGH VIEW/DJANGO: Tell Celery instance to use celeryconfig module
#app.config_from_object('celeryconfig')  # WORKS WHEN CALLED THROUGH TERMINAL

# Load task modules from all registered Django app configs.
app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])

myapp.celeryconfig.py
from __future__ import absolute_import, unicode_literals
from datetime import timedelta

## List of modules to import when celery starts.
CELERY_IMPORTS = ('celery_tasks',)

## Message Broker (RabbitMQ) settings.
BROKER_URL = 'amqp://'
BROKER_PORT = 5672

## Result store settings.
CELERY_RESULT_BACKEND = 'rpc://'

## Misc
#CELERY_IGNORE_RESULT = False
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Berlin'
CELERY_ENABLE_UTC = True

CELERYBEAT_SCHEDULE = {
    'doctor-every-10-seconds': {
        'task': 'celery_tasks.fav_doctor',
        'schedule': timedelta(seconds=3),
    },
}

myapp.celery_tasks.py
from __future__ import absolute_import
from celery.task import task

suf = lambda n: "%d%s" % (n, {1: "st", 2: "nd", 3: "rd"}.get(n if n < 20 else n % 10, "th"))
@task
def fav_doctor():
    # Stuff happend here

@task
def reverse(string):
    return string[::-1]

@task
def send_email(user_id):
    # Stuff happend here

@task
def add(x, y):
    return x+y

anotherapp.settings.py
INSTALLED_APPS = [
    ...
    'kombu.transport.django',
]

myapp.views.admin_scripts.py
from celery.result import AsyncResult
from myapp.celery_tasks import fav_doctor, reverse, send_email, add
from myapp.celery_main import app

@login_required
def admin_script_dashboard(request):
    if request.method == 'POST':
        form = Admin_Script(request.POST)
        if form.is_valid():
                # Results
                async_result = add.delay(2, 5)
                task_id = async_result.task_id
                res = AsyncResult(async_result)
                res_1 = add.AsyncResult(async_result)
                res_2 = add.AsyncResult(async_result.id)
                print ("async_result: {0}\ntask_id: {1}\nres: {2}\nres_1: {3}\nres_2: {4}".format(async_result, task_id, res, res_1, res_2))

                # Backend: Make sure the client is configured with the right backend
                print("Backend check: {0}".format(async_result.backend))

                # States/statuses
                task_state = res.state
                A = async_result.status
                B = res.status
                print ("task_state: {0}\nA: {1}\nB: {2}".format(task_state, A, B))

The results when triggering the celery workers through my django application (related to the print statements in app.views.admin_scripts.py):
async_result: 00d7ec84-ebdb-4968-9ea6-f20ca2a793b7
task_id: 00d7ec84-ebdb-4968-9ea6-f20ca2a793b7
res: 00d7ec84-ebdb-4968-9ea6-f20ca2a793b7
res_1: 00d7ec84-ebdb-4968-9ea6-f20ca2a793b7
res_2: 00d7ec84-ebdb-4968-9ea6-f20ca2a793b7
Backend check: <celery.backends.rpc.RPCBackend object at 0x106e308d0>
task_state: PENDING
A: PENDING
B: PENDING

Output in Terminal triggered:
[2018-07-15 21:41:47,015: ERROR/MainProcess] Received unregistered task of type 'MyApp.celery_tasks.add'.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you are using relative imports?
Please see <link> for more information.

The full contents of the message body was:
{'task': 'MyApp.celery_tasks.add', 'id': 'b21ffa43-d1f1-4767-9ab8-e58afec3ea0f', 'args': [2, 5], 'kwargs': {}, 'retries': 0, 'eta': None, 'expires': None, 'utc': True, 'callbacks': None, 'errbacks': None, 'timelimit': [None, None], 'taskset': None, 'chord': None} (266b)
Traceback (most recent call last):
  File "/Users/My_MBP/anaconda3/lib/python3.6/site-packages/celery/worker/consumer.py", line 465, in on_task_received
    strategies[type_](message, body,
KeyError: 'MyApp.celery_tasks.add'

I have several questions:
1. I can trigger the expected results by using commands in Terminal:
celery -A celery_tasks worker -l info

Then in the Python shell:
from celery_tasks import *
add.delay(2,3)

Which succeeds:
[2018-07-13 10:12:14,943: INFO/MainProcess] Received task: celery_tasks.add[c100ad91-2f94-40b1-bb0e-9bc2990ff3bc]
[2018-07-13 10:12:14,961: INFO/MainProcess] Task celery_tasks.add[c100ad91-2f94-40b1-bb0e-9bc2990ff3bc] succeeded in 0.017578680999577045s: 54

So executing the tasks in Terminal works, but not in my view.py in Django, why not?
2. Perhaps related to 1.: I have to, annoyingly, configure in app.celery_main.py the app.config_from_object depending if I want to test via Django, or via Terminal. You can see either I set the celeryconfig.py with myapp name prefixed, or without. Otherwise, an error message is thrown. I suspect some kind of import looping is causing an issue here (though I could be wrong) but I don't know why/where. How can I overcome this?
3. In my settings.py file (not celeryconfig.py) I have configured in INSTALLED_APPS: 'kombu.transport.django'. Is this necessary? I'm using celery 3.1.26.post2 (Cipater)
4. In all my files I have at the top:
from __future__ import absolute_import, unicode_literals

For what purpose is this for exactly and for 3.1.26 is it required?
5. I read here, that you need to ensure the client is configured with the right backend. But I'm not sure exactly what this means. My print out is (as per app.views.admin_scripts.py):
Backend check: <celery.backends.rpc.RPCBackend object at 0x106e308d0>

If there are any abnormalities in my code you recognise, please feel free to let me know.

A: I'm still trying to figure out the answer to my question 2, meanwhile I've figured out how to retrieve the required results: I have async_result = add.delay(2, 5) but then after this I need to have async_result.get() followed by task_output = async_result.result. The result status/state (async_result.state or async_result.status) is then set to succeed.

A: *

*Celery tasks should have proper names. When running from django, the task name is MyApp.celery_tasks.add which is why celery worker not able to run it. But from terminal when your imported using from celery_tasks import *, task name is celery_tasks.add which is why it is working correctly.

*You can change config based on environment variable.

*kombu.transport.django Adding this not necessary.

*This is related to Python 2/3. See this docs for more info.

*If you want task results after the task is completed, it should be stored somewhere. So backend is needed for this. If you don't want to retrieve results, you don't need this.


text:
Q: Is this graph bipartite? A planar depiction of a loop-free connected graph has 7 regions, each is a
polygon. The numbers of edges on the boundaries of the regions are respectively
3,3,3,3,3,4,5. (a) Find the number of vertices of the graph.
(b) Is G bipartite?
I figured out that part a) is 7 vertices.
So now we have
|V| = 7 |F| = 7 and |E| = 12
so for part b) I began trying to draw sample graphs and my initial intuition is that it isn't but how do I go ahead and properly prove that?

A: Also, the graph on part a) could look like this:


text:
Q: Append element on multiple if conditions I have this table:

    Name
    Paul Johnson
    Birthdate
    28th May 1974

    Street
    Fake Street 148
    City
    New York

There is a script that is executed by mouseenter event
$('th').on("mouseenter mouseleave", function(e) {if (e.type === 'mouseenter') {

});

inside it is code below
var toolbar = $("
").css({
      "padding": "5px",
      "background" : "#F8F8F8"
      "borderRadius" : "5px 0 5px 5px",
      "left" : "-30px",
      "top" : "0",
      "zIndex" : "99"
    });

toolbar.append( gmaps ).append( google ).append( phone ).append( copy );

$(this).append( toolbar );

and link inside toolbar
    var link = $("").css({
      "display" : "block",
      "height" : "20px",
      "width" : "20px",
      "marginBottom" : "5px",
      "background-size" : "100%",
      "position" : "relative"})
      .attr({"target" : "_blank"
});

There are many kinds of links, more than 100 variants. There is for example two of them
var thisNext = $( $(this).parent().next('td') ).text();

    var gmaps = link.clone().css({
      "background" : "url(https://dl.dropboxusercontent.com/s/pwcubxu7xoigavz/maps.png) no-repeat",
      "background-size": "100%",
    }).attr({href: 'https://www.google.com/maps/search/' + thisNext });

    var google = link.clone().css({
      "background" : "url(https://dl.dropboxusercontent.com/s/ja0plpnomx3v0jn/find.png) no-repeat",
      "background-size": "100%",
    }).attr({href: 'https://www.google.cz/search?q=' + thisNext });

I have got more tables on site, but table like this shouldnt append nothing

  User
  John

My questions/goals:

*

*variable thisNext should get data from next td element ( if user
clicks to name, it should get Paul Johnson etc ), but my code do not
works

*not each th should append toolbar, for exemple City should do nothing - vhat is the best solution to define which elements should append toolbar?

*if is user "John" th element street should append gmaps and
google inside toolbar, if is user "Steve" same element should append only google. For another th element should "Steve" get both links, "John" nothing etc.
here is codepen
I cant make it with classes, ids etc. I need to make only with raw table just like I posted.

A: *

*1

variable thisNext should get data from next td element ( if user clicks to name, it should get Paul Johnson etc ), but my code do not works

$(this) refers to  element, so desired  is just its next sibling:
var thisNext = $(this).next().text();

*

*2

not each th should append toolbar, for exemple City should do nothing - vhat is the best solution to define which elements should append toolbar?

You can get 's content to determine its "type" and then decide based on it:
var this_type = $(this).text();
//"User", "Street", "City", etc.

if (this_type === 'City'){
    //append nothing
} else if (this_type === 'Street'){
    toolbar.append( gmaps ).append( google ); //for example
} else {
    // default (for all the rest "types")

    toolbar.append( gmaps ).append( google ).append( phone ).append( copy );
}

*

*3

if is user "John" th element street should append gmaps and google inside toolbar, if is user "Steve" same element should append only google. For another th element should "Steve" get both links, "John" nothing etc.

So we have different set of buttons for different users.
Do you have separate page for each user, or are they all on the same page?
First, let's get the current user (for one user — one page case):
/**
 * Finds username on the page.
 * If a table on the page has only one , it's considered a table with username
 */
function determineCurrentUser (){
    $('table').each(function(){
        var $td_elements = $(this).find('td');
        if ( $td_elements.length === 1 ){
            return $td_elements.eq(0).text();
        }
    });
    return false;
}

//How to use:
//Somewhere not in a loop (to call it only once)
var user = determineCurrentUser();

Second, deside what buttons to append based on user:
if (user === 'John'){
    if (this_type === 'City'){
        //append nothing
    } else if (this_type === 'Street'){
        toolbar.append( gmaps ).append( google );
    } else {
        // default (for all the rest "types")
        toolbar.append( gmaps ).append( google ).append( phone ).append( copy );
    }
} else if (user === 'Steve'){
    if (this_type === 'City'){
        //append nothing
    } else if (this_type === 'Street'){
        //only `google` for Steve's street
        toolbar.append( google );
    } else {
        // default (for all the rest "types")
        toolbar.append( gmaps ).append( google ).append( phone ).append( copy );
    }
}

*
I would also put all per-user and per-th-type rules to a config object somewhere not in the mouseenter handler, but that's next step.

A: Alternate solution using hashmap of options based on known names as keys and indexing of dom elements:
var config = {
  "John" : {"map": "gmap", "links":[1,4,6]},
  "Steve" : {"map": "bing", "links":'all'}
}

Assume table is first table in page and toolbar goes in 2nd cell on row where name is also located
var $table = $('table').eq(0);
$table.find('tr>th:eq(1)').on("mouseenter mouseleave", function(e) {
        var opts = config[$(this).text()];
        if (e.type === 'mouseenter') {

This will certainly take some fine tuning but using indexing is likely your best approach

A: For starters use class to denote elements that should have toolbar.
You could pass a config object to data- attribute for the various options if this is being rendered server side. If it is being rendered client side use data() method to store on element

    Name
    Paul Johnson
    Birthdate
    28th May 1974

JS
$('th.has-toolbar').on("mouseenter mouseleave", function(e) {
        var opts = $(this).parent().data('toolbar-options');
        if (e.type === 'mouseenter') {
          // use opts to determine what goes in toolbar

Use indexing to figure out next/previous


text:
Q: Decreasing the height of Buttons in SWT Table rows I have an org.eclipse.swt.widgets.Table. I put a org.eclipse.swt.widgets.Button
 to the last column.
If it is unchanged, my Button hogs all space available in cell both vertically and horizontally.
I figured out a way how to manipulate the width of the Button (see below). However this approach does not work on heights. I would prefer to reduce the height of the Button by some pixels if possible. Or adding some padding above and below. Or increasing the height of the row and leaving the height of the Button unchanged.
Any help is highly appreciated.
Here is what I have so far:
private void createButtons(Table table) {

    int items = tableViewer.getTable().getItems().length;

    TableEditor[] editors = new TableEditor[items];
    Button[] buttons = new Button[items];

    for (int i = 0; i < items; i++) {
        Button button = new Button(table, SWT.PUSH);
        buttons[i] = button;
        button.setText("Details");
        button.setSize(100, 10); //(Works perfectly on width, fails on height)

        TableEditor editor = new TableEditor(tableViewer.getTable());
        editors[i] = editor;
        editor.minimumHeight = button.getSize().y;
        editor.minimumWidth = button.getSize().x;

        editor.setEditor(button, tableViewer.getTable().getItem(i), 3);
    }
}

A: The height of a table item is dictated by its content. Usually the height is chosen so that text and image can be displayed. Unless you implement custom painting, you cannot influence the table item height.
To add a margin around the button, you should put it into a Composite with a suitable layout (e.g. a FillLayout with marginWith and/or marginHeight set accordingly).


text:
Q: Frequent BSOD on Windows 10 VNC Server I'm using RealVNC server v6.7.2 x64 home edition and ever since I started using it, my laptop that is the VNC server has been randomly displaying a "blue screen of death" and then shutting down.  This is happening almost daily where as this laptop almost never BSOD'ed before.
Are there any settings in VNC server that might cause or help prevent the "server" from crashing?  I realize this could potentially be an issue totally unrelated to VNC Server, but it seems like there's a correlation between it's use and the now frequent BSODs.
My server laptop is a Lenovo ThinkPad P51 running Windows 10 Enterprise (version 20H2, build 19042.630) and is fully patched.


text:
Q: Hide property from Swagger conditionally? I have a class that I am annotating with Swagger annotations for documentation of our API. One such class is used as part of the Response for two different endpoints. However, we are using @JsonView to hide some of the properties of the class for the different endpoints. When our Swagger.json is generated, the hidden properties are shown for both responses.
I was able to hide the properties completely by annotating them with @ApiModelProperty(hidden = true), however this hid them from both responses. Is there any way to use the JsonView to hide the properties only from some responses?

A: Short answer is NO, there is no current support for conditional behaviour for ApiModelProperty.
Long answer - its quite a challenge - becauae as far as swagger/springfox issues go( #805,#563 ).
seems there is support of JsonView, and this feature was added to release version 3.0.0, also seems that issue #805, is very similar to what you are facing, so its a good place to start.
It also mentions that there is a way, but it involves removing JsonView and rely on mapping DTOs to Models using mapstruct's @Mapper annotated Interfaces, which let you generate different DTO's for the same model.
And from a personal opinion, I think there should a seperation of responsibity here and have a 1:1 relationsip between DTO and request/response models or content, maybe have those specific cases be handled using plain old java way.
From top of my head assuming your usecase is for a Student object:
Absraction
public interface Student {
    int getId();
    String getName();
    String getAge();
}

Model

also acts as controller, can access the view layer and data layer

public class StudentModel implements Student {
    private int id;
    private String insuranceNumber;
    private String natSecurityNum;
    private String name;
    private String age;

    public double calculateEnrolmentFee() {
        // some database/service calls
    }
    public StudentInfo getInfo(){
        // map model to info dto
    }
    public StudentDetails getDetails() {
       // map model to details dto
    }

    public void terminateEnrollment() {
        // some behaviour and state changes
    }
    // Override Student's getters
    .
    .
    .

}

View

For endpoint 1

public class StudentInfo implements Student {
    private int id;
    private String name;
    private String age;

   // Override Student's getters and add setters
    .
    .
}

For endpoint 2

public class StudentDetails implements Student {
    private int id;
    private String insuranceNumber;
    private String natSecurityNum;
    private String name;
    private String age;

    // Override Student's getters and add getter/setter based on design
    .
    .
    .
}

You can use builders aswell.


text:
Q: Angular2 run animation on leave & observable filter I have a component that I can animate on entry like this, the entry animation works fine. The handleRemoval method gets executed and an event emitter filters the component from the list of components (using observables). But the :leave animation does not run:
    @Component({
        animations: [
            trigger(
            'enterAnimation', [
                transition(':enter', [
                style({transform: 'translateY(100%)', opacity: 0}),
                animate('500ms', style({transform: 'translateY(0)', opacity: 1}))
                ]),
                transition(':leave', [
                style({transform: 'translateY(0)', opacity: 1}),
                animate('500ms', style({transform: 'translateY(100%)', opacity: 0}))
                ])
            ]
            )
        ],
        template: `
            <div class="mb1 card text-xs-center rounded" [@enterAnimation]="show">

    ...
export class ContentPropertyComponent {

    show: boolean = false;

    constructor(private router: Router) {
        this.show = true;
     }

    handleRemoval(contentProperty: PropertyModel) {
        this.show = false;
        this.delete.emit(this.contentProperty);
    }
}

Any help appreciated.

A: Angular introduced the :enter and :leave shortcuts in version 2.1.0, so if you're using an earlier version (as I suspect), you should use the void => * and * => void transition definitions. Or, alternatively, upgrade your Angular distribution to 2.1.0+.
Changing your code accordingly works in Angular 2.0+
animations: [
    trigger("enterAnimation", [
      transition('void => *', [
          style({transform: 'translateY(100%)', opacity: 0}),
          animate('500ms', style({transform: 'translateY(0)', opacity: 1}))
        ]),
        transition('* => void', [
          style({transform: 'translateY(0)', opacity: 1}),
          animate('500ms', style({transform: 'translateY(100%)', opacity: 0}))
        ])
    ])
  ]

Plunker: https://plnkr.co/edit/xW38PWgD3SQyhRv09IUW?p=preview


text:
Q: Incorrect compiler error usage of uninitialized variable I just encountered a case where Visual Studio tells me my code might result in accessing an uninitialized variable, but the rules of boolean logic dictate this isn't possible here.
I simplified the code to visualize the problem, in this case appearing for x:
static void Main(string[] args)
{
    IDictionary<String, MyType> dictionary = null;
    if (new Random().Next() % 2 == 0)
    {
        dictionary = new Dictionary<string, MyType>();
        dictionary.Add("xyz", MyType.Whatever);
        dictionary.Add("abc", MyType.DontCare);
    }

    var myType = dictionary?.TryGetValue("abc", out var x) ?? false ? x : MyType.None;
}

enum MyType
{
    None,
    Whatever,
    DontCare
}

In case dictionary isn't initialized it's null, thus resulting in ?? evaluating the ternary operator to false. This is the only case where x won't be initialized, but still I get the error message for x in the true case of the ternary operator.
Remarks: Setting parenthesis doesn't change anything, and resolving the ternary operator to a full-fledged if doesn't either.
Is this a known behavior or a bug?
EDIT: Just to clarify, I DO know how to fix the problem. I was just slightly surprised to encounter this error, since the described problem, accessing the uninitialized x, will never happen according to boolean logic.
EDIT: Using a full if doesn't change the problem:
static void Main(string[] args)
{
    ...

    MyType myType;
    if (dictionary?.TryGetValue("abc", out var x) ?? false)
    {
        myType = x; // <-- error still occurs here
    }
    else
    {
        myType = MyType.None;
    }
}

A: The problem is the x in this line:
var myType = dictionary?.TryGetValue("abc", out var x) ?? false ? x : MyType.None;

Since you have a null-propagation operator (?.), x will never be assigned when dictionary is null. You have to take out x as a separate variable above the var with a default value.
MyType x = MyType.None;

var myType = dictionary?.TryGetValue("abc", out x) ?? false ? x : MyType.None;

The static compiler just isn't smart enough to figure out the null-propagation operator will cause that expression always to return false (and hence x is never used). Not it just treats the statement as if it can.
As you can see on the C# language Github page, there is an active feature request to let the compiler figure out the outcome of the null-propagation operator.


text:
Q: Adding columns from one datagridview and results into another datagridview The main task is to use values from one datagridview and have the sum be displayed on another datagridview on the same form.
There will be two datagridviews on the same form
datagridview1
 apples | oranges
      2 | 3
     10 | 20
      1 | 1

datagridview2
 total apples | total oranges
           13 | 24

is this at all possible?
If not, I was thinking of possibly creating a new row in the original datagridview?

A: Here's code to find the total of column index "1" for datagridview1 :
                Dim total As Double 'double or integer depends on your situation
                For i As Integer = 0 To DataGridView1.RowCount - 1
                    total += DataGridView1.Rows(i).Cells(1).Value
                Next

Now you need to add total to another datagridview:
                DataGridView2.Rows.Add("Oranges",total)


text:
Q: how to check a kernel version which was used when building package I use apt when downloading packages from Ubuntu repositories. How can I check which kernel version was used when building package?
When it is important (kernel version of the build server vs. kernel version of the machine where package is installed)?

A: It's almost never important.  If you're truly worried about the build system, you should consider the compiler, library and header versions before considering the kernel.
It is up to the code itself as to whether it 'remembers' the kernel version.  Some packages store a string representing the compiler version, as this is far more important.  In fact the kernel itself does this (see the contents of /proc/version).

A: I will not add anything about importance or not of knowing that kernel version since the comments and the answer above is fully explained.
But as an answer for your comment in the answer above

What about graphics drivers (kernel build vs run environment) ?

What you must care is the gcc version that the kernel was compiled with so that you have to use same version with respect to your graphic drivers(Nvidia specially).
You need tocat the /proc/version file. This file identifies the kernel version that is currently running and gcc version used to build the kernel.
$ cat /proc/version
Linux version 3.2.0-23-generic (buildd@crested) (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu4) ) #36-Ubuntu SMP Tue Apr 10 20:39:51 UTC 2012

So as example start building NVIDIA module using gcc-4.6:
$ export CC=/usr/bin/gcc-4.6
$ bash NVIDIA-Linux-***.run


text:
Q: How to calculate the day of the week based on unix time I know that there are functions/classes in most programming languages to do that, but I would like to know the calculation.
So: How do I get from the unix time in seconds to a day-number (e.g. 0 for Sunday, 1 for Monday etc.)?
Thanks in advance. BTW: this is my first post on Stack Overflow.

A: The problem you ask is reasonably easy, compared to how ridiculously complicated other date/time functions can be (e.g. Zeller's congruence).

*

*Unix time is defined as the number of seconds elapsed after January 1, 1970, at 00:00 (midnight) UTC.

*You can look up a calendar to find that 1970-01-01 was a Thursday. There are 24 * 60 * 60 = 86400 seconds in a day.

*Therefore values 0 to 86399 are Thursday, 86400 to 172799 are Friday, 172800 to 259199 are Saturday, etc. These are blocks of 86400 seconds aligned at 0.

*Suppose T is your Unix timestamp. Then floor(T / 86400) tells you the number of days after 1970-01-01. 0 = Thursday January 1st; 1 = Friday January 2nd; 2 = Saturday January 3rd; etc.

*Add 4 and modulo 7. Now 0 → 4; 1 → 5; 2 → 6; 3 → 0; 4 → 1; 5 → 2; 6 → 3; 7 → 4; 8 → 5; 9 → 6; 10 → 0; etc. This is your final answer.

*In summary: day of week = (floor(T / 86400) + 4) mod 7.

*(This assumes that you want the day of week in UTC. If you want to calculate it for another time zone, you need to perform some addition or subtraction of hours and minutes on T first.)

A: In JavaScript, days of the week are:
0 = Sun
1 = Mon
2 = Tue
3 = Wed
4 = Thu
5 = Fri
6 = Sat

You can use built-in methods:
// Unix epoch, 4 = Thu
new Date(0).getUTCDay()

// Today, 2 = Tue
new Date().getUTCDay()

Or a custom solution (remember to divide getTime() milliseconds  by 1000):
// Unix epoch, 4 = Thu
(Math.floor(new Date(0).getTime() / 86400 / 1000) + 4) % 7

// Today, 2 = Tue
(Math.floor(new Date().getTime() / 86400 / 1000) + 4) % 7

Solution (from Geek for Geeks):
function dayOfWeek(d, m, y) {
  let t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
  y -= (m < 3) ? 1 : 0;
  return ( y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}

// Unix epoch, 4 = Thu
Math.floor(dayOfWeek(1, 1, 1970))

// Today, 2 = Tue
Math.floor(dayOfWeek(7, 12, 2021))

https://www.geeksforgeeks.org/find-day-of-the-week-for-a-given-date/


text:
Q: Windows USB Tutorial I've been trying to follow the Windows USB Tutorial at Microsoft MSDN
I've followed it through to the end without error and this is the output
1>------ Build started: Project: USB Application1, Configuration: Win7 Debug x64 ------
1>  device.cpp
1>  main.cpp
1>  Generating Code...
1>  USB Application1.vcxproj -> c:\users\hp\documents\visual studio 2013\Projects\USB Application1\x64\Win7Debug\USBApplication1.exe
2>------ Build started: Project: USB Application1 Package, Configuration: Win7 Debug x64 ------
2>  Stamping x64\Win7Debug\USBApplication1.inf [Version] section with DriverVer=03/22/2014,13.49.5.125
2>C:\Program Files (x86)\Windows Kits\8.1\build\WindowsDriver.common.targets(1300,5): warning : The driver package project c:\Users\hp\documents\visual studio 2013\Projects\USB Application1\USB Application1 Package\USB Application1 Package.vcxproj doesn't have any references to other projects and no projects were packaged.
2>C:\Program Files (x86)\Windows Kits\8.1\build\WindowsDriver.common.targets(1300,5): warning :
2>  ........................
2>  Signability test complete.
2>
2>  Errors:
2>  None
2>
2>  Warnings:
2>  None
2>
2>  Catalog generation complete.
2>  c:\users\hp\documents\visual studio 2013\Projects\USB Application1\x64\Win7Debug\USB Application1 Package\usbapplication1.cat
2>  Done Adding Additional Store
2>  Successfully signed: c:\users\hp\documents\visual studio 2013\Projects\USB Application1\x64\Win7Debug\USB Application1 Package\usbapplication1.cat
2>
========== Build: 2 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

When I try to manually update the USB driver in the device manager, I keep getting
The required section was not found in the INF.

I have tried with two devices, a thumbdrive and a mobile phone but all with the same (non) results.  Anybody know what is wrong please?
This is one of the INF files
;
; USBApplication1.inf
;
; Installs WinUsb
;

[Version]
Signature = "$Windows NT$"
Class     = USBDevice
ClassGUID = {88BAE032-5A81-49f0-BC3D-A4FF138216D6}
Provider = %ManufacturerName%
CatalogFile=USBApplication1.cat
DriverVer=03/22/2014,13.49.5.125

; ========== Manufacturer/Models sections ===========

[Manufacturer]
%ManufacturerName% = Standard,NTamd64

[Standard.NTamd64]
%DeviceName% =USB_Install, USB\VID_04E8&PID_685E

; ========== Class definition ===========

[ClassInstall32]
AddReg = ClassInstall_AddReg

[ClassInstall_AddReg]
HKR,,,,%ClassName%
HKR,,NoInstallClass,,1
HKR,,IconPath,%REG_MULTI_SZ%,"%systemroot%\system32\setupapi.dll,-20"
HKR,,LowerLogoVersion,,5.2

; =================== Installation ===================

[USB_Install]
Include=winusb.inf
Needs=WINUSB.NT

[USB_Install.Services]
Include=winusb.inf
AddService=WinUsb,0x00000002,WinUsb_ServiceInstall

[WinUsb_ServiceInstall]
DisplayName     = %WinUsb_SvcDesc%
ServiceType     = 1
StartType       = 3
ErrorControl    = 1
ServiceBinary   = %12%\WinUSB.sys

[USB_Install.HW]
AddReg=Dev_AddReg

[Dev_AddReg]
; By default, USBDevice class uses iProduct descriptor to name the device in
; Device Manager on Windows 8 and higher.
; Uncomment for this device to use %DeviceName% on Windows 8 and higher:
;HKR,,FriendlyName,,%DeviceName%
HKR,,DeviceInterfaceGUIDs,0x10000,"{5aecf9ec-5a73-421b-841d-e9ab9b241a2b}"

[USB_Install.CoInstallers]
AddReg=CoInstallers_AddReg
CopyFiles=CoInstallers_CopyFiles

[CoInstallers_AddReg]
HKR,,CoInstallers32,0x00010000,"WdfCoInstaller01011.dll,WdfCoInstaller"

[CoInstallers_CopyFiles]
WdfCoInstaller01011.dll

[DestinationDirs]
CoInstallers_CopyFiles=11

; ================= Source Media Section =====================

[SourceDisksNames]
1 = %DiskName%

[SourceDisksFiles]
WdfCoInstaller01011.dll=1

; =================== Strings ===================

[Strings]
ManufacturerName=""
ClassName="Universal Serial Bus devices"
DiskName="USBApplication1 Installation Disk"
WinUsb_SvcDesc="WinUSB Driver"
DeviceName="USBApplication1 Device"
REG_MULTI_SZ = 0x00010000

Okay, I found c:\windows\inf\setupapi.dev and I think the part in question is
     dvi:                     CoInstaller 1: Enter 20:25:55.535
     inf:                          Opened PNF: 'C:\Windows\INF\oem75.inf' ([strings])
!!!  dvi:                     CoInstaller 1: failed(0xe0000101)!
!!!  dvi:                     Error 0xe0000101: The required section was not found in the INF.
     dvi:                {DIF_INSTALLDEVICE - exit(0xe0000101)} 20:25:55.703
!!!  ndv:                Error(e0000101) installing device!
     ndv:                Device install status=0xe0000101
     ndv:                Performing device install final cleanup...
!    ndv:                Queueing up error report since device installation failed...
     ndv:           {Core Device Install - exit(0xe0000101)} 20:25:55.708
     dvi:           {DIF_DESTROYPRIVATEDATA} 20:25:55.709
     dvi:                CoInstaller 1: Enter 20:25:55.709
     dvi:                CoInstaller 1: Exit
     dvi:                Default installer: Enter 20:25:55.710
     dvi:                Default installer: Exit
     dvi:           {DIF_DESTROYPRIVATEDATA - exit(0xe000020e)} 20:25:55.711
     ump:           Server install process exited with code 0xe0000101 20:25:55.718
     ump:      {Plug and Play Service: Device Install exit(e0000101)}
     ndv: {Update Driver Software Wizard exit(e0000101)}
<<<  Section end 2014/03/22 20:26:31.825
<<<  [Exit status: FAILURE(0xe0000101)]

There are also some occurrences of
     sig:                Key      = usbapplication1.inf
     sig:                FilePath = C:\Windows\System32\DriverStore\FileRepository\usbapplication1.inf_amd64_neutral_bebc4e93bfc6a60a\usbapplication1.inf
     sig:                Catalog  = C:\Windows\System32\DriverStore\FileRepository\usbapplication1.inf_amd64_neutral_bebc4e93bfc6a60a\USBApplication1.cat
!    sig:                Verifying file against specific Authenticode(tm) catalog failed! (0x800b0109).
!    sig:                Error 0x800b0109: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.

for various files above that

A: I ran into the same problem with the WinUSB sample application from the Win 8.1 WDK.  Their sample INF appears to be missing the following sections:
[USB_Install.Wdf]
KmdfService=WINUSB, WinUsb_Install

[WinUsb_Install]
KmdfLibraryVersion=1.11

After adding this to my INF, it installs OK.


text:
Q: New Battery: Runs out at "10% left" I installed a new Apple battery in my MacBook Pro (13-inch, Late 2011) myself (bought the battery new from iFixIt).
Installation worked great, extra 4 hours of battery life - fantastic.
Then I decided to get all smarty-pants and "recalibrate the battery".  I let the battery run empty, and the system entered "deep sleep"/"hibernation" mode as expected.
THEN I broke it when I did an SMC reset, as found here.
Ever since the SMC reset, when my battery meter in the menu bar gets to ~9%, the system completely shuts off without warning.  No hibernation, nothing - complete power off.
Can anyone tell me how to get the system to properly recognize that the battery is almost dead, so it enters deep-sleep as it used to?
Things I've tried: Resetting SMC again, running battery dead and charging back to full.
Battery Charge Cycle counts looks normal; here are possibly relevant specs form system profiler:
Battery Info > Charge Information:
Full Charge Capacity (mAh): 5683
Health Information:
Cycle Count:    100
Condition:  Normal

System Power Settings > Battery
Hibernate Mode: 7
Reduce Brightness:  Yes
Standby Delay:  4200
Standby Enabled:    0

A: If a new battery doesn't work with your hardware - I would return it to the vendor or seek service. Some aftermarket batteries may not work properly and the failure you describe isn't likely to be something you (or any technician) messed up with cabling or connectors not seated.
When you reset the SMC it perhaps did a full read of the battery details and something isn't correct for it's code to predict when to send the low voltage / low charge warnings and begin an orderly shutdown.
This failure mode is different than the shutting off too high a remaining change - but it could be the same fix - get another battery.

*

*Battery on white MacBook shuts off abruptly after 30% charge is left


text:
Q: AGAIN: read failed, socket might closed or timeout I want pair my android  device(android 4.2.2) to another android device that founded by BluetothAdapter.startDiscovery(). What I found when run BluetoothDevice.connect() request pairing start.
but I have problem to run connect() and I got
  read failed, socket might closed or timeout, read ret: -1

I tried impliment fallback and gatclass , methods in
IOException: read failed, socket might closed - Bluetooth on Android 4.3
also correct UUID according to
Bluetooth Connection failed "java.io.IOException: read failed, socket might closed or timeout, read ret: -1"
and static UUID"00001101-0000-1000-8000-00805F9B34FB"
But all of them not work for me
My code is huge but blow code is similar (and same problem)
Android want to send bluetooth pair request to another devices
can any body help  PLZ ?

A: I found my answer in another Question!. this link:
Android Connect Bluetooth device automatically after pairing programmatically
In Question discripe how connect(and it's answer complete it)
Note: before Test sure devices are Unpair


text:
Q: Firebase's Realtime database's `child_removed` event not firing let database = firebase.database(); //the database is empty.

database.ref('user').set({
    color: "red",
    height: 180,
});

database.ref('user/color').remove();

database.ref('user').on('child_added', e => {
    console.log(e.val());
});

database.ref('user').on('child_removed', e => {
    console.log(e.val());
});

I expect 'child_removed' to fire because of: database.ref('user/color').remove(); and I expect it to log out 'red'.
'child_added' seems to work like so: it fires for every value user ends up with. So the only thing that gets logged to the console is 180.

A: The issue is that you call .remove() before you setup the listener. Put your listener before calling .remove():
let database = firebase.database(); //the database is empty.

database.ref('user').set({
    color: "red",
    height: 180,
});

// listener first
database.ref('user').on('child_removed', e => {
    console.log(e.val());
});

// then calls
database.ref('user/color').remove();


text:
Q: Create a drool to list all rules within other drools basically i was wondering if there is a way to run something and it would go into every drools file in the directory's under it (in a folder with say 50 folders in there, would go into each folder.) and pull certain data from these files
So i run it, it access lets say 10 .DRLs each with 5 rules inside that have a name rule "blah blah" and a logger.info line. among what the rule actually does.
Could something be written to go into all these files and create a list of each filename, then under that all rule names and logger lines?
We have roughly 500 .drl files each with anything from 1 to 100 rules within these files. manually creating a list of what we have in place for each file, would take alot of time :)

A: Drools can do this, but I don't think it is the tool you would want to employ. Drools is for modeling business logic. You aren't really doing that here. You could pull the data manually using notepad++, grep, emacs, or other mass text manipulation tools. I wouldn't really recommend that either.
The best tool for this task is probably going to be a script written in python or ruby. Ruby being the one I would pick in this instance for its better integration of regular expressions. Once you have this script you can extract this data at will in the future. Scripts are re-usable and extendable. This makes them a better choice than the hack and slash of mass text editors if you expect you will need this information or information like it on a regular basis.
If one of your requirements is that this task occur whenever your drools fire then it might be easier to do this text processing in Java. You would probably want to have Java do the work before or after the fireAllRules event depending on your requirements.
Finally, drools does actually know quite a bit about itself. You could conceivably ask drools for a lot of this information when it runs. I have never done this myself. When I had to tackle a task like the one you describe, I used a script.


text:
Q: What to do when a declare array variable is undefined at view but working with controller laravel 5.7 Here is the code:
    public function chat($id=1){

    Route::view('/chat', 'chat');

    $id = View::make('chat.blade', ['reviewer_id' => Reviewer::findOrFail($id)]);

    $audiences = DB::table('audience')->get();

    $data = [
             'id'=>$id,
             'audiences'=>$audiences,
             'audience_id'=> 2
            ];
    return View::make('chat.blade', ['data'=>$data]);

}

As the code is simple I route to blade view, get data from database, get audience data, initialize data array return data to chat.blade simple code but in view

Undefined variable: data (View:
  /Users/userinfo/Sites/chat/resources/views/chat.blade.php)

View code:

        @foreach($data->audiences as $info->audience)
            {{$info->audience->id}};
        @endforeach

            <form action="/" method="post">
                <input type="hidden" value={{$reviewer_id}} name="id">
                <input type="hidden" value={{$audience_id}} name="id">
                <input type="text" name="message">
                <input type="submit" value="submit">
            </form>

<?php $__currentLoopData = $data->audiences; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $info->audience): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <?php echo e($info->audience->id); ?>;
            <?php endforeach; $__env->popLoop(); $loop =
$__env->getLastLoop();

?>

> undefined variable $data

A: change $data->audiences to $data['audiences'] in your view. $data is an array not an object

A: If i do it then i do it like this
public function chat($id = 1){
    Route::view('/chat', 'chat'); // I don't know what that is
    $reviewer_id = Reviewer::findOrFail($id); // or Reviewer::find($id);
    //I Update this little bit : $audiences = DB::table('audience')->get();
    $audiences = Audience::all();
    $audience_id = 2 ;
    return view('chat.blade', compact(['id','audiences','audience_id','reviewer_id']));
}

Now you can access all the variables passed in compact in your blade file like this

     // Depends on what is in the $audiences could be with "$key => $value"
     @foreach($audiences as $key)
            {{$key->id}};
     @endforeach

   <form action="/" method="post">
     <input type="hidden" value={{$reviewer_id}} name="id">
     <input type="hidden" value={{$audience_id}} name="id">
     <input type="text" name="message">
     <input type="submit" value="submit">
   </form>


text:
Q: Performance wise do or don't add width and height to an img tag I know this question is asked before.
Most of them are 5-6 years old, so at the latest browsers do you add or don't you add the height and width of the original img size?

or

The resizing of the img will still be done with css so it's not about separation styling from the html

A: tl;dr: it's no impact on loading time.
The benefit in adding the width and height to the image tag is that the browser will place floating text according to the image size and avoid "jumping" the text if the pictures is ready with loading.
So it makes sense to add the dimensions if you know them. If you're simply adding dummy values, than it's useless and should not be done.
Speed wise it's practically no impact. A reasonable width="1000px" height="800px" has 29 Bytes.
With a downstream of 24.0 Mbit/s that's a delay of 9.667 microseconds (in this time, light travels 2898 meters). With a 56kbit modem, it's 4.143 milliseconds per picture.
Even if you have 10.000 pictures on one page, the delay would only be 96.67 milliseconds (41.43 seconds with 56kbit). And it would cost a lot more time to load all the images.

A: If you're still going to style with CSS, is there any benefit in adding it in the first place?
If you're concerned about performance, you'd be better off having the images as the size required on upload, so that you're not loading bigger images than you need.

A: You should specify the size of the imgages if possible, so that the browser knows how much space the image will need. That prevents the browser from needing to move elements around to make room for images that appear.
Normally it won't matter if you set the size in the HTML or in the CSS, but setting it in the CSS may allow you to specify the same size for multiple images. Also, as the CSS is cached it makes sense to move styling there to reduce the HTML size.


text:
Q: difference between ECDSA key and RSA key what is difference between ECDSA key and   RSA key when we generate key for V2 of the ssh protocol?

A: This question is not Unix-related and should be asked on crypto.stackexchange.com instead.
Elliptic curve cryptography works different from RSA. RSA is based on prime numbers, ECDSA can use any numbers. That means that a key of twice the size brings the security to the power of two with ECRSA (160 bit key => 280 key space, 320 bit key => 2160 key space). With RSA the security increases more slowly. It becomes less and less effective to make long RSA keys more secure. In other words: You need more computing power per security with RSA (at least for long keys).


text:
Q: URL for the user profile? to be a subdomain or text after the slash? I'm creating an online based system that has public user profiles for all users..
I'm wondering how to organize the URLs for these public user profiles? What could be better for the SEO and of course for the user friendliness?

{username}.mysystem.com

or

mysystem.com/{username}

or maybe even

mysystem.com/users/{username}

Thanks in advance!

A: Definitely not a subdomain for SEO Purposes.
I personally prefer the last option mysystem.com/users/{username} as it gives a level of separation from the rest of the application.
This of course requires that {username} is always unique in the database.  If it is not (see StackOverflow and the ability to have whatever username you like even if it's taken), then you need to add a Unique Identifier in the url string as well mysystem.com/users/{userID}/{username}
Lastly, if the site ENTIRELY revolves around the user (IE: a blogsite), then you can remove the users from the url string and just go with {username} again providing "username" is unique mysystem.com/{username}

A: One consideration for SEO is "do the users benefit financially if their profiles get search traffic?"
If the answer is yes, then users have an incentive to build links to their profiles. You won't have any control over the types of links they create. Consequently algorithmic penalties could be applied to your website because one bad egg is trying to increase search traffic.
If you put their profiles on sub domains, then any negative SEO will only affect the sub domain and not the test of the website.


text:
Q: Use Windows Software with the least amount of Windows OS licenses
Possible Duplicate:
Can you help me with my software licensing question?

So as we slowly move towards web applications my company still has some legacy Windows applications we need to support - specifically Outlook, Quickbooks and UPS Worldship.
My ultimate goal is to remove Microsoft / Windows from the picture completely.  Unfortunately, I've hit a roadblock in the path forward.
My options seem to be:

*

*Maintain individual Windows desktops join to a Domain.

*Thin clients that use cloned virtual desktops.

*Thin clients that use Terminal (Remote Desktop) Services.
Regardless of these options, even when taking advantage of Citrix and/or VMWare offerings, it seems like there is no way of getting around paying for one Windows desktop license (whether it be "physical", virtual, or CAL) per one user.  Using Citrix or VMWare clouds the license picture even further.
Now, I can understand paying for one user license per Outlook instance, but per user for a common base to deliver the application?  But whatever - that's just the way it is if we're going to use software built for Windows environment - unless there's a loophole I'm missing?  Is there some configuration where I can simply deliver the applications to the end users without multiple middle-man fees per user?
I'm just curious which of these options is the cheapest and simplest, software license wise?

A: No loopholes. Pay for the licenses you're going to use. Microsoft has built a good platform that you obviously benefit from as a business. Compensate them for their work as you would want your clients to compensate you for yours.


text:
Q: Special characters not being read, even though file is set to UTF-8 The special characters in my HTML files are not being read in Firefox (works fine in Safari and Chrome), even though I have the character set set to UTF-8. See the "A Parlatë e A Memorjë" seciton: https://memoriaelinguagrumentina.org/index.html
And this is the meta tag I'm using:
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content-Type" content="text/html; charset=UTF-8">
I've read through a dozen other questions in this forum with similar problems, but none of the solutions apply to my situation. I don't want to use HTML elements, because it would make editing a nightmare. And I'm not using anything other than HTML and CSS on this page.
Any suggestions?


text:
Q: Populating a Tree list from database I'm looking to populate a treelist with our company structure. In my database i have a table with positions that have the following layout
PositionID - Integer for the position
PositionText - Text for the position
ReportsToID - Position ID that this position reports to.

I would like to load the positions that first report to positionID=0 (Root level) and then cascade load each of the positions from there onwards while populating a Treeview so i can then have somthing like:
-Position 1
  -Position 3
  -position 5
     -Position 7
  -Position 4
     -Position 2

Any suggestions on how to achieve this would be great, even some sudocode would help me on the right track.
EDIT: I am able comfortable with adding nodes to my tree view, but where i am getting a little hung up is how to loop/recursive search so that i can work through my items and add everything. Im thinking somehow i need to add my first node, see if anyone reports to that node. If there are, add them. Then for the next level nodes, see if anyone reports to them and then continue.
I'm probably a little stuck on how to do the loop cleanly and efficiently.

A: Use this recordset:
SELECT ReportsToID, PositionID, PositionText
FROM Table
ORDER BY ReportsToID, PositionID

then

*

*Create the root node (0) in your tree

*Take the first row (which will need to have ReportsToID=0 in it)

*Create the PositionID node under the ReportsToID node
Note that ReportsToID has already been created in step 1 or 3

*Take the next row and go to step 3

Having the order means that you always create one complete level before going on to the next level.
Just be aware there is a major assumption here, and that is that ID's are incremental. For example ReportsToID=5 is on a lower level than ReportsToID=6
You can avoid this with a more sophisticated query that adds a 'path' column. Then you order on the path. You need a CTE for that.

A: TreeViews are tricky.
There are two approaches.

*

*Fill all the tree at once.

Pros: You hit the data base once. Less code.
Cons: If there are a lot of data, treeView will take some serious time to be filled.

*Fill only first level, add dummy nodes (to indicate a false cross-sign) and on BeforeExpand query the data base to fill the node.

Pros: Very fast.
Cons: Query the database on the first BeforeExpand of each node. More code.
So, if you have just some nodes to fill go with the first approach.
But if there are serious data, second works better.

A: I was able to work a solution to this which is posted below. This might not be the most elegant but it works quickly and seems to work correctly. Any feedback on this will be great.
 Private Sub LoadTreeList()
    TreeView1.Nodes.Clear()
    Dim dr() As System.Data.DataRow
    dr = Me.PositionsDataSet.Positions.Select("ReportsToPositionID = 0")
    'Populate the First Node
    For Each Row In dr
        TreeView1.Nodes.Add(Row("PositionID").ToString, Row("PositionText").ToString)
        AddSubNodes(TreeView1.Nodes(Row("PositionID").ToString))
    Next

End Sub

Private Sub AddSubNodes(ByVal CurrentNode As TreeNode)
    Dim dr() As System.Data.DataRow
    dr = Me.PositionsDataSet.Positions.Select("ReportsToPositionID = " & CurrentNode.Name)
    For Each Row In dr
        Dim NewNode As TreeNode = CurrentNode.Nodes.Add(Row("PositionID").ToString, Row("PositionText").ToString)
        Dim dr2() As System.Data.DataRow
        dr2 = Me.PositionsDataSet.Positions.Select("ReportsToPositionID = " & Row("PositionID").ToString)
        If dr2.Count > 0 Then
            AddSubNodes(NewNode)
        End If
    Next
End Sub


text:
Q: Bash script that needs root only runs when I type exit! I have successfully made a bash script that needs root, permission, which I can run as root! But, the script only runs when I am using the terminal as root and if I type exit, it runs.  When I type :
bash lights_infinity.sh

The terminal does nothing. Why is this so and is it normal? The code is
#!/bin/bash

sudo su
while true
do
    sudo -k setleds -D +caps < /dev/console
    sleep 0.1
    sudo -k setleds -D +caps < /dev/console
    sleep 0.1
    sudo -k setleds -D -caps < /dev/console
    sleep 0.1
done

Do I need to remove the sudo commands?

A: I would
#!/bin/bash
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi
while true
do
    setleds -D +caps < /dev/console
    sleep 0.1
    setleds -D +caps < /dev/console
    sleep 0.1
    setleds -D -caps < /dev/console
    sleep 0.1
done

and do this:
sudo lights_infinity.sh

(add the -k if you want to kill the 15 minute time-frame for sudo but should not be needed)

The reason you need the "exit" is due to the "sudo su" you used. That opens an extra shell you need to "exit".

*

*extra: check for "root" at the beginning of the file. If this runs for 15 minutes it might error out(not sure); if so add "sudo" to the "setleds" and it will stop and ask the password.

*extra2: 3 times "setleds -D +(/-)caps < /dev/console
sleep 0.1" looks better when you use a function. And the while loop will look better if it has a nicer exit than control-x.


text:
Q: Turn standard date "DD/MM/YYYY" into UNIX Time We have a form capture apps from front end that need to pass the value into a UNIX database system.
Since there is no direct integration available, we use Zapier to do this, and it works well except for date conversion, as since we code it in JSON (via Zapier webhook), the UNIX database system muse conform to Unit Date format (e.g. for DOB 1/1/1970 will need to be written as "DOB" : "/Date(-39600000+1100)/",)
The challenge is, how do I convert the standard DD/MM/YYYY into the above format via zapier (since i use it for the integration) so the database can accept it without issue?

A: I'm presuming the date format you are talking about is the ISO date format. It looks like this - 2018-03-16T00:00:00.000Z.
You might want to add an intermediary step to format the date field received from your Form Trigger.
Method 1 - Using Zapier Formatter App:

*

*Add an action after your trigger step and choose the Formatter app.
screenshot

*Select the Date/Time option
screenshot

*Choose Format under Transform. In the input field, select the date field from the trigger step.

*Setup the to format, from format, and timezone as required.
screenshot

*Use this field in your next Webhook action.

Zapier has an article on formatting dates here.
Method 2 - Using Code app by Zapier:
In case you need more control, you can use the code app by Zapier.

*

*Choose the Code app, select "Run Javascript".

*In input data set the date field from your trigger app to a property named 'iDate'.
screenshot

*In the code section, copy and paste the code below.

*In the last line you can change the strJSON text to any of the other formats listed above it.

*Use the date field output from the code step in your Webhook action.

var yourDate = inputData.iDate;
var dArr = yourDate.split('/');
var d = Date.parse(`${dArr[2]}-${dArr[1]}-${dArr[0]}`);

//String representation of the Date for JSON
var strJSON = new Date(d).toJSON();
console.log('JSON String Representation: ', strJSON);

//ISO Date Format
var iso = new Date(d).toISOString();
console.log('ISO: ', iso);

//Date String
var str = new Date(d).toDateString();
console.log('Date String: ', str);

//Date String with time
var strTstamp = new Date(d).toString();
console.log('Timestamp String: ', strTstamp);

var output = {date: strJSON};

Update:
You can use the below code in the Code app on Zapier (do the setup as instructed above). This will output the time in the format you specified in your comment -39600000+1100.
var yourDate = inputData.iDate;
var dArr = yourDate.split('/');

//11*60*60*1000 for +11:00 Timezone. It is converting 11 hours into milliseconds.
//If your timezone is +05:30, 5*60*60*1000+(30*60*1000)
var unixTime = new Date(`${dArr[2]}-${dArr[1]}-${dArr[0]} 00:00:00 UTC`).getTime() - (11*60*60*1000);

//If your timezone is not +11:00, swap it below.
var unixWithTZ = `${unixTime}+1100`

console.log('UnixTime: ', unixWithTZ);
console.log('UnixWithTZ: ', unixWithTZ);

var output = {date: unixWithTZ};

Read more about Unix Time here.


text:
Q: How to show broadcast (simultaneous sending of two messages) in sequence diagrams in PlantUml I have this bit of plantuml:
@startuml

title Sequence diagram

A -> B : First
B -> C : Second
B -> A : Third

@enduml

It renders like this:

I would like to get this instead, with two arrows "happening concurrently":

Any hints on how to achieve this are appreciated!

A: You might find an answer with the Teoz pragma https://plantuml.com/teoz
@startuml
!pragma teoz true
title Sequence diagram

A -> B : First
B -> C : Second
&B -> A : Third

@enduml


text:
Q: Issue with data return in MongoDB I am facing a join issue in c# but I implement a join with MongoDB query successfully.
I created a database and create two collections.
MongoDB database and join
> db.childDocument.find().pretty()
{
        "_id" : 1,
        "sku" : "almonds",
        "description" : "product 1",
        "instock" : 120
}
{ "_id" : 2, "sku" : "bread", "description" : "product 2", "instock" : 80 }
{
        "_id" : 3,
        "sku" : "pecans",
        "description" : "product 4",
        "instock" : 70
}
{ "_id" : 4, "sku" : "rms", "description" : "product5", "instock" : 80 }
> db.masterDocument.find().pretty()
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2 }
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1 }
{ "_id" : 3, "item" : "rms", "price" : 56, "quantity" : 3 }

I am implementing a join functionality in MongoDB successfully
> db.masterDocument.aggregate([{ $lookup:{ from:"childDocument",localField:"item",foreignField:"sku",as:"data"  }  }])
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2, "data" : [ { "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 } ] }
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1, "data" : [ { "_id" : 3, "sku" : "pecans", "description" : "product 4", "instock" : 70 } ] }
{ "_id" : 3, "item" : "rms", "price" : 56, "quantity" : 3, "data" : [ { "_id" : 4, "sku" : "rms", "description" : "product5", "instock" : 80 } ] }

but I am trying to join in C# but not properly return a data in Postman:
I want to below output in ASP.NET Core Web API:
{ "_id" : 1, "item" : "almonds", "price" : 12, "quantity" : 2, "data" : [ { "_id" : 1, "sku" : "almonds", "description" : "product 1", "instock" : 120 } ] }
{ "_id" : 2, "item" : "pecans", "price" : 20, "quantity" : 1, "data" : [ { "_id" : 3, "sku" : "pecans", "description" : "product 4", "instock" : 70 } ] }
{ "_id" : 3, "item" : "rms", "price" : 56, "quantity" : 3, "data" : [ { "_id" : 4, "sku" : "rms", "description" : "product5", "instock" : 80 } ] }

Web API
public BookDB(IOptions<BooksConfiguration> settings)
{
    _settings = settings.Value;
    var ConnectionString = new MongoClient(_settings.ConnectionString);
    var database = ConnectionString.GetDatabase("document");
    _childDocument = database.GetCollection<childDocument>("childDocument");
    _masterDocument = database.GetCollection<masterDocument>("masterDocument");
}

public async Task<List<masterDocument>> getBookDescription()
{
    //var query = _childDocument.Aggregate().Match(e => e.sku == "almonds").ToList();

    var masterdocument =
                     from u in _childDocument.AsQueryable<childDocument>()
                     join a in _masterDocument.AsQueryable<masterDocument>() on u.sku equals a.item
                     //join c in _childDocument.AsQueryable<childDocument>() on c._id equals c._id   //master id
                     select new masterDocument()
                     {
                         _id = u._id,
                         item = a.item,
                         price = a.price,
                         quantity = a.quantity,
                         //_id = u._id,
                         //childDocuments = new List<childDocument>
                         //{
                         //    new childDocument { sku = a.item,description = "",instock = 0 }
                         //}
                         //childDocuments =  u.childDocuments
                         //childDocuments = (List<childDocument>)data
                         //childDocuments = new List<childDocument>()
                         //{
                         //    new childDocument()
                         //    {
                         //        //sku = x.item,
                         //        //description = "",
                         //        //instock = 0

                         //    }
                         //}
                         //childDocuments = (List<childDocument>)data
                         // childDocuments =            //array return
                     }
                    ;

    var alldocument = masterdocument.ToList();

    return alldocument;
}

Classes
public class masterDocument
{
    public double _id { get; set; }
    public string item { get; set; }
    public double price { get; set; }
    public double quantity { get; set; }
    public List<childDocument> childDocuments { get; set; }
}

public class childDocument
{
    public double _id { get; set; }
    public string sku { get; set; }
    public string description { get; set; }
    public int instock { get; set; }
}

Current output in Postman:
[
    {
        "_id": 1,
        "item": "almonds",
        "price": 12,
        "quantity": 2,
        "childDocuments": null
    },
    {
        "_id": 3,
        "item": "pecans",
        "price": 20,
        "quantity": 1,
        "childDocuments": null
    },
    {
        "_id": 4,
        "item": "rms",
        "price": 56,
        "quantity": 3,
        "childDocuments": null
    }
]

I am trying a join in c# but not properly working return data.
Please help.

A: Solution 1: With LINQ query
You need to .GroupBy MasterDocument._id as below:
var alldocument =
            (from a in _masterDocument.AsQueryable<masterDocument>()
            join u in _childDocument.AsQueryable<childDocument>() on a.item equals u.sku
            select new { master = a, child = u } into au
            group au by au.master._id into masterGroup
            select new masterDocument()
            {
                _id = masterGroup.Key,
                item = masterGroup.First().master.item,
                price = masterGroup.First().master.price,
                quantity = masterGroup.First().master.quantity,
                childDocuments = masterGroup.Select(x => x.child).ToList()
            })
            .ToList();

Solution 2: With BsonDocument (Export query from MongoDB Compass)
If you are unsure how to write the MongoDB query in C#, you can export your query to C# via MongoDB.
Pre-requisites
public class masterDocument
{
    ...

    [BsonElement("data")]
    public List<childDocument> childDocuments { get; set; }
}

PipelineDefinition<masterDocument, masterDocument> pipeline = new BsonDocument[]
{
    new BsonDocument("$lookup",
        new BsonDocument
        {
            { "from", "childDocument" },
            { "localField", "item" },
            { "foreignField", "sku" },
            { "as", "data" }
        })
};

var alldocument = _masterDocument
    .Aggregate(pipeline)
    .ToList();

Solution 3: With AggregateFluent
Pre-requisites
public class masterDocument
{
    ...

    [BsonElement("data")]
    public List<childDocument> childDocuments { get; set; }
}

var alldocument = _masterDocument
    .Aggregate()
    .Lookup<childDocument, masterDocument>(
        "childDocument",
        "item",
        "sku",
        "data")
    .ToList();

Result


text:
Q: Perl splitting array based on condition using grep I have some perl code that looks something like this:
my @array = map { rand } ( 1..100 );
my @matching = grep { $_ == $condition } @array;
@array = grep { $_ != $condition } @array;

This works ok, but what I would like to do is split the original array into two based on a single operation...I think I'm carrying out twice as many operations as strictly necessary.
Help appreciated!! Thanks.

A: By far the easiest method is to iterate your array and push values to either of the two arrays depending on the condition, as in the below example.
for (@array) {
  if ($_ % 2) {push @odd,  $_}
  else        {push @even, $_}
}

If you'd like to modify the source array:
for (my $i =0; $i < @array; ++$i) {
  if ($array[$i] % 2) {
    push @odd, splice (@array, $i--, 1);
  }
}

Why didn't you recommend List::MoreUtils::part?
The module in question might not exists on the target system, which is always an annoying thing.
Also on the system I ran tests on I found that List::MoreUtils::part was twice as slow as first snippet in this post, though with different implementations of part it might be the opposite actually.

A: I love the simplicity of List::MoreUtils' part function:
sub part (&@) {
    my ($code, @list) = @_;
    my @parts;
    push @{ $parts[ $code->($_) ] }, $_  foreach @list;
    return @parts;
}

The resulting @parts array is an array of arrayrefs. @$parts[0] is the array of elements that returned false. @$parts[1] returned true.

A: This is where part from List::MoreUtils comes in handy.
use List::MoreUtils qw'part';
my($even,$odd) = part { $_ % 2 } @array;

This works great if you want each element of input in exactly one array of the output.

If you want to possibly put them in more than one of the arrays, you have to loop over them yourself.
The best way to do that is with a foreach loop.
my(@div2,@div3);
for my $elem (@array){
  push @div2, $elem unless $elem % 2;
  push @div3, $elem unless $elem % 3;
}

If there are a lot of similar checks you have to do, perhaps you should loop on what your testing against as-well.
my %div;
for my $elem (@array){
  for my $div (2,3,5,7,11,13){
    push @{ $out{$div} }, $elem unless $elem % $div;
  }
}


text:
Q: Getting error 1064 while running query for table creation? I already have created customers and products table.I am getting this error while running following command in phpmyadmin.
CREATE TABLE orders (    id INT NOT NULL AUTO_INCREMENT,
    orderNumber INT,
    productId INT,
    customerId INT,
    orderDate DATETIME default CURRENT_TIMESTAMP,
    PRIMARY KEY(id),
    PRIMARY KEY (customerId) REFERENCES customers(id) ,
    FOREIGN KEY (productId) REFERENCES products(id)
                    );
1064 error

A: Can not create more than one primary keys.
Try this code.
CREATE TABLE orders (
id INT NOT NULL AUTO_INCREMENT,
orderNumber INT,
productId INT,
customerId INT,
orderDate DATETIME default CURRENT_TIMESTAMP,
PRIMARY KEY(id),
FOREIGN  KEY (customerId) REFERENCES customers(id) ,
FOREIGN KEY (productId) REFERENCES products(id));