text:
Q: Plot json file data points to react mapbox gl I'm trying to plot my json file data points in a react mapbox. But I don't know why I'm getting white screen as output and there's no error as well. Can someone help me out with this?
React app.js code
import * as React from 'react';
import Map, {Marker} from 'react-map-gl';
import markers from "./input_data.json";
import 'mapbox-gl/dist/mapbox-gl.css';

function App() {
  return (
    <Map
      initialViewState={{
        longitude: 133.7751,
        latitude: -27.2744,
        zoom: 3
      }}
      style={{width: "100vw", height: "100vh"}}
      mapStyle="mapbox://styles/iwahith/clbyt8h2h000h15n2xjctmrsf"
    >

      {markers.map(marker => (
        <Marker key={marker.index} longitude={marker.Lng} latitude={marker.Lat} color='red' />
      ))}

    </Map>
  );
}

export default App;

Please find the sample json below:
[
    {
        "Station_ID": 480,
        "Status": "Retired",
        "Lat": "-",
        "Lng": "-",
        "index": 0
    },
    {
        "Station_ID": 488,
        "Status": "Committed",
        "Lat": -35.0969482085,
        "Lng": 138.484060872,
        "index": 1
    },
    {
        "Station_ID": 488,
        "Status": "Committed",
        "Lat": -35.0969482085,
        "Lng": 138.484060872,
        "index": 2
    }
]

Extra information I would like to tell you index is the unique attribute in my json and I haven't given any mapbox access token, just having a doubt do I need to provide any mapbox access token. If yes where do I need to enter it. Thanks in advance


text:
Q: Rails has_one and accepts_nested_attributes_for I can't seem to get a has_one relationship with accepts_nested_attributes_for to work. This is my first foray into nested attributes, so it might be incorrect. Help!
Models:
class Case < ActiveRecord::Base
  has_one :logged_event, class_name: 'Event', dependent: :destroy
  accepts_nested_attributes_for :logged_event
end

class Event < ActiveRecord::Base
  belongs_to :case
  belongs_to :user
  validates :case, presence: true
  validates :user, presence: true
end

Controller:
class CasesController < ApplicationController
  load_and_authorize_resource

  def new
    @case.build_logged_event(user: current_user)
  end

  def create
    if @case.save
      flash[:notice] = 'Case was successfully logged.'
      redirect_to cases_path
    else
      render 'cases/new'
    end
  end
end

Form:

New Case

<%= error_messages_for :case %>
<%= form_for(@case) do |form| %>

    <%= form.label(:study) %>:
    <%= form.select(:study, Case.options_for(:study), include_blank: true) %>

  <%= form.fields_for(:logged_event) do |logged_event_form| %>
    <%= logged_event_form.label(:created_at, 'Date Case was opened:') %>
    <%= logged_event_form.select(:created_at, [['Today', Date.today], ['Yesterday', Date.yesterday]]) %>
  <% end %>
  <%= form.submit('Log Case') %> or <%= link_to('cancel', cases_path) %>
<% end %>

It's saying that the logged event is not getting a user id or a case id, so both validations on the event class are failing. It looks like:
There were problems with the following fields:
Logged event case can't be blank
Logged event user can't be blank
I don't get that, because in the new action I have already built the object. I also tried form.fields_for(:logged_event, @case.logged_event) but that didn't work either.

A: It's because new is not being called when you submit the form. Only the create action is being ran. So @case is populated only with the for submission data; no user or case is assigned to it since it's not in the form.
You'd need to assign the user and case properties of @case before trying to save (and running validations)

A: Turns out you shouldn't validate on both sides. I was validating that a case had an event and an event had a case. By removing the validates :case, presence: true like from event, everything worked as it should have.

A: You don't need to remove your validation -- you just need to add inverse_of to the association declaration to tell Rails to manage the back reference for you.
Your models should look like this:
class Case < ActiveRecord::Base
  has_one :logged_event, class_name: 'Event', dependent: :destroy, inverse_of: :case
  accepts_nested_attributes_for :logged_event
end

class Event < ActiveRecord::Base
  belongs_to :case, inverse_of: :logged_event
  belongs_to :user, inverse_of: :logged_event # or inverse_of: :event -- you didn't provide your User model
  validates :case, presence: true
  validates :user, presence: true
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I find out what a linux command does exactly? When I run something like python file.py, the system is (I think) executing some file with file.py as an argument. How do I find out exactly which file it is executing or at least the directory?
Is there a Linux command that let's you find the targets of other commands?

A:
Is there a Linux command that let's you find the targets of other commands?

Yes, it's called which in my machine when I run:
$ which python
$ /usr/bin/python

Normally in linux, unless you specify the current directory by the following:
./any_command

The bash (or the shell you are using) will look into the directories listed in your PATH environment variable trying to find a command with the given name.
The PATH is a list of directories separated by ":" character. Normally it has already some default locations where your shell will look for executables like /bin, /usr/bin, /usr/local/bin (the root user has different paths in his $PATH env variable).
If you have some location which you would like to add to your path you can do this by running the following:
export PATH=$PATH:/my_new_location

This way you can start running programs located in the my_new_location directory from anywhere without specifying the whole path to them. The order is important, if the same command appears in two different directories the command from the first directory in the list is used. Thus, if you would like to give precedence to your my_new_location you have to put it in the front of the PATH variable as in the following declaration:
export PATH=/my_new_location:$PATH

A: "What a command does" is not well defined and is an ambiguous sentence. All of them have side-effects (at the very least, burning CPU cycles is heating your processor).
I am assuming your command is not malicious or hostile, and your operating system is some Linux...
Very often, a command has some documentation. So for command foo try aproposfoo and manfoo and often foo--help (required by GNU coding standard) or else STFW. If the command is packaged in your distribution, it might have a separate documentation package (e.g. GCC is packaged as gcc-5, g++-5, gccgo-5 etc... on my Debian/Sid, but there is also a gcc-5-doc package etc... I recommend installing most documentation packages of the software you are using... and also manpages & manpages-dev &  manpages-posix & manpages-posix-dev on Debian related distributions).
Every process is doing some system calls (which is the most common way to do observable side effects, such as input & output). The possible Linux syscalls are listed in syscalls(2). You can find the sequence of the dynamically executed syscalls of a command or process with  strace(1) (some few "syscalls" like time(2) are often not true system calls done by the kernel, see vdso(7) for details).
Try for a simple example:
 strace pwd

and you'll see that it is doing about 70 system calls, notably on my Debian/PC:
getcwd("/home/basile", 4096)            = 13
fstat(1, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0)
                                        = 0x7f61aac5a000
write(1, "/home/basile\n", 13)          = 13

See also ltrace(1), which traces calls to functions inside shared libraries.
At last, most Linux commands are free software, so you can download and study their source code, and even improve it.
As others answered, your shell is searching an executable in your $PATH (which you could query with echo $PATH), and you could use whichfoo  and whereisfoo and typefoo  to find more about foo. Of course, shells have some builtin commands, such as cd (which makes the shell itself do a chdir(2) syscall, so there cannot be any ELF executable for the cd command, which has to be a builtin), and most shells enable you to define shell functions and aliases.
PS. Even for understanding malicious commands, strace can be very useful.


text:
Q: Zabbix: How do I configure a Trigger which will check if a specific value has been changed in the last 10 minutes? I've been given the task to monitor a specific value in some MySQL server database, I need to raise a notification if the value has not been changed in the last 10 minutes.
I've added to the UserParameter_mysql.conf the following line:
UserParameter=mysql.query, echo "select id from resolved_clicks order by id desc limit 1" | mysql -N -u zabbix -pPASSWORD aggregator

And when running a check from the Zabbix server, it returns the value correctly:
[root@zabbix ~]# zabbix_get -s IP -k mysql.query
7957178672
[root@zabbix ~]#

The next step was to create an Item which I've already done so and now I'm trying to configure the Trigger.
The trigger should arise a notification if the value has not been updated in the last 10 minutes.
How can I configure the trigger to reflect this condition? Thanks!
Edit #1:
Here's the Latest data from the trigger I've just created:

My questions are:
1. What's the meaning of change?
2. How can I know from looking on the Change row how many seconds
   have passed since the last 2 checks?
3. How can I test that the trigger is operating successfully without
   having to reproduce the problem?

A: Your question is not 100% clear, so I've covered both possibilities:

If you want to check whether data is not arriving from the Zabbix agent, use the nodata function.

Returns:
  1 - if no data received during period of time in seconds. The period should not be less than 30 seconds.
  0 - otherwise

For example, a trigger which will fire if no data was received for 10 minutes:
{mysql.query.nodata(600)}=1

If you want to check whether the value has not changed, use delta.

Returns the difference between the maximum and minimum values in a period ('max()' minus 'min()'). The period is set in seconds or as a number of collected values (preceded by a # hash mark) in the first parameter.

For example, a trigger which will fire if the value has not changed for 10 minutes:
{mysql.query.delta(600)}=0

Finally, you probably want to rename your item. mysql.query is very generic, and is already used by common MySQL templates. Something like aggregator.highest_click_id might be more appropriate.


text:
Q: Is logic within a factory method acceptable? Im in the process of creating a factory method which will be used to create a collection of Drupal Module's (objects).
In the creation of this collection through the factory method i want to ensure we're only adding modules to the collection that implement a specific hook. (In non Drupal terms this basically means a module [object] is of a certain type).
All of this filter logic is carried out in the factory method (which includes dependency injection principles) to return a collection of modules that implement the required hook.
I guess my question is.. is this an acceptable approach to take? Is it good practice to include this level of logic within a factory method etc etc.
The method in question: createFromModuleKeysImplementingHook
<?php

/**
 * Class ModuleCollectionFactory.
 *
 * Contains static factory methods that can be implemented to create
 * ModuleCollection objects.
 *
 * @package RuralStack\Common\Module
 */
final class ModuleCollectionFactory {

    /**
     * Create a ModuleCollection object from an array of Module keys.
     *
     * The following creation method will (for each passed Module key) create
     * a Module object which then added into the returned ModuleCollection
     * object.
     *
     * @param array $moduleKeys
     *     An array of Module keys to create the ModuleCollection object from.
     *
     * @return ModuleCollection The populate ModuleCollection object.
     */
    public static function createFromModuleKeys(array $moduleKeys){
        $moduleCollection = new ModuleCollection();
        foreach($moduleKeys as $moduleKey){
            $moduleCollection->add(Module::create($moduleKey));
        }
        return $moduleCollection;
    }

    /**
     * This is the method in question that implements the logic
     *
     * Is this good or bad practice?
     *
     * Is there a better way of doing this?
     *
     * @param array $moduleKeys
     * @param $hookName
     * @param HookInformationInterface $hookInformation
     *
     * @return ModuleCollection
     */
    public static function createFromModuleKeysImplementingHook(array $moduleKeys, $hookName, HookInformationInterface $hookInformation){

        /**
         * $moduleKeys = array('my_module', 'test_module', 'hook_module');
         *
         * $hookName = 'some_hook';
         *
         * $modulesInvokingHook = array('tm_dule, 'hook_module', 'my_module');
         *
         * array_intersect = array('hook_module', 'my_module');
         * ^^^Create the Module collection object from these
         */

        /**
         * Get all of the module keys that implement the hook (function) passed
         * to the factory method. Returns an array of module keys that matches
         * the format of the passed $moduleKeys argument.
         */
         $modulesInvokingHook = $hookInformation->getHookImplementations($hookName);

         $moduleCollection = new ModuleCollection();
         foreach(array_intersect($moduleKeys, $modulesInvokingHook) as $moduleKey){
            $moduleCollection->add(Module::create($moduleKey));
         }
         return $moduleCollection;
     }

}


text:
Q: How to draw shapes outside the big circle shape - netlogo I want to draw a large circle and outside to it 50 small ones
breed [largecircle lc]
breed [smallcircke sc]

ask patches with [(pxcor > min-pxcor) and
    (pxcor < (max-pxcor))]
    [ set pcolor blue]

;cteate turtle / draw circle/ and make the circle to be in a drawing area (patches)
create-largecircle 1 [
    set shape "circle"
    set color green
    setxy 0 0
    set size  10
    stamp
    die
  ]
create-smallcircle 50 [
    set shape "circle"
    setxy random-xcor random-ycor;randomize
    move-to one-of patches with [pcolor = blue ]
  ]

it doesn`t work.Circles are still generated inside large circle area
Any thoughts how can I approach the requirement?

A: Your approach doesn't work, because you are not modifying any pcolors of patches in the landscape. The stamp command only leaves an image of the largecircle turtle, but the pcolors underneath still remain blue. Thus, your smallcircles are still allowed to move anywhere even within the stamp area of your largecircle.
To solve this, you need a different approach. Turtle shapes in NetLogo are useful for generating visual output of your model. But it is not possible to identify patches which are covered by a certain turtle shape. Even though a turtles visual shape can cover several patches, its location is still limited to one specific patch.
It's hard to recommend an approach without knowing, what you are exactly planning to do with your model. However, here is a solution that comes close to your provided code example:
breed [smallcircle sc]
globals [largecircle]

to setup
ca
ask patches with [(pxcor > min-pxcor) and (pxcor < (max-pxcor))][
   set pcolor blue
]

;store patches within radius of center patch as global
ask patch 0 0 [
  set largecircle patches in-radius (10 / 2)
]
;set color of largecircle patches green
ask largecircle [
  set pcolor green
]
;create small circles and move to random location outside largecircle
create-smallcircle 50 [
    set shape "circle"
    move-to one-of patches with [not member? self largecircle]
]
end

I removed the largecircle breed and instead created a global variable largecircle.
The largecircle is then created by asking the center patch, identifying all patches within a certain radius and store these patches in the global variable largecircle. We can now use this patch-set to set the pcolor of largecircle-patches or to control the movement of the small circles.


text:
Q: I don't want to see all the graphs before selecting a dropdown button (python plotly) I created a dropdown menu with several graphs and everything is fine but when I start the program and have not yet selected one of the buttons, I see all the graphs and it just looks messy so I want to change this. In the default situation I would like to see only the graph that is connected to the first button. I tried to do this with the line "active = 0" but it only caused the first button to be highlighted.
Here is a snippet of my data (it shows the effect of the corona crisis on the sales index in the german manufacturing industry):
Chemicals;Mechanical engineering;Motor vehicles and motor vehicle parts;Dates
101.5;108.1;104.6;Jan-2019
101.2;105.8;105.9;Feb-2019
101;105.9;106.2;Mar-2019
101;105.6;101.2;Apr-2019
99.3;103.2;104.5;Mai-2019
99.4;103;101.9;Jun-2019
99.2;104;99.5;Jul-2019
99.4;103;102.2;Aug-2019
97.1;102.7;102.2;Sept-2019
99.7;100.6;100.9;Okt-2019
99.1;101.8;100.4;Nov-2019
98.7;99.7;101.6;Dez-2019
99.2;102.4;100.1;Jan-2020
101.5;100.1;99.8;Feb-2020
99.2;91.5;72.7;Mar-2020
90;73.9;24.8;Apr-2020

And here is a simple version of my program:
import plotly.graph_objects as go
import numpy as np
import pandas as pd

df = pd.read_csv("sales_index_manufacturing.csv", delimiter = ";")

fig = go.Figure()

fig.add_trace(
    go.Scatter(x=list(df['Dates']),
               y=list(df['Chemicals']),
               name="Chemicals",
               line=dict(color="#008b8b"))
)

fig.add_trace(
    go.Scatter(x=list(df['Dates']),
               y=list(df['Mechanical engineering']),
               name='Mechanical engineering',
               line=dict(color="#8b008b"))
)

fig.add_trace(
    go.Scatter(x=list(df['Dates']),
               y=list(df['Motor vehicles and motor vehicle parts']),
               name='Motor vehicles and motor vehicle parts',
               line=dict(color="#ffa500"))
)

fig.update_layout(
    updatemenus=[
        dict(
            active= 0,
            buttons=list([
                dict(label='Chemicals',
                     method="update",
                     args=[{"visible": [True,False,False]},
                           {"title": "Chemicals",
                            "annotations": [],
                           'yaxis': {'title': 'sales index (2015 = 100)'}}]),
                dict(label='Mechanical engineering',
                     method="update",
                     args=[{"visible": [False,True,False]},
                           {"title": 'Mechanical engineering',
                            "annotations": [],
                           'yaxis': {'title': 'sales index (2015 = 100'}}]),
                dict(label='Motor vehicles and motor vehicle parts',
                     method="update",
                     args=[{"visible": [False,False,True]},
                           {"title": "Motor vehicles and motor vehicle parts",
                            "annotations": [],
                           'yaxis': {'title': 'sales index (2015 = 100)'}}]
                    )]
            ),
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x=-0.04,
            xanchor="left",
            y=1.132,
            yanchor="top",
        )
    ])

fig.update_layout(
    legend=dict(x= 0.75,
                y=1.1,
                bgcolor='rgba(255, 255, 255, 0)',
                bordercolor='rgba(255, 255, 255, 0)'),
    width=1000,
    height=600,
    autosize=False,
    template="plotly_white",
)

fig.show()

When you run the code, you're probably wondering what I mean by "messy," but the original program contains a lot more graphs and data, and it really looks like a mess in the default situation.
Thanks in advance for your help!


text:
Q: Stuck at the string number part.. when I enter a string the code returns an error as the input function has been casted as an integer Question: Create an if-else conditional statement where a user inputs a number and outputs positive, negative, zero or string number.
num = input("Input: ")
if num > 0:
   print("Output: Positive")
elif num < 0:
    print("Output: Negative")
elif num == 0:
    print("Output: Zero")
else:
    print("Output: String Number")

A: Try using this:
num = int(input("Enter Number: "))
This will ensure that the number the user inputs is an int.
It'll raise an error if the number is a decimal or isn't a number at all.
You can use try and except to catch the error if the string is not a number.

A: Use try except
try:
    num = int(input("input: "))

    if num > 0:
        print("Output: Positive")
    elif num < 0:
        print("Output: Negative")
    elif num == 0:
        print("Output: Zero")
except:
    print("Output: String Number")


text:
Q: Marcus Number Fields chapter 5 exercise 8 The exercise is the following: one should show that $R=\mathbb{Z}[\sqrt{223}]$ has ideal class group which is a cyclic group of order $3$.
I tried to follow the standard path which Marcus uses to determine other ideal class groups: firstly, I calculated $\lambda$ which turns out to be $\sqrt{223}$. Having that, one reduces to check what happens to prime in $R$ which are above $2,3,5,7,11,13$.
I've checked that the prime above $2,5,7,11,13$ are trivial in the ideal class group and using Kummer theorem I've found that $$3R=(3,1+\sqrt{223})(3,1-\sqrt{223}) .$$
Let's call this two primes respectively $p,q$. One can check that $14-\sqrt{223} \in p $ and $14-\sqrt{223} \not \in q$, while the nrm of this element is $-27$, so that one got $p^3=(14-\sqrt{223})=e$ in the ideal class group. With a similar reasoning, one got $q^3=e$ in the ideal class group.
Now, if we manage to demonstrate that $p,q$ are not principal we are done. If one of this ideal were principal, the element which generates it should have norm $\pm 3$. So , we are reduced to show the following :there are no solutions in $\mathbb{Z}$ of $a^2-223b^2=\pm3$.
The one with the $+$ is showed to be impossible using reciprocity, while I've got no idea to end for the other equation.


text:
Q: why my sql query drops the title of column in associative array? i have two tables: users and scripts.user hasthe column user_id and scripts has two :script_id and cron_formtat. when i query for the users:
$query = "select `user_id` from users";
$result = mysql_query($query) or die(mysql_error());

while ( $row = mysql_fetch_assoc($result)){
    array_push($usersArr,$row);
}

result:
[{"user_id":"1"},{"user_id":"2"},{"user_id":"3"},{"user_id":"4"},{"user_id":"5"}]

i get associative array (with the title of the column) as i need, but why does my second query returns array with all values but drops the titles of the columns?:
$query = "select script_id,`cron_format`  from scripts";
$result = mysql_query($query) or die (mysql_error());

while($script = mysql_fetch_assoc($result)){
    foreach($usersArr as $user){
        $userScriptCronArr[$user["user_id"]][$script["script_id"]] = $script["cron_format"];
    }
}

result:
{"1":{"1":"*\/3 * * * *","2":"*\/6 * * * *","3":"*\/3 * * * *","4":"* * * * *"},"2":{"1":"*\/3 * * * *","2":"*\/6 * * * *","3":"*\/3 * * * *","4":"* * * * *"},"3" ...

in second result the first number is user_id, and for each user im assign's each of the existing scripts.
why does my second query drops the user_id,script_id and cron_format titles?

A: Nothing wrong here. You get your associative array.. It's $script
while($script = mysql_fetch_assoc($result)){
    foreach($usersArr as $user){
       $userScriptCronArr[$user["user_id"]][$script["script_id"]] =    $script["cron_format"];
   }
  }

So there is nothing wrong with your query. $userScriptCronArr is constructed as a multidimensional array with two numeric keys.

Regarding the angular part:
while($script = mysql_fetch_assoc($result)){
    foreach($usersArr as $user){
       $userScriptCronArr[] = array(
           "user_id" => $user["user_id"],
           "script_id" => $script["script_id"],
           "cron_format" => $script["cron_format"]
       );
   }
}

This should yield you an JSON array you can use with your angular code. But please, read the manuals!

A: In the first output you are pushing the entire query result as it is. But in the second you are not pushing the entire result but initiating the $userScriptCronArr in a numeric array. The data you want is still in the $script. You just have to initialize it properly and you are done.


text:
Q: URLDownloadToFile cannot update progress properly? I try to use URLDownloadToFile to download a large file in Delphi XE3. I want it to show the download progress.
Below is my code
unit MainFrm;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, WUpdate, Vcl.StdCtrls, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, IdHTTP, UrlMon, ActiveX,
  Vcl.ComCtrls;

const
     S_ABORT = HRESULT($80004004);

type
     TDownLoadMonitor = class( TInterfacedObject, IBindStatusCallback)
     private
      FProgressBar: TProgressBar;
         FShouldAbort: Boolean;
     protected
        function OnStartBinding( dwReserved: DWORD; pib: IBinding ): HResult; stdcall;
        function GetPriority( out nPriority ): HResult; stdcall;
        function OnLowResource( reserved: DWORD ): HResult; stdcall;
        function OnProgress( ulProgress, ulProgressMax, ulStatusCode: ULONG;
             szStatusText: LPCWSTR): HResult; stdcall;
        function OnStopBinding( hresult: HResult; szError: LPCWSTR ): HResult; stdcall;
        function GetBindInfo( out grfBINDF: DWORD; var bindinfo: TBindInfo ): HResult; stdcall;
        function OnDataAvailable( grfBSCF: DWORD; dwSize: DWORD; formatetc: PFormatEtc;
             stgmed: PStgMedium ): HResult; stdcall;
        function OnObjectAvailable( const iid: TGUID; punk: IUnknown ): HResult; stdcall;
     public
         constructor Create(ProgressBar: TProgressBar);
         property ShouldAbort: Boolean read FShouldAbort write FShouldAbort;
    end;

  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    ProgressBar1: TProgressBar;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);private
    FMonitor: TDownloadMonitor;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

Uses ShellAPI, System.IniFiles;

procedure TForm1.Button2Click(Sender: TObject);
begin
  URLDownloadToFile(nil, 'https://www.datanumen.com/dwg-recovery/ddwgr.exe', PChar('E:\Temp\ddwgr.exe'), 0, FMonitor as IBindStatusCallback);

end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FMonitor := TDownloadMonitor.Create(ProgressBar1);
end;

constructor TDownLoadMonitor.Create(ProgressBar: TProgressBar);
begin
     inherited Create;
     FProgressBar := ProgressBar;
     FShouldAbort:=False;
end;

function TDownLoadMonitor.GetBindInfo( out grfBINDF: DWORD; var bindinfo: TBindInfo ): HResult;
begin
     result := S_OK;
end;

function TDownLoadMonitor.GetPriority( out nPriority ): HResult;
begin
     Result := S_OK;
end;

function TDownLoadMonitor.OnDataAvailable( grfBSCF, dwSize: DWORD; formatetc: PFormatEtc; stgmed: PStgMedium ): HResult;
begin
     Result := S_OK;
end;

function TDownLoadMonitor.OnLowResource( reserved: DWORD ): HResult;
begin
     Result := S_OK;
end;

function TDownLoadMonitor.OnObjectAvailable( const iid: TGUID; punk: IInterface ): HResult;
begin
     Result := S_OK;
end;

function TDownLoadMonitor.OnProgress( ulProgress, ulProgressMax, ulStatusCode: ULONG; szStatusText: LPCWSTR ): HResult;
begin
    if Assigned(FProgressBar) then
    begin
      if ulStatusCode = BINDSTATUS_BEGINDOWNLOADDATA then
      begin
        FProgressBar.Min := 0;
        FProgressBar.Max := ulProgressMax;
      end
      else if ulStatusCode = BINDSTATUS_DOWNLOADINGDATA then
        FProgressBar.Position := ulProgress;
    end;

    if FShouldAbort then
         Result := E_ABORT
    else
         Result := S_OK;
end;

function TDownLoadMonitor.OnStartBinding( dwReserved: DWORD; pib: IBinding ): HResult;
begin
     Result := S_OK;
end;

function TDownLoadMonitor.OnStopBinding( hresult: HResult; szError: LPCWSTR ): HResult;
begin
     Result := S_OK;
end;

end.

The problem is that the progress bar is displayed incorrectly. I try to debug TDownLoadMonitor.OnProgress and find ulProgress is always the same value as ulProgressMax, they change from small values, such as 0,0 to 95374,95374 then 347227,347227 and increase gradually, but always the same value, so the progress bar is always about 100%.
Why does it not show the actual download progress properly?


text:
Q: Big O has a correct representation? Let's say I have two function that run, respectively, in O(n) and O(m).
For representational purposes, is it wrong to represent it as O(n)+O(m) instead of O(n+m)?
I was doing a test in which the representation O(n) + O(m) was marked wrong

A: These two notations do not mean the same thing.
O(m) means the set of all functions which asymptotically do not grow faster than m. So strictly speaking, O(m) + O(n) is not proper notation because these are two sets, not two functions; you cannot add sets together like this. However, we might informally write this to mean "the sum of some function in O(m) and some function in O(n)", or the set of all such sums, if the reader will know from context that that is what it's supposed to mean.
Clearly, every sum of two functions from O(m) and O(n) respectively is a member of O(m + n). So the question is then whether the converse holds: is it true that every function in O(m + n) can be written as a sum of two functions in O(m) and O(n) respectively? I don't know off the top of my head, but if you consider the function max(m, n), it doesn't seem like it could ever equal the sum of any two functions from O(m) and O(n) respectively. (Note that it's not enough to find two functions whose sum is an upper bound for max(m, n); it has to equal max(m, n) since otherwise max(m, n) is not a member of the set of all such sums.) So if you claim that these two sets, which are defined differently, actually are equal, then the onus is on you to offer a proof.
Now, it may be the case that in your test, the question did concern a function which could be represented as some function in O(m) plus some function in O(n); I don't know, since we haven't seen the test question. But even so, as mentioned earlier, "O(m) + O(n)" is not proper notation and it would normally only be written informally, so for that reason alone your answer might have been marked incorrect.


text:
Q: import a dump file mysql ubuntu I installed mysql server on my machine running ubuntu then after installation I did the following:

*

*mysql -u root -p   to get mysql prompt
2.create database prediction ;

*create user adam;

*set password for adam = password("12211");

*grant all privileges on prediction.* to adam identified by '12211';

*use prediction;

*-u adam -p prediction

I get the error :
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-u khalil -p prediction

A: Your error message doesn't correspond to your #6 entry (adam v.s. khalil). In any case, you cannot simply enter -u whatever into the mysql command line. Those are command line options, not sql commands/queries. You'd need to EXIT mysql first, then re-enter
$ mysql -u adam -p prediction

at the shell prompt


text:
Q: TabLayout inside Toolbar I want to achieve a certain look with the new Design Support Library and I can't stop seeing a weird bug.
Here's the screencast with the desired output (not done with DSL)
And the ouput I get using DSL.
The toolbar+tabs is in an activity with a viewpager, and the recyclerView is inside a fragment within the viewpager (the adapter actually, but you get my point)
Code for the activity :
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_main"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:elevation="4dp"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways">

            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorColor="@color/white"
                app:tabTextColor="@color/selected_text"
                app:tabSelectedTextColor="@color/white"/>

        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/main_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <android.support.design.widget.SupportFloatingActionsMenu
           ...>
           /* Code for a fancy fab w/ menu */

    </android.support.design.widget.SupportFloatingActionsMenu>

</android.support.design.widget.CoordinatorLayout>

For the fragment containing the recyclerView :
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.insa.burnd.view.MainActivity.NewsfeedFragment"
    android:id="@+id/fragment_newsfeed">

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </android.support.v4.widget.SwipeRefreshLayout>

</android.support.design.widget.CoordinatorLayout>

The java code is pretty standard, I bing the viewpager to the tabs... etc.
Thank you in advance for your help :) !

A: This and many other bug fixes were fixed in version 22.2.1 of the Design Library. Please make sure your build.gradle file references the newest version.


text:
Q: Creating a chromakey animated-gif playing for streaming overlay You know soundboards? Hit a button, play a sound? I don't see why that can't be developed for animated gifs.
All the parts are lying around, but I'm not a coder. Scratch that: I've been known to cobble together functional HTML together with the right Lynda training. I'm surely willing to learn what is needed, but that's where I must turn to you. Because I need one or two of you code-fu programmer-types to point me in the right direction.
Here is how I've been picturing it:
HTML Page A is just a collection of links. Each of those links opens in a named HTML Page B, which would be where all other links would send to as well. Page B would have a chromakey background color of your choosing. Each animated gif would need only be played once rather than looped.
A more feature-rich version of this is what Streamlabs already does - Twitch notifications.
What is killing me, and the reason why I haven't posted, like, a week ago, is because every time I sit down to post to these forums, I shake my head and say "there's no way this thing doesn't exist already" and go back to searching.
Anyway, any pointy-actions are much appreciated and thanks for taking the time to read this.


text:
Q: Travis-CI: deploy different branches to different servers Currently I'm trying to setup a concept project for Continuous Integration using a github repo in combination with Travis-CI.
My.travis.yml looks like this
language: java
jdk:
- oraclejdk8
before_cache:
- rm -f  $HOME/.gradle/caches/modules-2/modules-2.lock
- rm -fr $HOME/.gradle/caches/*/plugin-resolution/
cache:
directories:
- "$HOME/.gradle/caches/"
- "$HOME/.gradle/wrapper/"
branches:
 only:
 - master
 - develop

deploy:
 provider: cloudfoundry
 api: https://api.eu-gb.bluemix.net
 username: j.cuppen@acuity.nl
 password:
  secure: [key]
 organization: 'Acuity\ Stagiairs'
 space: 'stage\ job'
 on:
  repo: JasonLighthunter/GradleTest
  branch: develop

and my manifest.yml looks like this:
---
applications:
- name: gradleweb
  memory: 512M
  host: gradleTest
  path: build/libs/GradleTest.war

Currently when i push to develop it builds and deploys to gradleTest.eu-gb.mybluemix.net
What im trying to figure out is how I can configure travis in such a way that when the master is pushed it is deployed to, let's say: gradleProd.eu-gb.mybluemix.net
Thanks in advance

A: You can specify manifest file for each deploy. Change your .travis.yml to:
deploy:
  - provider: cloudfoundry
    edge: true
    username: ${CF_USERNAME}
    password: ${CF_PASSWORD}
    organization: ${CF_ORGANIZATION}
    space: ${CF_SPACE}
    api: https://api.ng.bluemix.net/
    manifest: manifest.master.yml
    on:
      branch: master
  - provider: cloudfoundry
    edge: true
    username: ${CF_USERNAME}
    password: ${CF_PASSWORD}
    organization: ${CF_ORGANIZATION}
    space: ${CF_SPACE}
    api: https://api.ng.bluemix.net/
    manifest: manifest.develop.yml
    on:
      branch: develop

in this case you can add two files: manifest.develop.yml and manifest.master.yml


text:
Q: Extension, get value of TCA select I created a new extension with the extension_builder and added a select-field:
'selectlist' => array(
    'exclude' => 1,
    'label' => 'LLL:EXT:my_test/Resources/Private/Language/locallang_db.xlf:tx_mytest_domain_model_test.selectlist',
    'config' => array(
        'type' => 'select',
        'renderType' => 'selectSingle',
        'items' => array(
            array('LLL:EXT:my_test/Resources/Private/Language/locallang.xlf:tx_mytest_domain_model_test.selectlist.item1', 0),
            array('LLL:EXT:my_test/Resources/Private/Language/locallang.xlf:tx_mytest_domain_model_test.selectlist.item2', 1),
        ),
        'size' => 1,
        'maxitems' => 1,
        'eval' => ''
    ),
),

In the template I access this field with:
<f:link.action action="show" arguments="{test : test}"> {test.selectlist}</f:link.action>

The problem is that test.selectlist is only the key of the select-item. But what I need is the value (in my case the translated value from locallang.xlf).
I have not found any documentation about how to access the value in the template.
Is it possible? How can I do it?

A: In my case I can use a work around.
array('LLL:EXT:my_test/Resources/Private/Language/locallang.xlf:tx_mytest_domain_model_test.selectlist.item1', 1),
array('LLL:EXT:my_test/Resources/Private/Language/locallang.xlf:tx_mytest_domain_model_test.selectlist.item2', 2),

and
<f:translate key="tx_joyatest_domain_model_test.selectlist.item{test.selectlist}" />

this works, cause the translation key can be identified by the select-item-key.

A: Try biesior's answer for "TYPO3 TCA type select in FLUID?". That technique may be helpful to you, or give you an idea.


text:
Q: What is the best way to do TDD/BDD for ember.js? Found one approach with Jasmine: Ember.js TDD – how to test your ember views
Has anyone used this approach? Are there any other/better ways of doing TDD/BDD for Ember?


text:
Q: Android M app update and Permission for a Sync Adapter I have an app using a AbstractThreadedSyncAdapter for syncing a calendar.
We are working on a build for android M. I have the calendar permission requests working in all cases except where the user already has the syncing setup and then upgrades our app from a non android M build to the new M build.
A] I can check the permission the first time the user opens the app after he upgraded it, but he may not open the app for a few weeks, during which his calendar will not sync.
B] I am heading toward the following option: The background sync service would start an activity that displays an explanation why we now need calendar permission because of the upgrade to M.
My question is:
Is B] the best option ?

A:
Is B] the best option ?

IMHO, no. Raise a Notification, alerting the user of the need to grant the permission. When the user taps on the Notification, then go through requestPermissions() and ask the user for the permissions that you need. If the user ignores the Notification, remind them periodically (e.g., once a day) with a fresh Notification.
This achieves your objective of alerting the user to the problem without interfering with whatever they happen to be doing at the time you decide that you need this permission.


text:
Q: Ruby: toggle a boolean inline? How can I get the opposite of a boolean in Ruby (I know that it is converted to 0/1) using a method inline?
say I have the given instance:
class Vote

  def return_opposite
    self.value
  end

end

Which obviously doesn't do anything, but I can't seem to find a method that is simple and short something like opposite() or the like. Does something like this exist and I'm just not looking at the right place in the docs? If one doesn't exist is there a really short ternary that would toggle it from 1 => 0 or 0 => 1?

A: You can use XOR operator (exclusive or)
a = true
a # => true
a ^= true
a # => false
a ^= true
a # => true

A: Edit: See comment by @philomory below.

I believe this is basically an oversight in the boolean classes (TrueClass and FalseClass) in Ruby.
You can negate any object:
nil.! => true
false.! => true
true.! => false
0.! => false
1.! => false
a.! => false (all other objects)

But you cannot in-place negate the boolean objects:
a.!! => does not compile

I guess this would call for trouble with the compiler's grammar.
The best you can do, is thus:
a = a.!

A: If you just want to access the opposite of the value, use ! as some people have said in the comments. If you want to actually change the value, that would be bool_value = !bool_value. Unless I've misunderstood your question. Which is quite possible.

A: I like to use this
@object.boolean = !@object.boolean

A: Boolean expressions are not 0 or 1 in Ruby, actually, 0 is not false
If n is numeric we are swapping 0 and 1...
n == 0 ? 1 : 0 # or...
1 - n          # or...
[1, 0][n]      # or maybe [1, 0][n & 1] # or...
class Integer; def oh_1; self==0 ? 1:0; end; end; p [12.oh_1, 0.oh_1, 1.oh_1] # or...
n.succ % 2     # or...
n ^= 1

If b already makes sense as a Ruby true or false conditional, it's going to be hard to beat:
!b

These examples differ in how they treat out-of-range input...

A: In order to toggle a boolean data in rails you can do this vote.toggle!(:boolean)

A: If you want to toggle boolean (that is false and true) , that would be as simple as just use ! as others has stated.
If you want to toggle between 0 and 1 , I can only think of something naive as below :)
def opposite
     op = {0=>1,1=>0}
     op[self.value]
end

A: In a Rails app, I use this method to toggle a post between paused and active, so ! (not) is my preferred method.
def toggle
  @post = Post.find(params[:id])

  @post.update_attributes paused: !@post.paused?

  msg = @post.paused? ? 'The post is now paused.' : 'The post is now active.'

  redirect_to :back, notice: msg
end

A: I think that using a ternary can be interesting :
check = false
check == true ? check = false : check = true


text:
Q: Block Completion no longer works after update to Windows 10 I recently updated to Windows 10. Since doing that, RAD no longer automatically completes blocks for me. If I type an open bracket then press enter, it used to indent the next line and put a closing bracket on the line after that.
Here is what my settings look like:

Is there a way to re-enable this feature?


text:
Q: Valid way to get HibernateGridDataSource sorted by specified columns The common usage of HibernateGridDataSource for showing table contents on page is just simple method:
public GridDataSource getList() {
    return new HibernateGridDataSource(session, Foo.class);
}

I wonder, what is the valid and beauty way to get this data source presorted by specified columns? For example, let's it would be field date of Foo class.

A: Well, I found the decision for my self. Any others more convenient methods will be also appreciated.
    return new HibernateGridDataSource(session, Foo.class) {
        @Override
        protected void applyAdditionalConstraints(Criteria crit) {
            crit.addOrder(Order.desc("date"));
        }
    };


text:
Q: How does android handle the +-sign in a phonenumber I'm trying to call a calling card through code and want to send the following uri to the intent:
accessnumber+pause+phonenumber+#
The phonenumber comes from the addresslist, but how do I handle the + (as in exit code), because it's for example in the States 011, in Europe 00. And I guess I can't just send it to the intent. Is there a way to handle this?
Problem is that the calling card wants the plus as a 00 or a 011 for example.
String uri = "tel:" + Uri.encode(phonenumber)

try {
                Intent intentCall = new Intent(Intent.ACTION_CALL);
                intentCall.setData(Uri.parse(uri));
                startActivity(intentCall);
                } catch (ActivityNotFoundException e)        { }

A: Android is documented to use rfc3966 compatible telephone uris.  RFC3966 specifies that the '+' character is used for international dialling, so Android should recognize the '+' character and deal with it appropriately.


text:
Q: PUT request access blocked I have been trying to update values in a certain table with a PUT request. However, I keep getting those errors and I am not sure why:
OPTIONS http://localhost:8080/api/ping/1001 404 (Not Found)

and
Access to XMLHttpRequest at 'http://localhost:8080/api/ping/1001' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Whenever I switch the request to a GET request it works.
My backend
 embeddedServer(Netty, 8080) {

       routing {
            get("/api/ping/{num?}"){
                var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
                var stmt: Statement? = null
                var resultset: ResultSet? = null
                val obj = arrayListOf<SRTEntry>()
                        .....
                        .....
                val gson = Gson()
                var str = gson.toJson(obj)
                call.response.header("Access-Control-Allow-Origin", "*")
                call.respondText(str, ContentType.Application.Json)
            }
            put("/api/ping/{num?}"){
                var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
                var stmt: PreparedStatement? = null
                var resultset: ResultSet? = null
                val obj = arrayListOf<SRTEntry>()
                        .....
                        .....
                val gson = Gson()
                var str = gson.toJson(obj)
                call.response.header("Access-Control-Allow-Origin", "*")
                call.respondText(str, ContentType.Application.Json)
            }

Frontend that calls PUT request
var url = "http://localhost:8080/api/ping/1001";
var req = new XMLHttpRequest();
req.onload = function(event){
    if (parseInt(req.status, 10) != 200) {
        return;
    }
    var text = req.responseText;
    console.log(text);
}
req.open("PUT", url, true);
req.send();

Call to GET request:
var url = "http://localhost:8080/api/ping/1001";
var req = new XMLHttpRequest();
req.onload = function(event){
    if (parseInt(req.status, 10) != 200) {
        return;
    }
    var text = req.responseText;
    console.log(text);
}
req.open("GET", url, true);
req.send();

Thanks in advance for your help!

A: Adding
install(CORS){
            method(HttpMethod.Put)
            anyHost()
        }

Before routing fixed it for me as shown below:
install(CORS){
    method(HttpMethod.Put)
    anyHost()
}
routing {
   get("/api/ping/{num?}"){
   var nsq_num: Int = Integer.valueOf(call.parameters["num"]?: "1001")
   var stmt: Statement? = null
   var resultset: ResultSet? = null
   ...

You can get more information about it from https://dev.to/effingkay/cors-preflighted-requests--options-method-3024


text:
Q: Is deserialization synchronized in Java? In this example class, could I be sure that getTransientObject() never returns null (assuming the field is not assigned null) in a multithreaded environment or should I mark the field as volatile?
public class MySerializable implements Serializable {

    private static final long serialVersionUID = 5697687207743287388L;

    private transient TransientObject transientObject;

    public MySerializable(TransientObject transientObject) {
        this.transientObject = transientObject;
    }

    public TransientObject getTransientObject() {
        return transientObject;
    }

    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        out.writeUTF(transientObject.getId());
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        this.transientObject = retrieveTransientObject(in.readUTF());
    }

    private static TransientObject retrieveTransientObject(String id) {
        // ...
    }

}


text:
Q: Should I correct for bias and set a delta degree of freedom when dealing with a finite data set? I'm analysing data from a suite of tests. The tests are effectively sanity/pass-off checks for control SW which is being developed: each test follows the same procedure and I don't expect great variation in the results. Some variability will be there as the testing is performed on a real-world system which is effected by environmental conditions.
My reasoning is that I don't need to correct for bias or delta degree of freedom for variability as I am dealing with an entire population of results to get an idea of what is an acceptable variation in values and what should be considered an outlier. I may be wrong though as statistical analysis is not a field I have had great experience in.
Going forward I intend to compare future test results to the ones I am using here as a "baseline".


text:
Q: Why is SDL_RenderCopy so long? I'm creating a game with SDL2 in C and I have a problem, I'm actually doing the main menu of my game: I have 3 buttons on my menu and I want them to go red when I put my mouse over them, so what I did is I pre-loaded 4 SDL_Textures for my entire screen: one with all buttons not colored and the 3 others are the same main menu with each button highlighted in red, I thought it would be faster than changing the button color and recreating the texture each time, but when I put my mouse over the buttons they are passing red really slow, I'm just using SDL_RenderCopy and SDL_RenderPresent each time the screen is updated so it shouldn't be that long. Here's my function code and a picture of my program to understand better. (sorry for the bad english btw)

typedef struct          s_sdlVar
{
    SDL_Window          *window;
    SDL_Renderer        *renderer;
    SDL_Event           event;
    SDL_Texture         *mainMenu[MAIN_MENU_TEXTURE_COUNT];
    t_rect              mainMenuButtonRect[MAIN_MENU_OPTION_COUNT];
    t_res               screenResolution;
    int                 boxSiz;
    t_byte              difficulty;
}                       t_sdlVar;

static int  checkButtonPos(t_rect *buttonPos, int x, int y)
{
    for (int i = 0; i < MAIN_MENU_OPTION_COUNT; i++)
        if ((x >= buttonPos[i].x) && (x < buttonPos[i].x + buttonPos[i].w)
        && (y >= buttonPos[i].y) && (y < buttonPos[i].y + buttonPos[i].h))
            return (i + 1);
    return (0);
}

int         displayMainMenu(t_sdlVar *sdl)
{
    t_bool  exit = false;
    t_bool  isButtonOn = false;
    int     textureIndex = 0, buttonIndex = 0;

    if (SDL_RenderCopy(sdl->renderer, sdl->mainMenu[0], NULL, NULL))
        return (-1);
    SDL_RenderPresent(sdl->renderer);
    while (!exit)
        if (SDL_PollEvent(&sdl->event))
        {
            if (sdl->event.type == SDL_MOUSEMOTION)
            {
                if ((textureIndex = checkButtonPos(sdl->mainMenuButtonRect, sdl->event.motion.x, sdl->event.motion.y)))
                {
                    if (SDL_RenderCopy(sdl->renderer, sdl->mainMenu[textureIndex], NULL, NULL))
                        return (-1);
                    SDL_RenderPresent(sdl->renderer);
                    isButtonOn = true;
                }
                else if (isButtonOn)
                {
                    if (SDL_RenderCopy(sdl->renderer, sdl->mainMenu[0], NULL, NULL))
                        return (-1);
                    SDL_RenderPresent(sdl->renderer);
                    isButtonOn = false;
                }
            }
            else if ((sdl->event.type == SDL_QUIT) || ((sdl->event.type == SDL_MOUSEBUTTONDOWN) && isButtonOn && (textureIndex == 2)))
                exit = true;
        }
    return (buttonIndex);
}


text:
Q: How to get the value of the checkbox in a table and the id of the object in the row of the current checked checkbox? I am currently working in Asp.net MVC in Visual Studio 2017. I am new to working with Asp.net MVC and can not get the values i am needing.
I have a table of questions that are all displayed in a table on my view page. Each one of the questions have a Boolean value that shows as check boxes when they are being displayed. I am currently trying to write a script to get the checkbox value of true or false and where that checkbox is checked I am trying to get the Id of the question in the current row.
This is my view where I am displaying the questions.
@model IEnumerable<CapstoneApplication.Models.Question>

@{
ViewBag.Title = "Index";
}

Questions: Admin View

@Html.ActionLink("Create Question", "Create")

        @Html.DisplayNameFor(model => model.IsPartOfGame)

        @Html.DisplayNameFor(model => model.Category.CategoryName)

        @Html.DisplayNameFor(model => model.QuestionDescription)

@foreach (var item in Model) {

            @Html.CheckBoxFor(modelItem=>item.IsPartOfGame, new {onclick = "SaveCheckBox(this)" })

            @Html.DisplayFor(modelItem => item.Category.CategoryName)

            @Html.DisplayFor(modelItem => item.QuestionDescription)

            @Html.ActionLink("Edit", "Edit", new {id = item.Id}) |
            @Html.ActionLink("Delete", "Delete", new {id = item.Id})

    }

This is the script I am currently using.
function SaveCheckBox(checkboxInput) {
$.ajax({
    type: 'GET',
    url: 'Index',
    data: {idValue: checkboxInput.closest("tr").getAttribute("id"),
    newValue: checkboxInput.checked },
    dataType: 'json'

     });
}

Finally this is the method the script calls to give the values to.
 public ActionResult Index(bool? newValue, int? idValue)
    {
        //save to database here
        var questions = db.Questions.Include(q => q.Category);
        return View(questions.ToList());
    }

The problem I am having is that newValue always returns the correct value of being either true or false but idValue is always null it never grabs the id of the question in the row of the checkbox that was checked.

A: I would place the id as the data attribute in your CheckboxFor
    @Html.CheckBoxFor(
       modelItem=>item.IsPartOfGame
     , new {onclick = "SaveCheckBox(this)", data_itemid = item.Id}
   })

Then I would use this for your javascript
function SaveCheckBox(checkboxInput) {
$.ajax({
    type: 'GET',
    url: 'Index',
    data: {
       idValue: checkboxInput.dataset.itemid
     , newValue: checkboxInput.checked
    },
    dataType: 'json'
});
}


text:
Q: Oracle SQL how to eliminate duplicated row by specific column for example I have values like below in one table
 Table A
 ----------------
 item_name price departure
 ----------------
 shoe      10    150
 shoe      10    150
 socks     2     100
 socks     2     110
 shirt     5     170
 shirt     5     170
 gloves    1     210
 gloves    1     210
 gloves    1     210

I would like to select all rows with unique item_name so the simple method is using UNION
select item_name, price, departure from table A
UNION
select item_name, price, departure from table A

but like you see socks have diffrent departure and my result is wrong because I got result
 Table A
 ----------------
 item_name price departure
 ----------------
 shoe      10    150
 socks     2     100
 socks     2     110
 shirt     5     170
 gloves    1     210

Can you help me, I looking simple method something without left join because the table A contains a lot of data and I want to optimize
i want to get result like below where socks have smallest department in same (item_name and price)
Table A
 ----------------
 item_name price departure
 ----------------
 shoe      10    150
 socks     2     100
 shirt     5     170
 gloves    1     210

thanks for help

A: I think that you just need aggregation:
select item_name, price, min(departure) departure
from mytable
group by item_name, price

Demo on DB Fiddle:

ITEM_NAME | PRICE | DEPARTURE
:-------- | ----: | --------:
shoe      |    10 |       150
socks     |     2 |       100
shirt     |     5 |       170
gloves    |     1 |       210

A: Using row_number() is an effective way of choosing a particular row from a table. Within the over() clause use partition by and order by to control when the row number is reset to 1:

select
    *
from (
    select
         item_name
       , price
       , departure
       , row_number() over(partition by  item_name order by price, departure) as rn
    from mytable a
    ) d
where rn = 1

ITEM_NAME | PRICE | DEPARTURE | RN
:-------- | ----: | --------: | -:
gloves    |     1 |       210 |  1
shirt     |     5 |       170 |  1
shoe      |    10 |       150 |  1
socks     |     2 |       100 |  1

db<>fiddle here


text:
Q: How to Refresh Fragment with new Data I have a fragment in which i have 2 designs, 1 design shows all the items stores within my database and out them into a table. Design 2 is where you can add them. Once finishing design 2, when you go back the TableLayout is gone and the new item is not there. Can anyone help and tell me what the issue is
public class Device extends Fragment {

    public Device() {
        // Required empty public constructor
    }

    //FOR CALENDAR
    final Calendar myCalendar = Calendar.getInstance();
    TextView CalendarTxt, TimeTxt;
    EditText ReminderTxt;

    //FOR CALENDAR
    private void updateLabel(TextView edittext) {
        String myFormat = "dd/MM/yy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);

        edittext.setText(sdf.format(myCalendar.getTime()));
    }

    //FOR CALENDAR
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel(CalendarTxt);
        }

    };
    public void Refresh() {
        SQLiteDatabase db = getActivity().openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
        Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);
        Log.d("Count", String.valueOf(data.getCount()));
        if (data.getCount() > 0) {
            data.moveToFirst();
            //Database values taken and added
            do {
                View tableRow = LayoutInflater.from(getContext()).inflate(R.layout.table_item, null, false);
                TextView name = (TextView) tableRow.findViewById(R.id.TblItemName);
                TextView date = (TextView) tableRow.findViewById(R.id.TblItemDate);

                name.setText(data.getString(0));
                date.setText(data.getString(1));

            } while (data.moveToNext());
            data.close();
        }

    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_device, container, false);

        ViewGroup placeholder = (ViewGroup) rootView;

        CircleButton AddNotifBtn = rootView.findViewById(R.id.AddNotifBtn);
        TableLayout tableLayout = rootView.findViewById(R.id.tableLayout);
        //Database established
        SQLiteDatabase db = getActivity().openOrCreateDatabase("NotificationDatabase", android.content.Context.MODE_PRIVATE, null);
        Cursor data = db.rawQuery("SELECT * FROM PersonalNotif", null);

        Log.d("Count", String.valueOf(data.getCount()));
        if (data.getCount() > 0) {
            data.moveToFirst();
            //Database values taken and added
            do {
                View tableRow = LayoutInflater.from(getContext()).inflate(R.layout.table_item, null, false);
                TextView name = (TextView) tableRow.findViewById(R.id.TblItemName);
                TextView date = (TextView) tableRow.findViewById(R.id.TblItemDate);

                name.setText(data.getString(0));
                date.setText(data.getString(1));
                tableLayout.addView(tableRow);

                tableRow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                                .setIcon(android.R.drawable.ic_dialog_alert)
                                .setTitle("Do you want to Delete Reminder- " + name.getText().toString())
                                .setMessage("Accepting will delete the Chosen Reminder")
                                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        db.delete("PersonalNotif", "NameOfNotif=? and TimeOfNotif=?", new String[]{name.getText().toString(), date.getText().toString()});
                                        Refresh();
                                        tableLayout.removeView(tableRow);

                                    }
                                })
                                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                    }
                                })
                                .show();

                    }
                });

            } while (data.moveToNext());
            data.close();

        }

        AddNotifBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Refresh();

                View newView = inflater.inflate(R.layout.fragment_device2, container, false);
                View oldView = inflater.inflate(R.layout.fragment_device, container, false);
                //All New Views need newView before hand

                /// Calender Button Code Start
                CalendarTxt = newView.findViewById(R.id.CurrentDateSelect);
                CircleButton CalendarButton = newView.findViewById(R.id.calendarBtn);
                CalendarButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new DatePickerDialog(getContext(), date, myCalendar
                                .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),   //Refers Back to Method at the Top
                                myCalendar.get(Calendar.DAY_OF_MONTH)).show();
                    }
                });
                /// Calender Button Code End

                /// Clock Button Code Start
                TimeTxt = newView.findViewById(R.id.CurrentTimeSelect);
                Calendar mcurrentTime = Calendar.getInstance();
                int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); //All the Variables needed
                int minute = mcurrentTime.get(Calendar.MINUTE);
                CircleButton ClockButton = newView.findViewById(R.id.timeBtn);
                ClockButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TimePickerDialog mTimePicker;
                        mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                                @SuppressLint("DefaultLocale") String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
                                TimeTxt.setText(curTime);
                            }
                        }, hour, minute, true);//Yes 24 hour time
                        mTimePicker.setTitle("Select Time");
                        mTimePicker.show();
                    }
                });
                /// Clock Button Code End

                /// Proceed Button Code Start
                Button ProceedBtn = newView.findViewById(R.id.ProceedBtn);
                ProceedBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ReminderTxt = newView.findViewById(R.id.ReminderTxt);
                        String TimeVal = TimeTxt.getText().toString();
                        String DateVal = CalendarTxt.getText().toString();  //ID initialisation
                        String RemindVal = ReminderTxt.getText().toString();

                        if ((TimeVal + DateVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((TimeVal + DateVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((TimeVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else if ((DateVal + RemindVal).isEmpty()) {
                            Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
                        } else {
                            String FinalAlarmVal = DateVal + " " + " " + TimeVal; //Combines time and Date to make final Val

                            String AlarmHour = TimeVal.substring(0, 2);
                            String AlarmMins = TimeVal.substring(3, 5); //Gets Key Part of TextView

                            String AlarmMonth = DateVal.substring(3, 5);
                            String AlarmDay = DateVal.substring(0, 2);  //Gets Key Part of TextView

                            AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins),
                                    Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
                            try {

                                ContentValues values = new ContentValues();
                                values.put("NameOfNotif", RemindVal);
                                values.put("TimeOfNotif", FinalAlarmVal);    //Adds into Database

                                db.insert("PersonalNotif", null, values);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            placeholder.removeAllViews();
                            placeholder.addView(oldView);
                            Refresh();
                        }
                    }
                });
                /// Proceed Button Code End

                /// Proceed Button Code Start
                Button CancelBtn = newView.findViewById(R.id.CancelBtn);
                CancelBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Fragment currentFragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
                        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
                        fragmentTransaction.detach(currentFragment);
                        fragmentTransaction.attach(currentFragment);
                        fragmentTransaction.commit();

                        placeholder.removeAllViews();
                        placeholder.addView(oldView);

                    }
                });
                /// Proceed Button Code End

                //placeholder.removeAllViews();   //These two lines replace old view for the new one
                placeholder.addView(newView);

            }
        });

        return rootView;
    }

}


text:
Q: Deploy virtual PC based on snapshot using Hyper-V I have a server with Hyper-V configured, it is easy to create a new virtual machine using the management tools, but it can take some time.
I often see those hosts that say "We can have your server ready in 5 seconds". And I wonder how do they manage this? I would also like to deploy a full functional clean server in 5 seconds.
So how is this done? Is it by first installing a clean server, then take a snapshot of that for later to deploy a new server based on that snapshot?
I tried doing this, but I did not find any where to install a new virtual machine based on the snapshot.
Anyone got any thoughts to share on this?

A: Yes, this is done by creating a Virtual Machine Template, this is a VM that you have configured the way you want all your VM's to be and you then replicate each time you want to create a new VM. This means you don't have to go through a complete install of Windows every time you create a VM.
However, it's not as simple as just copying the machine, as you end up with issues like duplicate SIDS, machine names, IP addresses etc. This article provides a very brief overview of how to create template VM's, this article goes a bit more in depth into the whole process.

A: You don't need SCCM.
What you can do is:

*

*Script the creation of a virtual machien

*Start with a copy of a prepard image.

Basically:

*

*Install an image once

*make a differential disc

*On it make  sysprep that does not remove drivers.

Then, on the new machine:

*

*start with a copy of said disc

Creating a new machine is trivial with powershell (http://poshcode.org/571). Really takes only one second, and you just need 2 parameters: number cpu's and amount ram.
The copy starts and should be ready within - hm - a minute or so. maximum.
This is at least what I do ;) No snapshots here for that ;)


text:
Q: net core api controller method runs differently on release configuration I have a standard Net core Api solution. My Business layer service, connects to DB , maps the LogModel with DTO and returns it to controller to return to the client.

I can edit LogModelDTO however I like and it works perfectly in Debug configuration, but when I publish my code, or just choose Release configuration, it seems my application ignores my changes to DTO model.
Here I commented out some properties:

Postman results:

In debug configuration it returns only Id property, which is expected.
How can I fix this?
edit: I cleaned my solution and Release configuration started working, but when I publish my app, it still seems to ignore the changes I make...

A: When publishing, do you have the setting to overwrite files activated?


text:
Q: Phonegap - InAppBrowser - Cross Origin Policy I realize domain's require white listing in order to make cross domain calls within the actual Phonegap app, but does the InAppBrowser plugin also abide by these white listing rules?
Cordova 2.7.0 - Android
Thanks!

A: Not necessarily needed,
Check the _self description

window.open( strUrl, strWindowName[, strWindowFeatures])

strWindowName:

"_self" -> opens in the Cordova WebView if strUrl is in the
  white-list, else it opens in the InAppBrowser
"_system" -> always open in the system web browser
"_blank" -> always open in the InAppBrowser


text:
Q: AngularJS: Bind a Service Variable to a Value on a Controller's $scope I am creating a single-page AngularJS web app. My app needs to be able to query a backend service to get some information about a user's state, and this state information needs to be available to the various pieces of the single-page app. I created a service to manage this functionality, but I'm having trouble hooking things up in a way that seems reasonable to me.
Initially, I had things set up like this...
<service.js>
...
var url = 'www.my-backend.com';
this.val = [
    {
        name: 'undefined',
        isValid: false
    }
];
$http.get(url, {})
    .success (function (data) {
        this.val = data;
    })
    .error (function () {
        this.val =  [
            {
                name: 'error',
                isValid: false
            }
         ];
    });
...

And then in my controller...
<controller.js>
...
$scope.val = service.val
...

This didn't work though (val.name was 'undefined'), presumably because service.val was bound to the controller's $scope before the get request had a chance to terminate. However, that does seem at odds  with what I read here.
The next thing I did was this...
<service.js>
...
var url = 'www.my-backend.com';
this.valPromise = $http.get(url, {});
...

And then in my controller...
<controller.js>
...
$scope.val = [
    {
        name: 'undefined',
        isValid: false
    }
];
service.valPromise
    .success (function (data) {
        $scope.val = data;
    })
    .error (function () {
        $scope.val =  [
            {
                name: 'error',
                isValid: false
            }
         ];
    });
...

This worked, but I didn't like it. I feel like that logic belongs in the service.
So the next thing I did was work through the various suggestions that I found here, although none of them seemed to have the desired effect. I also saw this, but it seems like overkill and not really applicable to my problem.
Ideally I'd really like to figure out how to get my first attempt working (tightly bind my service variable to my controller scope by reference), but if that's not something that can really be done within the Angular framework, I'm happy to use some kind of watch behavior. Can anyone spot what I'm doing wrong or why my service variable isn't getting properly hooked up to my controller?

A: In your $http callbacks this is not the service. You'll find plenty of answers about the meaning of this on SO. You need to refer to the service via a variable.
The second problem is that this.val = data; would assign a new value to the service, but doesn't change the data in the scope, which still points to the old array. So you need to copy the new data to the existing array.
var service = this;
$http.get(url, {})
.success (function (data) {
    angular.copy(data, service.val);
})

A: I ran into this problem the other day.  The reason it does not get set is because there is a race condition and because the data access is inside the service layer, it will lose every time.  It seems like there should be a easy way to do this.  I ended up just having my initial controller make the data access calls and set the properties in the service for other controllers to get.


text:
Q: How to add else false to boolean method I have a boolean method that checks if certain elements are present.
It currently only returns true, but I want to assert it's false at a later stage of my testing when the elements are no longer displaying.
I'm using a webdriver wait to check the elements are present.
I've tried isDisplayed() and simple if and else statements but they won't work for me.
public boolean is_leaderbaord_viewable(){
    WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
    wait.until(ExpectedConditions.visibilityOf(position_header));
    wait.until(ExpectedConditions.visibilityOf(player_header));
    wait.until(ExpectedConditions.visibilityOf(num_of_players));
    wait.until(ExpectedConditions.visibilityOf(leaderboard_picks_header));
    System.out.println("Leaderboard is now displayed");

    return true;
}

I just want to be able to assert it's either true or false in my tests.

A: Just use try and catch:
try {
        WebDriverWait wait = new WebDriverWait(Drivers.getDriver(), 10);
        wait.until(ExpectedConditions.visibilityOf(position_header));
        wait.until(ExpectedConditions.visibilityOf(player_header));
        wait.until(ExpectedConditions.visibilityOf(num_of_players));
        wait.until(ExpectedConditions.visibilityOf(leaderboard_picks_header));
        System.out.println("Leaderboard is now displayed");

        return true;
    }
    catch (Exception e){
        return false;
    }

Hope this helps you!


text:
Q: Sending designated logs to the Kafka sink using Uber-Zap logger in Go I am trying to use zap logger package to create a core with file, console and Kafka sinks. I have some really specific INFO level logs that I want to send to a Kafka topic for processing by a downstream consumer. However, with the current implementation I am getting all INFO level logs in the Kafka topic, even the ones I do not want.
Is there a way to prevent the unwanted logs of the same level to not go to any one specific sink, using a common zap logger object?
Below is the function that I am using to create the single logger object.
func newZapLogger(config Configuration) (Logger, error) {
    var writer zapcore.WriteSyncer
    cores := []zapcore.Core{}

    if config.EnableFile {
        getLogLevel(config.FileLevel)
        if config.LogConfig == true {
            writer = zapcore.Lock(zapcore.AddSync(&lj.Logger{
                Filename: config.FileLocation,
                MaxSize:  config.LogMaxSize,
                Compress: config.LogCompression,
                MaxAge:   config.LogMaxAge,
            }))
        } else {
            writer = zapcore.Lock(zapcore.AddSync(&lj.Logger{
                Filename: config.FileLocation,
            }))
        }
        cores = append(cores, zapcore.NewCore(getEncoder(config.FileJSONFormat, config.IsColour), writer, atomLevel))
    }
    if config.EnableConsole {
        getLogLevel(config.ConsoleLevel)
        switch config.Stream {
        case 1:
            writer = zapcore.Lock(os.Stdout)
        case 2:
            writer = zapcore.Lock(os.Stderr)
        case 3:
            writer = zapcore.Lock(zapcore.AddSync(ioutil.Discard))
        default:
            writer = zapcore.Lock(os.Stdout)
        }
        cores = append(cores, zapcore.NewCore(getEncoder(config.ConsoleJSONFormat, config.IsColour), writer, atomLevel))
    }
if config.EnableKafka == true {
        highPriority := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
            return lvl >= zapcore.WarnLevel
        })

        if len(brokerConn) > 0 {
            var (
                kl  LogKafka
                err error
            )
            kl.Topic = config.KafkaTopic
            config := sarama.NewConfig()
            config.Producer.RequiredAcks = sarama.WaitForAll
            config.Producer.Partitioner = sarama.NewRandomPartitioner
            config.Producer.Return.Successes = true
            config.Producer.Return.Errors = true

            kl.Producer, err = sarama.NewSyncProducer(brokerConn, config)
            if err != nil {
                return nil, fmt.Errorf("Failed to initialise kafka logger, connect to kafka failed: %v", err)
            } else {
                topicErrors := zapcore.AddSync(&kl)
                kafkaEncoder := zapcore.NewJSONEncoder(zap.NewDevelopmentEncoderConfig())
                cores = append(cores, zapcore.NewCore(kafkaEncoder, topicErrors, highPriority))
            }
        } else {
            return nil, fmt.Errorf("Failed to initialise kafka logger, no broker specified")
        }
    }

    appendedCore := zapcore.NewTee(cores...)
    logger := zap.New(appendedCore, zap.AddCaller(), zap.AddCallerSkip(1)).Sugar()
    defer logger.Sync()
    return logger, nil
}

I am using Sarama package to implement Kafka producer.
I have also thought of using a custom logging level. However, it is not supported in zap v1.0.


text:
Q: Incompatibility of the motherboard and HDD I have a problem with my old HDD that refuses to work with the new motherboard; the disk just doesn't show up in BIOS. Same results with different SATA ports and cables, but this disk does work on the old PC. BIOS and Windows just don't show this disk, and Ubuntu shows a number of "sata: COMRESET failed" errors for this disk.
Any ideas?


text:
Q: display nested JSON in ruby on rails I believe this is going to be an easy fix but everything I'm trying isn't working.
I'm getting data from an external API and I'm looking at display the data after matching the ids.
The data is JSON and has some nested content.
I've tried the following

Street: <%= @users.find{|u| u['id'] == @album['userId']}.try(:[],'address''street') || 'not available' %>

The data is structured like so
{
  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
}

A: You'll want that to be:

Street: <%= @users.find{|u| u['id'] == @album['userId']}.try(:[],'address').try(:[],'street') || 'not available' %>

For a multi-level try, you might want to look into dig.
Also, if the iteration is as in your previous questions, then @album may need to be album. If this is in a different context than your previous questions, then kindly disregard.

A: This is where dig is useful:
https://ruby-doc.org/core-2.3.0_preview1/Hash.html

Street: <%= @users.find{|u| u['id'] == @album['userId']}.dig(:address, :street)  || 'not available' %>


text:
Q: Change div to span multiple rows when middle row display set to none I have three divs that each take up a row like in the below code.
The top row question contains some text that changes over time and can be varying length.
The middle row speech_bubble_middle_bar contains an input bar that sometimes will be displayed, and sometimes will not.
The bottom row speech_bubble_bottom_bar contains some buttons that will always be there.
I need to figure out how to expand the size of question when speech_bubble_middle_bar has display set to none, so I have more space for the text when speech_bubble_middle_bar is not displayed.
I thought I could do that by changing grid-rows from 1/2 to 1/3 to define question as spanning the space that previously was taken up by speech_bubble_middle_bar, and I was going to use JavaScript to switch back and forth as needed when the middle bar is displayed. Unfortunately it's not working, and instead moves speech_bubble_bottom_bar up to occupy the empty space.
This is my relevant code:
* {
  -webkit-box-sizing: border-box;
  -mo-box-sizing: border-box;
  box-sizing: border-box;
}

html,
body {
  position: fixed;
  height: 100%;
  background-color: #311049;
  font-size: 2vh;
  margin: 0 auto;
}

.screen {
  position: absolute;
  height: 100%;
}

.menu-button {
  grid-column: 3/4;
  position: relative;
  height: 100%;
}

.menu-button img {
  position: absolute;
  height: auto;
  max-height: 75%;
  max-width: 75%;
  left: 50%;
  right: 50%;
  top: 50%;
  bottom: 50%;
  transform: translate(-50%, -50%);
}

.display {
  position: relative;
  height: 86.286%;
  width: 100vw;
}

.speech-bubble {
  display: grid;
  grid-template-rows: 60% 20% 20%;
  position: relative;
  background-color: #f5f5f5;
  height: 61.8%;
  width: 90vw;
  margin: auto;
  border-radius: 2em;
  z-index: 10;
  padding-bottom: 1em;
}

.speech-bubble:after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 15vw;
  width: 0;
  height: 0;
  border: 4em solid transparent;
  border-top-color: #f5f5f5;
  border-bottom: 0;
  margin-left: -2em;
  margin-bottom: -2em;
  z-index: -1;
}

.logo-animation {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 10%;
  padding-top: 10%;
  padding-left: 10%;
  padding-right: 10%;
  display: none;
}

.logo-animation img {
  height: 100%;
  object-fit: contain;
  margin-left: auto;
  margin-right: auto;
  display: none;
}

.question {
  grid-rows: 1/2;
  position: relative;
  font-size: 5vh;
  padding-left: 0.5em;
  padding-right: 0.5em;
  padding-top: 0.5em;
  padding-bottom: 0.5em;
  background: green;
}

.question-text {
  height: 100%;
  width: 100%;
  overflow: auto;
}

.speech-bubble-middle-bar {
  grid-rows: 2/3;
  padding-left: 1%;
  padding-right: 1%;
  padding-top: 1%;
  padding-bottom: 1%;
  background: red;
}

.input-text {
  visibility: hidden;
  width: 100%;
  height: 100%;
  border-radius: 2.5em;
  border: 0.25em solid black;
  padding: 1%;
  font-size: 2em;
  text-align: center;
}

.speech-bubble-bottom-bar {
  grid-rows: 3/4;
  display: grid;
  grid-template-columns: 50% 50%;
  position: relative;
  width: 100%;
}

.left-button-container {
  position: absolute;
  height: 100%;
  width: 38.2%;
  left: 0%;
  margin-left: 1em;
}

.left-button-container button {
  width: 100%;
  font-size: 2em;
}

.right-button-container {
  position: absolute;
  height: 100%;
  width: 38.2%;
  right: 0%;
  margin-right: 1em;
}

.right-button-container button {
  width: 100%;
  font-size: 2em;
}

.button {
  position: relative;
  display: inline-block;
  height: 100%;
  background: #311049;
  /*Button Color*/
  color: #f5f5f5;
  font-family: hack;
  font-size: 1.5rem;
  font-size: clamp(1rem, 3vw, 2rem);
}

.left-btn:after {
  display: block;
  color: #f5f5f5;
  line-height: 0.5em;
  content: "\2190";
}

.right-btn:after {
  display: block;
  color: #f5f5f5;
  line-height: 0.5em;
  content: "\2192";
}

Title

                    Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum. Lorem ipsum.

                    <input type="text" id="input-text" class="input-text" />

                        <button id="left_button" class="button resize">Wow!</button>

                        <button id="right_button" class="button resize">Next</button>

Here's a pic showing the problem, the red bar is speech_bubble_middle_bar that I need to be able to remove without speech_bubble_bottom_bar moving up, which is does when I hide the middle row by setting speech_bubble_middle_bar display to none.

Here's what it looks like with speech_bubble_middle_bar display set to none.

And here's a FS Fiddle:
https://jsfiddle.net/TheNomadicAspie/gmb86ak5/7/

A: Here is a short sample of code that does what I believe you wanted. It is bare and stripped of style. Just what is required.
Be sure to hit the "toggle" button to see the changes.

function toggle(e){
  if(e){e.stopPropagation();e.preventDefault();}
  var q = document.getElementById("question");
  var a = document.getElementById("answer");
  if (a.classList.contains("hide")){
    a.classList.remove("hide");
    q.classList.remove("questionExpand");
    q.classList.add("questionShort");
  } else {
    a.classList.add("hide");
    q.classList.remove("questionShort");
    q.classList.add("questionExpand");
  }
}
window.onload = function(){
  var b = document.getElementById("toggleAnswer");
  b.addEventListener("click",toggle,false);
}
.contain {
  line-height:2em;
  height:7em;
  border:1px solid black;
}
#question {
  overflow:auto;
}
.questionShort {
  height:5em;
}
.questionExpand {
  height:7em;
}
.hide {
  display:none;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<input type="text" />

<button id="toggleAnswer" class="butLeft">Toggle</button>

A: I realized a solution to this is just to change the grid-template-rows of .speech-bubble as needed from 60% 20% 20% to 80% 0% 20%


text:
Q: Apply function from std::tuple
Possible Duplicate:
"unpacking" a tuple to call a matching function pointer

I'm building a closure object to wrap a function and its parameters, to create a functor of zero parameters:
template<typename Function, typename... Args>
  struct closure
{
  closure(Function f, Args... args)
    : f(f),args(args...)
  {}

  void operator()()
  {
    // call f using the tuple's elements as arguments
    apply_from_tuple(f,args);
  }

  Function f;
  std::tuple<Args...> args;
};

What's the most concise way to build the function apply_from_tuple?


text:
Q: How to compare two database structures? I'm using SQLite/Hibernate. Idea is to check each time app starts whether database structure is up to date. I have my existing database in "DB" folder and each time app start I'm creating up to date database in "DB/structure" folder.
I want to compare them and if my existing database is old, copy data to up to date database. Get rid of old database and move fresh one in it's place.
So far I've tried SchemaCrawler, but I was getting errors with it and couldn't figure it out.
UPDATE:
I connected with SchemaCrawler to both databases:
public SchemaConroller() {

        SchemaCrawlerOptions options = new SchemaCrawlerOptions();
        options.setSchemaInfoLevel(SchemaInfoLevelBuilder.standard());

        Catalog catalog1=null;
        try {
            Connection conn = getConnection();
            catalog1 = SchemaCrawlerUtility.getCatalog(conn, options);
            for (Schema schema : catalog1.getSchemas()) {
                System.out.println(schema);
                for (Table table : catalog1.getTables(schema)) {
                    System.out.println("o--> " + table + "    size: "+table.getColumns().size());
                    /*for (Column column : table.getColumns()) {
                        System.out.println("     o--> " + column);
                    }*/
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Catalog catalog2=null;
        try {
            Connection conn = getConnection2();
            catalog2 = SchemaCrawlerUtility.getCatalog(conn, options);
            for (Schema schema : catalog2.getSchemas()) {
                System.out.println(schema);
                for (Table table : catalog2.getTables(schema)) {
                    System.out.println("o--> " + table + "    size: "+table.getColumns().size());
                    /*for (Column column : table.getColumns()) {
                        System.out.println("     o--> " + column);
                    }*/
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if(catalog1.equals(catalog2)){
            System.out.println(">>>>>>>>>>>>DATABASE IS UP TO DATE<<<<<<<<<<<<<<");
        }else{
            System.out.println(">>>>>>>>>>>>DATABASE IS OUT OF DATE<<<<<<<<<<<<<<");
        }
    }

But I always get positive answer, if I try catalog1 == catalog2 - I always get negative. How to properly compare data structure?

A: Alyona,
Please take a look at schemacrawler-diff for ideas on how to get started with programatically comparing database structures. Please note that this code is not production ready, nor is it supported, so you will to develop your own method of comparing databases, based on your needs.
Sualeh Fatehi, SchemaCrawler


text:
Q: ¿Cómo recorrer el siguiente arreglo en PHP? Tengo un código PHP el cual me trae el JSON pero no me deja recorrerlo, en este caso es tickets. En mi JSON me sale esto (son miles de registros más, esto es una muestra):
{
  "status": 200,
  "tickets": [
    "5d9c9469b2a7d12837b657b3",
    "5d9c9468b2a7d12837b657b1",
    "5d9c9459b2a7d12837b657a9",
    "5d9c9457b2a7d12837b657a7",
    "5d9c944fb2a7d12837b657a4",
    "5d9c9437b2a7d12837b6579e"]};

y este es mi código:
<?php

$ch = curl_init();

$options = array(CURLOPT_URL => 'https://api-cluster.postcenter.io/v2/tickets/state/open',
                 CURLOPT_HEADER => false,
                 CURLOPT_HTTPHEADER => array(
                    'Authorization: Key dksafk99w3r9',
                    "cache-control: no-cache"
                )
                );

curl_setopt_array($ch, $options);

curl_exec($ch);

curl_close($ch);

?>

A: Como bien indica el manual de PHP, Para que cURL te devuelva los datos tienes que poner en $options un parámetro que es este: CURLOPT_RETURNTRANSFER=>TRUE, luego, puedes guardar los datos en una variable y aplicarle json_decode.
Intenta esto:
<?php
    $ch = curl_init();

    $options = array(CURLOPT_URL => 'https://api-cluster.postcenter.io/v2/tickets/state/open',
                     CURLOPT_HEADER => false,
                     CURLOPT_RETURNTRANSFER=> TRUE,
                     CURLOPT_HTTPHEADER => array(
                        'Authorization: Key dksafk99w3r9',
                        "cache-control: no-cache"
                    )
                    );

    curl_setopt_array($ch, $options);

    $r=curl_exec($ch);

        if(!$r)
        {
            $mData=array( curl_error($ch) );

        } else {
            $json=json_decode($r);
            $mData=$json->tickets;
        }

        curl_close($ch);

    #Lectura de datos
    foreach ($mData as $item) {
        echo $item.PHP_EOL;
    }

?>

Si los datos vienen como muestras, verás en pantalla cada valor del array que hay en tickets, o bien el mensaje de error de la petición  cURL. Si no ves nada, depura la respuesta con un var_dump($r); y dinos lo que aparece en pantalla.


text:
Q: how to handle Sonarlint java:S2259 (Null pointers should not be dereferenced) if (res.getBody() == null || res.getBody().getServiceResult() == null) {
  return; //
}

in above code,
sonarlint complains that
SonarLint: A "NullPointerException" could be thrown; "getBody()" can return null. (from res.getBody().getServiceResult() )
I think "res.getBody() == null" checks null first so it should go to return line, not reach to next if condition.
Am I thinking something wrong?

A:
res.getBody() == null || res.getBody().getServiceResult() == null)

Sonar detects that res.getBody() can be null when you do the check res.getBody()==null.
After that, you call res.getBody() again.
It could be non-null the first time but not the second time, sonar does not know this.
In order to fix this, just do the following:
BodyType body=res.getBody();
if (body == null || body.getServiceResult() == null) {
  return;
}

You can then even reuse body after that.
If you are absolutely sure that res.getBody() stays null and is also not modified by another thread, you could also use a //NOSONAR comment in order to suppress the warning.

A: It seems res also can be null.
Try
if (res == null || res.getBody() == null || res.getBody().getServiceResult() == null) {
  return; //
}

Such long getter chains can also be replaced with Optional + map + ifPresent lambda style.