text:
Q: Create specific size images based on hex value Normally I would've given this a stab already but to be honest I don't even know where to start.
I have a Dataframe with a column of Hex values, and I'd like to write a script to pick each one and create a PNG file of specific dimensions filled with that color.
hexValue
 2A9D8F
 9B5DE5
 EE8959
 FEE440
 5F797B
 C1D375

All the images I'd like to be 1080 x 1080 px. Attached is the first as an example. Is there an easy way to do this?

Thanks in advance.

A: Does this help?
from PIL import Image

dummy_list = [
    "#ff00ee",
    "#ff0000",
    "#000000",
    "#00ff00"
]

for color in dummy_list:
    img = Image.new('RGB', (1080, 1080), color=color)
    img.save(f"{color}.png")

EDIT: Oh, and PIL is installed with:
pip install Pillow


text:
Q: CSS- Injecting and aligning images above certain words in (any) html text without ruining the text flow My goal is to dynamically (with content script) inject images above text in basically any page, and keeping the text normally aligned. The words I inject the image to have a span around them with a certain attribute, and my script(content script of chrome extension) wraps that span with another span(the parent in my css) that has the img (wrapped up in its own span) as well.
The issue (a CSS issue) is when i inject the images the text lining of the text gets ruined.
You can see it all much more clearly in https://jsfiddle.net/wyfumrx6/2/
the words 'a Good' aren't lined with the rest of the text.
Here's what i do now, using inline-flex and flex-direction:
HTML example:

  How

  to Make
  a Good Cup of Tea

With CSS (injected as well):
For the span wrapping the img(inside a span) and the text(also inside its own span):
.aui_top_in_page_parent {
  display: inline-flex;
  flex-direction: column;
  position: relative;
  z-index: 99999999;
  margin: 1%;
}

For the inside span wrapping the img only:
.aui_top_in_page {
  font-size: 14px;
  font-weight: regular;
  overflow: visible;
  padding: 0px 0px 0px;
  color: #fff;
  -webkit-border-radius: 7px;
  -moz-border-radius: 7px;
  border-radius: 7px;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
  text-align: center;
  text-decoration: none;
  z-index: 99999999;
  align-items: center;
}

see it all much clealy with the result here:
https://jsfiddle.net/wyfumrx6/
I want the line, the words, to stay in a straight line while the images are above the 'marked' words, and that that images will have enough margin from the text line above so that it's clear which word the img is refering to.

A: You can just use vertical align bottom if you remove the 1% top and bottom margin:

.aui_top_in_page_parent {
  display: inline-flex;
  flex-direction: column;
  position: relative;
  z-index: 99999999;
  margin: 0 1%;             /* change this to side margin only */
  vertical-align: bottom;   /* add this */
}

.aui_top_in_page {
  font-size: 14px;
  font-weight: regular;
  overflow: visible;
  padding: 0px 0px 0px;
  color: #fff;
  -webkit-border-radius: 7px;
  -moz-border-radius: 7px;
  border-radius: 7px;
  -webkit-background-clip: padding-box;
  -moz-background-clip: padding;
  background-clip: padding-box;
  margin-bottom: 20%;
  text-align: center;
  text-decoration: none;
  z-index: 99999999;
  align-items: center;
}

    How

    to

    Make

  a Good

    Cup of Tea

Updated fiddle

A: I find out the solution..
I make few changes in HTML and CSS file as below..
add span tag a Good
and some changes in css file.

.aui_top_in_page_parent{
       display: flex;
    flex-direction: column;
    /* position: relative; */
    align-items: center;
    margin: 0;
    justify-content: flex-end;
    margin: 5px;
}
a{
  display: flex;
    flex-direction: row;
}
.aui_top_in_page{

   font-size:14px;
   font-weight:regular;
   overflow:visible;
   padding:0px 0px 0px;
   color:#fff;
   -webkit-border-radius:7px;
   -moz-border-radius:7px;
   border-radius:7px;
   -webkit-background-clip:padding-box;
   -moz-background-clip:padding;
   background-clip:padding-box;
   margin-bottom: 0;
   text-align:center;
   text-decoration:none;
      z-index:99999999;
   align-items:center;
}
How to Makea Good  Cup of Tea

redpajama_set_name: RedPajamaStackExchange


text:
Q: .net IIS web server localhost I am new in .net and visual studio.
when I have tried to configure IIS web server in my local machine.
Its running in my system using
URL :- http://localhost:8080   ------------ IS IIS 8
But at the same time in mt colleagues system its running using
URL :- http://localhost/             ---------- IS IIS 7
Is it something i need to change and host setting ..
Using command --
inetmgr

or
host setting etc

Is it fine for my dev environment setup ??
Thanks !!

A: Open the Internet Information Service (IIS) Manager and click on the 'Sites' menu item on the left. You should see a list of sites that are running on your local installation of IIS. Right click the website whose port you want to change and select 'Bindings...'.
To have your website run on http://localhost/ you simply need to change the port in the bindings to port 80.

A:
Is it fine for my dev environment setup?

Yes.


text:
Q: Xcode 4.6 crash because of ARC? Unbelievable in Xcode 4.6.
If I initialize a variable to something, it frees the memory. But what if this variable has a random value ?
class X
{

private:

    NSThread* thr;

public:

    X();
};
X :: X()
    {
        thr = 0; // BOOM !!!?
    }
X* x = new X(); // Constructor crashes.

But if the constructor is inline, it doesn't!

A: In a C++ constructor, you need to use an initialization list to set the initial value of the member variable.
X :: X() : thr(nil)
{
}

Otherwise, like you are seeing, thr will initially have a garbage value, and you might crash when ARC tries to send -release to that value.
As the ARC documentation says:

ARC cannot differentiate between an assignment operator which is intended to "initialize" dynamic memory and one which is intended to potentially replace a value.


text:
Q: Adding to JComboBox without using an array Is it possible to add a String to a JComboBox without using an array?  I have an adding button that should add to combo box after clicking on it but I don't know how to do that.

A: Use DefaultComboBoxModel.addElement(E).  More generally, see How to Use Combo Boxes.

A: Andrew is correct, you don't need to go to the model though. The jComboBox class provides an addItem method for you.


text:
Q: Discord "messageCreate" and "InteractionCreate" events does not work I was trying to do a simple command using the clasic message event (now messageCreate event), so I programed a small code to test if the event is working righfully:
const Discord = require('discord.js')
const { Client, Intents, Message, MessageEmbed} = require('discord.js');
const { token, prefix } = require('./config.json')

const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.once('ready', () => {
    console.log(`${client.user.username} Se Ha Conectado Correctamente`)
})

client.on('messageCreate', (message) => {
    console.log('Un Mensaje! :D');
    console.log(message);
})
client.on('interactionCreate', interaction => {
    console.log(interaction);
})

client.login(token);

But when I send the messages at the guild where I am testing the bot, he can't detect them for some reason.
as extra data, the console.log of the ready event works perfectly.

Fixes testings

Maybe permissions? It already have administrator but I moved the role to the top for testing, nothing happened.
Maybe add the GUILD_MESSAGES intent on the client? I also tried this one but the bot still can't detect the messages
Discord.js version: v13.3.1
Node.js version: v17.0.1

A: Like Worthly Alpaca has mentioned in the comments, it is required to use the GUILD_MESSAGES intent in order to be able to receive the messages. Your client will now look like:
const client = new Client({intents: [Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILDS]});

Please note that you now have to enable the GUILD_MESSAGES intent on the page of your Discord application.


text:
Q: Electromagnetic field and voltage drop in a circuit I have been thinking for a while about what really causes voltage drop and how to explain it in terms of what the electric and magnetic fields do. So I've been reading a lot of posts here and in other places, but I could not really connect the dots to what happens to an electron at each point in the circuit, especially before and after the resistor. Either the explanations were too mathy or were lacking a little more in-depth explanation, which is really what I am looking for. I am confortable with math, but it doesn't explain to me the phenomena, and doesn't really help visualize the interactions at that quantum level. It just wants me to accept that the whole thing is a black box, but hey, according to the formula, this is what you get in the end!
I will try to explain what I know so far. Some other questions ([Q]) may pop along the way and I will try to list them for you to correct me if you think that's where i'm making a wrong assumption or I got something totally wrong. If it's not relevant to the main question, skip it.
So let's say we have a battery and a resistor in a circuit.
Here is what I have so far:

*

*When we complete the circuit, the electric field guided by the surface charges of the wire, propagates through and around the wire to the negative terminal and establishes a potential difference between the positive and negative terminal. If the wire were a perfect conductor, there would be no current.

*

*[Q] If there is a potential difference between the leads of the battery, why there has to be a voltage drop somewhere in the circuit (wire, resistor, load etc.) in order for the current to be flowing? In a perfect conductor, shouldn't the electrons be constantly accelerating therefore infinte current? or at least a current proportional to the total number of electrons available in the wire?

*Because of the electric field, all charges start to move. And it's not that the first electron hit by the field pushes the next and so on, but because each electron is affected by the field with the same force magnitude.

*Now because the electrons are moving, in a stationary surface charge's frame of reference, all the electrons appear closer (Lorentz's transformation), so there is a magnetic field created around the wire, perpendicular to the current flow, which acts upon all the surface charges at that point.

*Because the electron is moving, some of it's potential energy has been converted into kinetic energy, and the rest of its potential energy is stored in the magnetic field and the electric field.

*Let's say an electrons passes through the resistive material. It collides with the impurities (atoms, other electrons) transferring it's kinetic energy to the atom or electron, which in turn vibrates, releasing this vibrational energy into heat and light.

*

*[Q] Now because the electron has lost some KE, it's going a bit slower, so there will be a charge build-up. And because it's going slower, the magnetic field intensity should decrease, because the relativistic effects should have lower effect on the surface charges. Now what happens to the energy stored in the magnetic field, is it transfered to the electron to accelerate it again to keep the average velocity constant or it passes the energy to the electric field, which in turn accelerates the electron so on and so forth?

*Now what are we really measuring when we hook up a voltmeter to measure voltage across the resistor. Is is the strength of the magnetic field? electric field? both? neither?

*

*[Q] From electrostatics we know that if we bring a test charge at distance d in an uniform electric field, then it's potential will be equal to qEd, and if we move it further away from the field it will have less potential energy. So voltage (which is the diference in potential energy at these points) is a function of distance, then a voltage drop would mean that the charges somehow got further apart in the field or the field has been distorted so the flux density at a point after the resistor is lower  ... ?

If anyone could point the flaws in all of this, help me understand what really happens, or point me to some books, that would be great.

A: *

*Q1 If there is a potential difference between the leads of the battery, why there has to be a voltage drop somewhere in the circuit (wire, resistor, load etc.) in order for the current to be flowing? In a perfect conductor, shouldn't the electrons be constantly accelerating therefore infinte current? or at least a current proportional to the total number of electrons available in the wire?

*A1: As you know, we got Ohm's law, $U = R \cdot I$. Now, we take the limit $R \to 0\Omega$, while $U=const$. You see, that the current $I$ must diverge, $I\to \infty$. So, if we assume that the battery is a perfect voltage supply, the current must diverge. Alternatively, we can ask the question which voltage the battery supplies, if the current is limited by some value $I_{max}$. Now we get $U\to 0 V$ if $R\to 0\Omega$. So somehow we have to decide, which picture we like to use. For me, I prefer the first one, because I like to think of a battery as a perfect voltage supply.

*Q2: ... I don't know.

*Q3: I take this as your question: What are we really measuring when we hook up a voltmeter to measure voltage across the resistor?

*A3: There is not only one working principle but many working principles exists. Have a look here. I think, at least some of their names are self explaining. So I just copy them here: Parmanent Magnet Moving coil Voltmeter,
Moving Iron Voltmeter,
Electro Dynamometer Type Voltmeter,
Rectifier Type Voltmeter,
Induction Type Voltmeter,
Electrostatic Type Voltmeter,
Digital Voltmeter.

A: Q1: for an ideal battery with 0 internal resistance, closing the circuit with perfectly conducting wire will result in infinite current. If the battery has internal resistance, as real ones do, all the voltage drop will happen in this internal resistor and thus heat the battery until it is ruined (this could even be a fire hazard). The reason there is a voltage drop is because there is an electric field across some distance. Inside a perfect conductor, there is no field and therefore no voltage drop.
Q2: the same current flows through the resistor as through the perfectly conducting wire. The charges do lose energy to collisions within the resistor, but they are re-acceleration again.
Q3: the most simple volt meter allows charges to accumulate on two metal pieces which then repel each other against some restoring force such as gravity. They repel electrostatically, so it is the electric potential or voltage associated with the electric field which balances the potential difference associated with the resorting force. That is, the voltage causes a proportional increase in the average height of the metal pieces. Obviously there are other methods and modern equipment is more advanced.
I'm not sure your discussion of what the magnetic fields are doing is entirely necessary for the conceptual understanding you appear to be seeking here, since you haven't brought up inductance. Inductance is related to how much momentum gets stored in the magnetic field. Changing momentum takes time, so adding inductance to a circuit causes a lag after a change in voltage while the magnetic field "spins up" to its new equilibrium value. For simple ideal circuits, inductance is often neglected wherever possible and current is treated as if it hits equilibrium instantly after flipping the switch.

A:
[Q] If there is a potential difference between the leads of the battery, why there has to be a voltage drop somewhere in the circuit (wire, resistor, load etc.) in order for the current to be flowing?

I love this question! Here's how I explain it to my freshmen:
Imagine a "potential" you're more familiar with: gravity. When you go up an escalator (which has a potential difference $mg\Delta h$), in order to get back to the bottom, you have to lose potential energy $mg\Delta h$ some way or another (usually by walking down stairs). You also don't keep all that energy as kinetic once you get to the bottom, right? Your shoes & joints create friction (analogous to a resistor) shed the energy so you approach the escalator at ~0 speed again.
Now for a superconductor, with almost 0 resistance, it will keep increasing the current until the tiny resistance accounts for the voltage drop. Imagine, perhaps, an escalator and frictionless slide that keeps speeding you up until the air resistance gives you terminal velocity.

Now because the electron has lost some KE, it's going a bit slower, so there will be a charge build-up. And because it's going slower, the magnetic field intensity should decrease, because the relativistic effects should have lower effect on the surface charges. Now what happens to the energy stored in the magnetic field, is it transfered to the electron to accelerate it again to keep the average velocity constant or it passes the energy to the electric field, which in turn accelerates the electron so on and so forth?

It's not like the current decreases once it hits a resistor, imagine this as a bumper to bumper traffic jam on a single lane highway. They can all drive fast together, but if something slows some of them down it slows all of them down.
In the case that you could dial the resistance up or down, certainly if you were to increase the resistance quickly it would cause a change in the magnetic field which would induce an electric field to accelerate the charges as in Faraday's law. But this is the same for any change in current, not unique to changing resistance.

From electrostatics we know that if we bring a test charge at distance d in an uniform electric field, then it's potential will be equal to qEd, and if we move it further away from the field it will have less potential energy. So voltage (which is the diference in potential energy at these points) is a function of distance, then a voltage drop would mean that the charges somehow got further apart in the field or the field has been distorted so the flux density at a point after the resistor is lower ... ?

Circuits are really a special case that can't be treated with electrostatics. $V = qEd$ doesn't work well to describe circuits because electrons can't move freely past one another, so the effects of the electron in front of and behind of the one you're looking at are really what determines the $\vec{E}$ field at that point. But that is a messy, unhelpful way of looking of the special case that is electric circuits.

A: I believe your misunderstanding on all of these points is coming from the core idea of electricity being the flow of electrons. When the theories electromagnetism were developed in the 1800's, the electron had not been discovered yet, so you have to keep that in mind when trying to explain these ideas with the electron.
By trying to apply a simplistic explanation of electricity given in high school to Quantum Mechanics, you end up running into some problems where the conceptualisation doesn't match up with real life.
Properly understanding electricity and electromagnetism cannot at all be done by just thinking about the electron, so start by read about electric potential and some history on electromagnetism


text:
Q: c++ what happens if callee deletes caller? is the behaviour in a c++ app defined if a callee function deletes the object in which the caller (member) function is defined? will the rest of the caller function body still be executed? will it run correctly if it doesn't access any member variables?
I just ask because I found this case  in my application (the result of some juggling with member function pointers) and I was surprised why it doesn't make my app crash.

A: Yes, that is the expected behavior. As long as the code does not access any non-static member objects or functions, there is no reason why it can't keep running.

A: A notable exception to "yes the rest of the caller will run" is Win32's FreeLibraryAndExitThread, which REALLY deletes the caller, stack space, code, and all.

A: The code is still on the stack even though the destructor was called.  You can't depend on the fact that any free'd memory won't be overwritten in the meanwhile, though.  If it isn't overwritten, however, and the destructor doesn't otherwise overwrite anything critical, things would go along smoothly.


text:
Q: UDP multicast with multiple interfaces not working I have 2 network interfaces

 enp5s0   Link encap:Ethernet  HWaddr d8:cb:8a:c3:4d:61
          inet addr:192.168.1.3  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::dacb:8aff:fec3:4d61/64 Scope:Link
          inet6 addr: 2607:fa48:6d42:4230::1003/128 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

ens6      Link encap:Ethernet  HWaddr a0:36:9f:57:0b:ac
          inet addr:192.168.1.5  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a236:9fff:fe57:bac/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

listening for UDP multicast packets from 224.1.1.1:5007 but packets are only received by my program when running on enp5s0 which happens to be the default interfaces.
I'm using the following code to select the interface based on it's IP based on what I read here. But it doesn't seem to work.

struct ip_mreq mc_addr = {};
mc_addr.imr_multiaddr.s_addr = inet_addr("224.1.1.1");
mc_addr.imr_interface.s_addr = inet_addr(argv[1]);
int rv = setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF,  &mc_addr.imr_interface, sizeof(mc_addr.imr_interface));
if(rv &lt 0) {
    perror("IP_MULTICAST_IF");
}
rv = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,  &mc_addr, sizeof(mc_addr));
if(rv &lt 0) {
    perror("IP_ADD_MEMBERSHIP");
}

If I use enp5s0 everything works fine but when using ens6 I receive nothing even though I can see activity on my switch and in wireshark. Even more confusing is that if I start my program twice with each one running one interface each both programs receive packets.
So why isn't my program receiving packets when using only ens6?

A: In a multihomed host you generally need to join via all available interfaces, unless you know that multicasts will only be arriving via one of them. Otherwise the IGMP join message doesn't go to all possible routers.


text:
Q: How to slice an array into two arrays I have an array that need to be sliced in two parts (see below):
     [items] => Array
    (

        [product] => Humbucker
        [product_price] => 12
        [model] => Single Humbucker
        [model_price] => 12
        [guitarbrands] => fdfdfdf
        [guitarbrands_price] => 23
        [neckfretboard] => 33
        [neckfretboard_price] => 22
        [guitarmodels] => fdfdsf
        [guitarmodels_price] => 22

    )

I want this array
   [items] => Array
    (

        [product] => array(
                            [product] => Humbucker
                            [product_price] => 12
                          )
        [model] =>   array(
                            [model] => Single Humbucker
                            [model_price] => 12
                          )

        [guitarbrands] =>array(
                            [guitarmodels] => fdfdsf
                            [guitarbrands_price] => 23
                           )

    )

A: I usually keep a function for general use e.g :
function preg_grep_keys( $pattern, $input, $flags = 0 )
{
    $keys = preg_grep( $pattern, array_keys( $input ), $flags );
    $vals = array();
    foreach ( $keys as $key )
    {
        $vals[$key] = $input[$key];
    }
    return $vals;
}

So in your case you would be doing sth like this
 $outoupt=array(
        'product'=> preg_grep_keys('/^product/', $input),
         'model'=> preg_grep_keys('/^model/', $input),
         'product'=> preg_grep_keys('/^guitar/', $input)
          );

Hope this might help

A: $result = array('items' => array());

foreach ($array as $key => $value) {
    if (strpos($key, '_') !== false) {
        continue;
    }
    $result['items'][$key] = array(
        $key           => $value,
        "{$key}_price" => $array["{$key}_price"]
    );
}


text:
Q: Cannot Retrieve Column[0] in a Gridview I have been able to correctly access every column/row combination in my grid, except for column 1. It always returns a blank. Below is 4 different ways I have tried, they all run, but all return blank.
protected void userListGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Display") //switch to update user mode
    {
        int rowIndex = Convert.ToInt32(e.CommandArgument);
        string Username = userListGrid.Rows[rowIndex].Cells[0].Text;
        // LinkButton Link = userListGrid.HeaderRow.Cells[0].Controls[0] as LinkButton;
        // string Username3 = Link.Text;
        string Username4 = userListGrid.Rows[rowIndex].Cells[0].Text.ToString();

        GridViewRow selectedRow = userListGrid.Rows[rowIndex];
        TableCell lastNameCell = selectedRow.Cells[0];
        string lastName = lastNameCell.Text;

        List<CustomUserRecord> userRoleList = GetUserList(Username);
    }
}

So  I am trying to get the column user ID
User ID | Email
Jack    | Jack@gmail
Diane   | Diana@aol.com

A: I ended up doing this. Probably would have got help but I didn't realize it was a Linkbutton sorry all, thanks for your help.
 int rowIndex = Convert.ToInt32(e.CommandArgument);
 LinkButton Link = (LinkButton)userListGrid.Rows[rowIndex].Cells[0].Controls[0] ;
                string Username = Link.Text;


text:
Q: Unable to get the value entered by user on button click event , value is entered in a dynamically loaded textbox I have few textboxes on a page which are loaded dynamically on change of text in dropdownlist.
The user enters values in these textboxes and clicks on a addnewitem button. In the code behind I want to capture the values entered in these textboxes. But I get the value as empty.
On Pageload mthd there is nothing which is referencing to createdynamiccontrols method.Then I have
    protected override void CreateChildControls()
    {
        base.CreateChildControls();
        CreateDynamicControls();

    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
    }

    protected override object SaveViewState()
    {
        return new Pair(base.SaveViewState(), null);
    }

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(((Pair)savedState).First);

        EnsureChildControls();
    }

 public void CreateDynamicControls()
    {
        Student= ddlStudentschool.SelectedItem.Text.ToString();
        studentcollege= ddlstudentcollege.SelectedValue.ToString();
        int rowPos = 0;

        DynPanel.BorderStyle = BorderStyle.Solid;

Based on the selected of studentschool and studentcollege, the following textboxes & fieldnames will be created
        Label Mynewlabel = new Label();
        Mynewlabel.ID = "lbl" + FldLabel;
        Mynewlabel.Text = FldLabel;
        Mynewlabel.Visible = true;
        Mynewlabel.Font.Bold = true;
        DynPanel.Controls.Add(new LiteralControl(""));
        DynPanel.Controls.Add(Mynewlabel);
        DynPanel.Controls.Add(new LiteralControl("	"));

        if (ControlType == "TextBox")
        {
            int textBoxLength;
            TextBox MynewTextBox = new TextBox();
            MynewTextBox.ID = "txt" + Fldname;

            MynewTextBox.Width = 100;
            MynewTextBox.EnableViewState = true;
            MynewTextBox.Enabled = true;
         did not paste the whole code
       }
   protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
    {
        CreateDynamicControls();
    }

  protected void btnAddItem_Click(object sender, EventArgs e)
    {
        CreateDynamicControls();

        if (DynPanel.Controls != null)
        {
            foreach (Control ctrl in DynPanel.Controls)
            {
                if (ctrl is TextBox)
                {
                    TextBox _txt = DynPanel.FindControl(ctrl.ID) as TextBox;
                    int count = DynPanel.Controls.Count;
                    // txtresult.ID = ctrl.ID;
                    txtresult.Text = ((TextBox)ctrl).Text;
                    TextBox txtPath = (TextBox)ctrl.FindControl("");
                    string result = txtresult.Text;
                }

Firstly i am getting object reference not set to an instance of an object when the createchildcontrols method is called the second time and also if I dont have the createdynamiccontrols method in additem click event, controls are no longer tehre...

A: It probably has to do with how you're loading the control. On post-back you need to reload your dynamic controls in the same position as they were originally loaded. Otherwise the viewstate won't match up and the control state can't be loaded into the control tree. If that doesn't work then please post more code!

A: You need to re-create dynamic control on each postback, see my previous answer to a similar question here


text:
Q: SSH Lost Terminal Colors I have to computers with exactly the same configuration (same PS1 etc...).
When I ssh from A to B the terminal correctly displays PS1 and file type colors (i.e. blue directories, green executables etc.)
But when I ssh from B to A PS1 is set to default and colors disappear. Furthermore, I created public keys to ssh without password from A to B and vice-versa. It works correctly from A to B but it doesn't work from B to A, again I repeated the exact same procedure on both pc:
On Host A
ssh-keygen
ssh-copy-id -i ~/.ssh/id_rsa.pub address.to.host.B

On Host B
ssh-keygen
ssh-copy-id -i ~/.ssh/id_rsa.pub address.to.host.A

What could be the problem?
EDIT:
The problem is that when I ssh from B to A bash is not called in B. But why?

A: the remote .bashrc file is not executed by default when connecting over ssh.
Adding source .bashrc to .bash_profile solved the problem. Still I don't know why it keeps asking for the password.


text:
Q: Automapper reverse map through a function In source Device.cs in simplification I have:
using Assisticant.Collections;

(...)

private ObservableList<Result> _results = new ObservableList<Result>();

public IEnumerable<Result> Results
{
   get { return _results; }
}

public void AddResult(Result result)
{
    _results.Add(result);
}

The destination DeviceDto.cs is:
public List<Result> Results { get; set; }

How should I make configuration for Automapper to make simple direct mapping from source to destination and at the same time reverse mapping of every element through .AddResult(result) function?
(I have to add elements this way due to used library purpose)
What should I add to:
var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Device, DeviceDto>().ReverseMap();
});

_mapper = new Mapper(config);

A: Do not use ReverseMap(), but configure the mapping from DeviceDto to Device explicitly.
Because Device.Results only defines a getter, it will be ignored by AutoMapper during the mapping step. Use the AfterMap method if you need to access source and destination at the same time.
using System.Linq;

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Device, DeviceDto>();
    cfg.CreateMap<DeviceDto, Device>()
        .AfterMap((src, dst) => src.Results.Select(result => dst.AddResult(result)));
});

A: You can use AfterMap:
var config = new MapperConfiguration(
    cfg =>
    {
        cfg.CreateMap<Device, DeviceDto>()
            .ReverseMap()
                .AfterMap((src, dest) =>
                {
                    foreach (Result result in src.Results)
                    {
                        dest.AddResult(result);
                    }
                });
    });


text:
Q: Javascript Regex Replace Multiple Patterns I'm trying to do a replace for every pattern that looks like either:
" - ", // space dash space
" ", // space
"*", // asterisk

and replace it with a space.
I tried:
const name = "Test - number one*"
const regExName = name.replace((\s-\s)|(-)|(\s)|(\*)/g, '_');

Obviously wrong... Help please?

A: Simply use this pattern:
/ - | |\*/g

Online Demo

And here is full code:

const name = "Test - number one*"
const regExName = name.replace(/ - | |\*/g, '_');
document.write(regExName);

A: You are missing the leading /:
name.replace(/(\s-\s)|(-)|(\s)|(\*)/g, '_');
             ^ here


text:
Q: How to scroll on multiple AmCharts simultaneously? I just started using AmCharts and have setup two line plots, one on top of the other, with their respective scrollbars.
Now, I want to "link" the scrollbars of both plots, so that if I move the scrollbar on the chart1, I'll get the same date range on the chart2. I imagine this shouldn't be too difficult with a listener, a get value function and a set value function, but I'm unable to find how to get the start/end values of the scrollbar so that I can play with them.
Any help would be appreciated.
thanks

A: There is a demo for this in the AmCharts Knowledge Base
https://www.amcharts.com/kbase/share-scrollbar-across-several-charts/
This is the code that is syncing the scrollbars, (I have added the annotations):
Create an array to populate with your charts
var charts = [];

Create how ever many charts you need
charts.push(AmCharts.makeChart("chartdiv", chartConfig));
charts.push(AmCharts.makeChart("chartdiv2", chartConfig2));
charts.push(AmCharts.makeChart("chartdiv3", chartConfig3));

Iterate over the charts, adding an event listener for "zoomed" which will share the event handler
for (var x in charts) {
  charts[x].addListener("zoomed", syncZoom);
}

The event handler
function syncZoom(event) {
  for (x in charts) {
    if (charts[x].ignoreZoom) {
      charts[x].ignoreZoom = false;
    }
    if (event.chart != charts[x]) {
      charts[x].ignoreZoom = true;
      charts[x].zoomToDates(event.startDate, event.endDate);
    }
  }
}


text:
Q: What is # next to object(someClass) in var_dump of an object? I have an inference. Am I right? This is the code & its output I used to draw the inference below:
 class a {
    public $var1;
    public $var2;
    }

 $obj0 = new a;
 var_dump($obj0);

 class b {
    public $var1;
    public $var2;
    public $var3;
    }

 $obj1 = new b;
 var_dump($obj1);

 $obj2 = new stdClass;
 var_dump($obj2);

 $obj3 = new stdClass;
 var_dump($obj3);

 $obj4 = new stdClass;
 var_dump($obj4);

 $obj5 = new stdClass;
 var_dump($obj5);

 var_dump(new stdClass);

 $obj6 = new stdClass;
 var_dump($obj6);

The output:
object(a)#1 (2) {
  ["var1"]=> NULL
  ["var2"]=> NULL
}
object(b)#2 (3) {
  ["var1"]=> NULL
  ["var2"]=> NULL
  ["var3"]=> NULL
}
object(stdClass)#3 (0) {

}
object(stdClass)#4 (0) {

}
object(stdClass)#5 (0) {

}
object(stdClass)#6 (0) {

}
object(stdClass)#7 (0) {

}
object(stdClass)#7 (0) {

}

The #<some-number> next to the line object(someClass) in var_dump of an object is actually #<count>. Where,

count is the number of objects / zval's for objects irrespective of which class it belongs to that has been created till now. Which keeps getting incrementing for every object created & gets decremented by 1 when a refcount of a zval reaches zero i.e. Garbage Collection.

Am I right?

A: No, it's an internal reference to the object instance, if you did
var_dump($obj1);

again, it would still be id #2
EDIT
In the case of your
var_dump(new stdClass);

PHP is creating a new instance of stdClass and dumping it using var_dump, giving you instance #7. However, because this instance is transient (you're not assigning it to any variable) it's being destroyed again immediately afterwards, so object id #7 is available again for allocation to the next object that you create with
$obj6 = new stdClass;

A: That number is Z_OBJ_HANDLE_PP(struc) where struc is a zval which leads to Z_OBJVAL(zval).handle which leads to (zval).value.obj.
See as well http://php.net/manual/en/internals2.variables.intro.php
In short I would say it's the object identifier written in decimal form (ref):
php_printf("%sobject(%s)#%d (%d) {\n", COMMON, class_name, Z_OBJ_HANDLE_PP(struc), myht ? zend_hash_num_elements(myht) : 0);

And not the count of objects ever created.


text:
Q: SSRS show a default value of 0 for a date that returns no rows I was hoping you can help me with a problem with SSRS reporting's line graph I'm trying to create.  So right now, I'm querying our database to get a card counts made for ever day.  Each card is a separate row in the database.  Right now, my chart is using the sum of cardCounts as the Y axis and for the X axis it is using the date as the category groups.  Now the problem is that for a couple days, there's no data at all because we didn't create cards on that day.  So rather than the line graph include that day as a 0 value, it's skipping that day altogether (in the pic below, the day of 7/16/2016 is missing completely).  I tried doing it at the data level, but when I do a "isnull" it still doesn't work.  Screenshot of issue
Here is the query I'm using:
SELECT dbo.ProductionSet.PSId,Convert(date,MIN(PSCreateTime)) AS CreateTime,isnull(MAX(dbo.ProductionSet.PSCardsInSet),0) AS CardCount,MAX(PrintJobMaster.PJMBatchid) AS BatchId,
isnull(DATEDIFF(SECOND,MIN(PaperPrintStart.PSTimeOf),MIN(PaperPrintDone.PSTimeOf)),0) AS PaperPrintSecs,
          isnull(nullif(DATEDIFF(Minute,MIN(ProductionSet.PSCreateTime),MIN(PaperCopyDone.PSTimeOf)),0),0) AS SecsToPaperOnPress
    FROM dbo.ProductionSet WITH (NOLOCK)
          LEFT OUTER JOIN PSStats PaperPrintStart WITH (NOLOCK) ON ProductionSet.PSId = PaperPrintStart.PSID AND PaperPrintStart.PSStatTo='1-1' AND PaperPrintStart.PJMID IS NOT NULL
          LEFT OUTER JOIN PSStats PaperPrintDone WITH (NOLOCK) ON ProductionSet.PSId = PaperPrintDone.PSID AND PaperPrintDone.PSStatTo='3-3' AND PaperPrintDone.PJMID IS NOT NULL
          LEFT OUTER JOIN PSStats PaperCopyStart WITH (NOLOCK) ON ProductionSet.PSId = PaperCopyStart.PSID AND PaperCopyStart.PSStatFrom='PA-D'
          LEFT OUTER JOIN PSStats PaperCopyDone WITH (NOLOCK) ON ProductionSet.PSId = PaperCopyDone.PSID AND PaperCopyDone.PSStatTo='PAD-D'
          LEFT OUTER JOIN PSStats EncodingStart WITH (NOLOCK) ON ProductionSet.PSId = EncodingStart.PSID AND EncodingStart.PSStatTo='R'
          LEFT OUTER JOIN PSStats EncodingDone WITH (NOLOCK) ON ProductionSet.PSId = EncodingDone.PSID AND EncodingDone.PSStatTo='M'
          LEFT OUTER JOIN dbo.PrintJobMaster WITH (NOLOCK) ON dbo.PrintJobMaster.PJMPSID=productionset.PSId
WHERE ProductionSet.PSCreateTime >= '7/16/2016' and ProductionSet.PSCreateTime < '7/17/2016'  and PaperCopyDone.PSTimeOf is not null
       GROUP BY ProductionSet.PSID
       ORDER BY MIN(ProductionSet.PSId)

A: Try using this expression in the Values of your chart.
=Sum(
IIF(ISNOTHING(Fields!CardCount.Value),0,Fields!CardCount.Value)
)

It will produce 0 for the dates in x-axis with null y-axis values.

Note that you have two Values series so you have to use the same
  expression for both fields.

Let me know if this helps.


text:
Q: Need a quick regex for a numeric range between 2000 to 9999 I am rather bad at regex's and am unsure of how to do this numeric range.
EDIT: Sorry about being vague, i need to check if the string inputted is between the numeric range 2000 to 9999, it will not have any numbers before or after it.

A: As a regex you can write
[2-9][0-9][0-9][0-9]

or
[2-9][0-9]{3}

or
[2-9]\d{3}

or
[2-9]\p{Digit}{3}

This will give you all numbers between 2000 and 9999 assuming they have no leading zeros. i.e. 002000 or +2000 will not match.
What I would do is
int i = Integer.parseInt(text);
if (2000 <= i && i <= 9999)
   // ok.


text:
Q: Force Send Root CA with Request We have third party API provider that provided an SOAP API. They have provided 3 certificates,

*

*Client Cert

*Intermediate Cert

*Root Cert

All certs are installed locally. They have provided a pfx cert with password. We have uploaded this pfx in SOAP UI tool and run a request it worked. Then we tried the same with .NET request,
var binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
var client = new ServiceReference1.myClient(binding, new EndpointAddress(serviceUrl));
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var certificate = new X509Certificate2(certificateBinary, certificatePassword);
client.ClientCredentials.ClientCertificate.Certificate = certificate;

It failed with handshake failure error.
Then we monitored both SOAP UI traffic and .NET code traffic using WireShark.

Clearly the .NET is not sending Root CA. The problem is that request is rejected by the third party API if Root CA is not present in the request. How can force send ROOT CA.


text:
Q: Cloud build failing on git submodules I have a Unity project in a git repo hosted on VSTS with submodules, I've integrated it the git repo with Unity cloud build.
When Cloud Build tires to do a build it seems to go fine checking everything out until it reaches the modules, it hangs on the line '328: Cloning into 'Assets/MySubmodule'... and just waits there for about an hour before the build fails for taking too long.
I get an error sometimes that goes like:
Username for 'https://mycompany.visualstudio.com': Clone of 'https://mycompany.visualstudio.com/DefaultCollection/_git/mysubmodulerepopath' into submodule path 'Assets/mysubmodule' failed
I'm thinking the issue might be that the submodules are not being referenced as ssh links but directly as https, is there some work around or something I need to do to get them to work?

A:
I'm thinking the issue might be that the submodules are not being referenced as ssh links but directly as https

Then, you can cloning again, this time using ssh.
First, type:
git config --global url."git@github.com:".insteadOf "https://github.com/"

Then clone your repo again (git clone --recursive)

A: Fixed this issue by updating the submodule git urls to use ssh


text:
Q: Auto post (user behalf) on facebook I've been searching and haven't found an answer.
I've a website that has a livetracking service.
I already use the javascript facebook share feed so that users can post on their facebook page their and others activities.
I wonder is at the moment (I know it had been possible in the past) is possible to post on user behalf. I already have a process to get a long lived token.
The goal is to give the ability of auto post when users start/end activities, informing their followers.

A: Update from August 2018 on:
The publish_actions can not be used anymore. It is not possible to post content on a user's profile automatically anymore. Facebook suggests using the share dialog instead, which requires the user's confirmation for every post. Facebook will show a window to the user for approving the post.
Example code for using the share dialog:
FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/',
}, function(response){});

The full documentation with all parameters can be found here:
https://developers.facebook.com/docs/sharing/reference/share-dialog

A third party is only able to post content on behalf of a user if that user has granted permission for doing so.
The first step is to register an app, in case you haven't done it already:
https://developers.facebook.com/apps/
Facebook will show a prompt to the user and ask him for giving permissions to that app. In the Facebook app, you need to ask for publish_actions permissions.
This will give you an access-token to publish posts on the wall of that user in his name.
For doing so you could use the Graph API:
POST graph.facebook.com
     /{user-id}/feed?
     message={message}&
     access_token={access-token}

If you are using the JavaScript SDK, the code could look similar to this:
FB.init({
    appId: 'insert your appID value here',
    cookie: true,
    xfbml: true,
    status: true });

FB.api(
    "/{user-id}/feed",
    "POST",
    {
        "message": "This is a test message"
    },
    function (response) {
      if (response && !response.error) {
        /* handle the result */
      }
    }
);

Here you will find detailed information on the parameter and responses:
https://developers.facebook.com/docs/graph-api/reference/v2.9/user/feed#publish


text:
Q: NGINX reverse proxy to HTTP I have apache behind a NGINX reverse proxy that supports ssl. My backend apache server listens on HTTP only, so I use:
proxy_pass http://realip:8888;

however, this breaks the site because all URLs go to http, and chrome won't allow HTTP to load over HTTPS. How can I set the header as "https://" while sending over "http" to the backend apache server?

A: The best way to fix this is with the backend application. (Without knowing anything about the backend app, I'll try to give a general answer.)
Here are 2 options:

*

*Configure or modify the backend web application to use "https" when building links instead of detecting the protocol actually used.

*(better option) Configure or modify the backend web application to use the X-Forwarded-Proto header when building links. This header would be set in the nginx proxy like so: proxy_set_header X-Forwarded-Proto $scheme; Some installations, such as the Ubuntu packages, provide this in the proxy_params snippet and can be included like so: 'include proxy_params'.
Both of these options require the backend web app to support this specifically or you to be able to modify them to.
If the backend web application is building links based on the protocol used to contact it, like $_SERVER['SERVER_PROTOCOL'] for php, then there is no way to change that with the nginx proxy alone.


text:
Q: Angular Service called twice in lazy loaded modules I am creating an Angular application where I have implemented lazy loading. It is working fine but when ever I am making any HTTP request to the server the action is happening twice.
In my current structure I have created a shared module to store all the common modules and components. I am using ajax service to make all the api calls to backend, AuthTokenService is to store and handle Authentication token-
Feature Module -
import { NgModule, ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

//Importing HTTP Intercepter and services
import { HTTPInterceptorProvider } from '@/core/_HTTP-interceptor';
import { AjaxService, AuthTokenService } from '@/core/_services';

//Importing pipes
import { SummaryPipe } from '@/core/_pipes';

//Externel Plugins Modules
import { NgSelectModule } from '@ng-select/ng-select';

import { AnimatedNumbersComponent } from '@/modules/shared';

@NgModule({
  declarations: [
    AnimatedNumbersComponent,
    //Pipes used are listed here
    SummaryPipe
  ],
  imports: [
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    RouterModule,
    NgSelectModule
  ],
  providers: [
  ],
  exports: [
    AnimatedNumbersComponent,

    ReactiveFormsModule,
    FormsModule,
    NgSelectModule
  ]
})
export class FeatureModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: FeatureModule,
      providers: [
        AjaxService,
        AuthTokenService,
        HTTPInterceptorProvider
      ]
    };
  }
}

App Module -
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule, routingComponents } from './app-routing.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FeatureModule } from './modules/featured/feature.module'

import { DatePipe } from '@angular/common';
import { NgxSpinnerModule } from "ngx-spinner";
import { AppComponent } from '@/app.component';

@NgModule({
  declarations: [
    AppComponent,
    routingComponents
  ],
  imports: [
    HttpClientModule,
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    NgxSpinnerModule, // NGX Spinner
    FeatureModule.forRoot()
  ],
  providers: [
    DatePipe
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

App Routing Module -
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard, SecureOuterPagesGuard, SecureInnerPagesGuard } from "@/core/_guards";

// Home page of the application
import { IndexComponent } from '@/modules/index/index.component';
import {
  LoginComponent,
  RegisterComponent,
  ForgetPasswordComponent,
  ResetPasswordComponent
} from '@/modules/auth';

import {
  PageNotFoundComponent,
  InternalServerErrorComponent
} from '@/modules/shared';

const routes: Routes = [
  {
    path: '',
    component: IndexComponent
  },
  {
    path: 'login',
    component: LoginComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'register',
    component: RegisterComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'forget-password',
    component: ForgetPasswordComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'reset-password',
    component: ResetPasswordComponent,
    canActivate: [SecureOuterPagesGuard]
  },
  {
    path: 'dashboard',
    loadChildren: () => import('./modules/dashboard/dashboard.module').then(m => m.DashboardModule),
    canActivate: [AuthGuard]
  },
  {
    path: 'internal-server-error',
    component: InternalServerErrorComponent
  },
  {
    path: '**',
    component: PageNotFoundComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: []
})
export class AppRoutingModule { }

export const routingComponents = [
  IndexComponent,
  LoginComponent,
  RegisterComponent,
  ForgetPasswordComponent,
  ResetPasswordComponent,
  SessionTimeOutComponent,
  PageNotFoundComponent
]

Ajax Service -
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map, timeout } from "rxjs/operators";

@Injectable()

export class AjaxService {

  constructor(
    private _http: HttpClient,
  ) { }

  apiCall(
    data: any,
    url: any,
    method: 'DELETE' | 'GET' | 'HEAD' | 'POST' | 'JSONP' | 'PUT',
    isRawUrlFormat: boolean = false
  ){
    // Checking if the provide url is in raw format or not
    if (isRawUrlFormat == false) {
      url = environment.API_URL + "/" + url;
    }

    // creating request variable of type Observable so that any component can subscribe it
    let request: Observable<any>;

     // setting methods of request type and passing params (url, data, headeers and observe to access complete response)
     switch (method) {
      case 'GET':
        request = this._http.get(url, { observe: 'response' });
        break;
      case 'POST':
        request = this._http.post(url, data, { observe: 'response' });
        break;
      case 'PUT':
        request = this._http.put(url, data, { observe: 'response' });
        break;
      default:
        request = this._http.request(method, url, { observe: 'response' });
    }

    // returning api result with status, if found any error returns that error
    return request.pipe(
      timeout(environment.AJAX_TIMEOUT),
      map((apiResult : HttpResponse<any>) => {
        const status : number = apiResult.status;
        let responseObject = apiResult.body;
        responseObject.status = status;
        // if found status 202 means has a refreshtoken in response then again setting it in localstorage
        if (status == 202) {
          localStorage.setItem("userToken", apiResult.body.response.data.token);
        }
        return responseObject;
      })
    )
  }
}


text:
Q: Running MSIEXEC on non-administrator login I need to get an msi installed on a number of machines. I've written a script to check the version and deploy if necessary, but it doesn't seem to like the msiexec call. Can msiexec be run from a limited user, or only administrators? Can someone point me in the right direction.
Alternatively, what's a better solution?

A: You need the "Always install with elevated privileges" setting in Group Policy, either as a Domain Policy if you have AD, otherwise as a local policy on the individual PCs themselves.
Find it in User Configuration\Administrative Templates\Windows Components\Windows Installer.


text:
Q: How send file through http from one end point to another end point in spring boot application I am building a spring boot rest API in which. I want to send the file via HTTP from one spring rest API application to another rest API  application and get a response whether the file successfully sends or not.
more explanation about the above scenario
I have 2 spring-rest-API. one running on port 4000 and another on 5000 on the local machine. I want to send a file from 4000 port rest API to 5000 port rest-API via post request and 5000 port rest-API will give a response whether the file successfully received or not. as this process is asynchronous. I also want to know how to handle it asynchronously.
Thanks in advance.

A: REST APIs are not designed to send files. You can send information about where a file is located(like a repository or cloud storage) so that the other end can take it from there, but not the file itself.

A: My little suggestion is u can try to send the file content between the API or like @razvan said. Different port wouldn't be an obstacle to call each other.


text:
Q: how to deploy a statefulset when a pod security policy is in place in kubernetes I am trying to play around with PodSecurityPolicies in kubernetes so pods can't be created if they are using the root user.
This is my psp definition:
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: eks.restrictive
spec:
  hostNetwork: false
  seLinux:
    rule: RunAsAny
  supplementalGroups:
    rule: RunAsAny
  runAsUser:
    rule: MustRunAsNonRoot
  fsGroup:
    rule: RunAsAny
  volumes:
  - '*'

and this is my statefulset definition
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: web
spec:
  selector:
    matchLabels:
      app: nginx # has to match .spec.template.metadata.labels
  serviceName: "nginx"
  replicas: 3 # by default is 1
  template:
    metadata:
      labels:
        app: nginx # has to match .spec.selector.matchLabels
    spec:
      securityContext:
        #only takes integers.
        runAsUser: 1000
      terminationGracePeriodSeconds: 10
      containers:
      - name: nginx
        image: k8s.gcr.io/nginx-slim:0.8
        ports:
        - containerPort: 80
          name: web
        volumeMounts:
        - name: www
          mountPath: /usr/share/nginx/html
  volumeClaimTemplates:
  - metadata:
      name: www
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "my-storage-class"
      resources:
        requests:
          storage: 1Gi

When trying to create this statefulset I get
create Pod web-0 in StatefulSet web failed error: pods "web-0" is forbidden: unable to validate against any pod security policy:

It doesn't specify what policy am I violating, and since I am specifying I want to run this on user 1000, I am not running this as root (Hence my understanding is that this statefulset pod definition is not violating any rules defined in the PSP). There is no USER specified in the Dockerfile used for this image.
The other weird part, is that this works fine for standard pods (kind: Pod, instead of kind:Statefulset), for example, this works just fine, when the same PSP exists:
apiVersion: v1
kind: Pod
metadata:
  name: my-nodejs
spec:
  securityContext:
    runAsUser: 1000
  containers:
    - name: my-node
      image: node
      ports:
        - name: web
          containerPort: 80
          protocol: TCP
      command:
      - /bin/sh
      - -c
      - |
          npm install http-server-g
          npx http-server

What am I missing / doing wrong?

A: You seems to have forgotten about binding this psp to a service account.
You need to apply the following:
cat << EOF | kubectl apply -f-
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: psp-role
rules:
- apiGroups: ['policy']
  resources: ['podsecuritypolicies']
  verbs:     ['use']
  resourceNames:
  - eks.restrictive
EOF

cat << EOF | kubectl apply -f-
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: psp-role-binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: psp-role
subjects:
- kind: ServiceAccount
  name: default
  namespace: default
EOF

If you dont want to use the default account you can create a separate service account and bind the role to it.
Read more about it k8s documentation - pod-security-policy.


text:
Q: I get $ \int fg' \, dx = 2fg + \int fg'\,dx + C $ while performing integration by parts. What did I do wrong? I am reaching a paradox by using integration by parts. I must be going wrong but unable to figure where I went wrong. Can you help me understand what I did wrong here?
We have two differentiable functions $ f(x) $ and $ g(x) $. Now we start with $ \int f(x) g'(x) dx $ and proceed like this:
$$
\int fg' \, dx = fg + \int f'g \, dx + C = fg + fg + \int fg'\,dx + C = 2fg + \int fg'\,dx + C.
$$
What went wrong here?
Update:
As told in the first comment to this post I have made a very silly error. Here is the fix now:
$$
\int fg' \, dx = fg - \int f'g \, dx + C = fg - fg + \int fg'\,dx + C = \int fg'\,dx + C.
$$
So there is no issue.

A: As told in the first comment to this post I have made a very silly error. Here is the fix now:
$$
\int fg' \, dx = fg - \int f'g \, dx + C = fg - fg + \int fg'\,dx + C = \int fg'\,dx + C.
$$


text:
Q: Haskell function with infinite list as argument After poking around the other posts involving infinite lists and my error messages, I still can't solve my issues.
I am just learning Haskell, and I thought that implementing the Newton-Raphson Square Root method would be an interesting first problem. Here is my code:
next_ ::  (Floating a) => a -> a -> a
next_ n x = (x + n/x)/2

repeat_ :: (Floating a) => ( a -> a ) -> a -> [a]
repeat_ f a = a : (repeat_ f (f a))

within :: (Ord a, Floating a) => a -> [a] -> a
within eps (x:xs)
  | (abs (x / b - 1.0)) < eps = b
  | otherwise = within eps (b:bs)
  where b = head xs
        bs = tail xs

The code is compiled by GHCi just fine. eps is the max distance between 2 successive square root approximations before the final answer is returned.
I split the three parts into three functions, with the intention of writing a sqrt function which calls within with repeat_ and next_. I have tested repeat_ and next_, and both of them work as expected. However, when I run within .01 (repeat_ (next_ 2.0) 2.5), I get this error message:
<interactive>:44:1: error:
• Non type-variable argument
    in the constraint: Num ([a] -> a2 -> a1)
  (Use FlexibleContexts to permit this)
• When checking the inferred type
    it :: forall a a1 a2.
          (Num ([a] -> a2 -> a1), Floating a, Floating a1, Ord a1) =>
          a2 -> [a1] -> a1

Reading through the error message and googling it, I am still lost. I have read through the similar questions here and couldn't fix the problem. The issue, I think, is the infinite list as an argument. I know that Haskell is Lazy, so it will only evaluate as many numbers as it needs until the return condition is met. I think that the above implementation is correct (i.e. (x:xs) for the inf. list), but I am not sure. The typeclasses are also an area of concern. After searching and reading, I am still shaky on the typeclass for within. Since the infinite list is being evaluated in the function, does within need a type declaration like repeat_ where it is stated that repeat_ takes in a function?
Any help is much appreciated! Thanks!


text:
Q: Normal basis of $GF(2^4)$ over $GF(2^2)$ I'm reading this paper: Scrutinizing the Tower Field Implementation of the $F(2^8)$
Inverter – with Applications to AES, Camellia, and SM4. It mentioned a sequence of field extensions $F_2 \subseteq F_{2^2} \subseteq F_{2^4} \subseteq F_{2^8}$. Let $r(y) \in F_{2^4}[y], s(z) \in F_{2^2}[z], t(w) \in F_2[w]$ be irreducible polynomials over their respective fields, and let $Y \in F_{2^8}, Z \in F_{2^4}, W \in F_{2^2}$ be roots of $r(y),s(z),t(w)$ over the corresponding fields respectively. Then it obtain a set of normal basis: $[Y^{16},Y]$ is a basis of $F_{2^8}$ over $F_{2^4}$, $[Z^4,Z]$ is a basis of $F_{2^4}$ over $F_{2^2}$, $[W^2,W]$ is a basis of $F_{2^2}$ over $F_{2}$.
But I really don't understand how to get $[Y^{16},Y], [Z^4,Z], [W^2,W]$. HELP!

A: *

*$F_{p^{2n}} = F_{p^n}[x]/(x^2+ax+b)$ for any $x^2+ax+b\in F_{p^n}[x]$ irreducible.

*$F_{p^n}$ is the splitting field of $x^{p^n}-x\in F_p[x]$.

*The $F_{p^n}$-conjugate of $x$ is $x^{p^n}$ and $x,x^{p^n}$ is a normal basis of $F_{p^{2n}}/F_{p^n}$ iff $x,x^{p^n}$ are $F_{p^n}$-linearly independent iff $x^{p^n-1}$ is not in $F_{p^n}$.

If $x^{p^n-1}\in F_{p^n}$,

Then $(x^{p^n-1})^{p^n-1}=1$.
On the other hand $x\in F_{p^{2n}}$ implies that $x^{p^{2n}-1}=1$.
Together this would imply that $x^{\gcd(p^{2n}-1,(p^n-1)^2)}=1$.
Now we assume that $p=2$, then $\gcd(2^{2n}-1,(2^n-1)^2)=2^n-1$ so $x^{2^n-1}=1$ ie. $x\in F_{2^n}$ which is a contradiction.

Whence $x,x^{2^n}$ is always a normal basis.


text:
Q: Attempt to invoke virtual method widget.RecyclerView.setLayoutManager on a null object reference I'm trying to put json array into recyclerview but when i run it, it gives me the
"Attempt to invoke virtual method widget.RecyclerView.setLayoutManager on a null object reference"
This my fragment code :
public class ShopsFragment extends Fragment {

private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;
private List<ShopsData> data_List;
public ShopsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView =  inflater.inflate(R.layout.fragment_shops, container, false);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    data_List = new ArrayList<>();
    StoresBackgroundTask backgroundTask = new StoresBackgroundTask(getActivity());
    backgroundTask.execute();

    return rootView;

}

}
and here is my onPreExecude Code :
    @Override
protected void onPreExecute() {
    recyclerView = (RecyclerView) activity.findViewById(R.id.recycler_view);
    final LinearLayoutManager layoutManager = new LinearLayoutManager(ctx);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new StoresRecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
}

I'm getting the error at the 4th line of the onPreExecude.
what's the problem?

A: Sure, that's because you're trying to retrieve recyclerView from within a method run in a different thread. If recyclerView is a Class variable, just remove the recyclerView = (RecyclerView) activity.findViewById(R.id.recycler_view); line from within the onPreExecute() method.


text:
Q: maven not creating jar correctly, creates folder instead? I have a dependency jReddit.jar in my local repo. When I build my project that has a reference to jReddit in it's pom, I keep getting error when server startup because it can't find jReddit.jar in the target web inf. I check the target web inf, and the jReddit is there, only its a folder and not a jar. It looks like 'jReddit.jar' but it is a folder not a jar. If I copy and paste the actual jar in my server it works, but I need it to build correctly. Inside my local repo the jReddit is there as a jar and looks normal.
I am not sure why this is happening because one day everything was working, then the next I can't build or deploy correctly.
          <dependency>
            <groupId>com.github.jreddit</groupId>
            <artifactId>jreddit</artifactId>
            <version>1.0.5</version>
    </dependency>

I havent changed this since it broke, so I think its fine
whole pom
<?xml version="1.0" encoding="UTF-8"?>
<!--
    JBoss, Home of Professional Open Source
    Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual contributors.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.jreddit.service</groupId>
    <artifactId>jRedditService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>WildFly Quickstarts: jRedditService</name>
    <description>A starter Java EE 7 webapp project for use on JBoss WildFly / WildFly, generated from the jboss-javaee6-webapp archetype</description>

    <url>http://wildfly.org</url>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>

    <properties>
        <!-- Explicitly declaring the source encoding eliminates the following
            message: -->
        <!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
            resources, i.e. build is platform dependent! -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!-- JBoss dependency versions -->
        <version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>

        <!-- Define the version of the JBoss BOMs we want to import to specify
            tested stacks. -->
        <version.jboss.bom>8.2.1.Final</version.jboss.bom>

        <!-- other plugin versions -->
        <version.compiler.plugin>3.1</version.compiler.plugin>
        <version.surefire.plugin>2.16</version.surefire.plugin>
        <version.war.plugin>2.5</version.war.plugin>

        <!-- maven-compiler-plugin -->
        <maven.compiler.target>1.7</maven.compiler.target>
        <maven.compiler.source>1.7</maven.compiler.source>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
                of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
                of artifacts. We use this here so that we always get the correct versions
                of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
                read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
                for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
                stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
                from the Hibernate family of projects) -->
            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>jboss-javaee-7.0-with-tools</artifactId>
                <version>${version.jboss.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.wildfly.bom</groupId>
                <artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
                <version>${version.jboss.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>

              <dependency>
                <groupId>com.github.jreddit</groupId>
                <artifactId>jreddit</artifactId>
                <version>1.0.5</version>
<!--                 <scope>provided</scope>                 -->
        </dependency>

        <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.4</version>
</dependency>
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1</version>
</dependency>

        <!-- First declare the APIs we depend on and need for compilation. All
            of them are provided by JBoss WildFly -->

        <!-- Import the CDI API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>javax.enterprise</groupId>
            <artifactId>cdi-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the Common Annotations API (JSR-250), we use provided scope
            as the API is included in JBoss WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.annotation</groupId>
            <artifactId>jboss-annotations-api_1.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the JAX-RS API, we use provided scope as the API is included
            in JBoss WildFly -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>jaxrs-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the JPA API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Import the EJB API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.ejb</groupId>
            <artifactId>jboss-ejb-api_3.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- JSR-303 (Bean Validation) Implementation -->
        <!-- Provides portable constraints such as @Email -->
        <!-- Hibernate Validator is shipped in JBoss WildFly -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <scope>provided</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- Import the JSF API, we use provided scope as the API is included in
            JBoss WildFly -->
        <dependency>
            <groupId>org.jboss.spec.javax.faces</groupId>
            <artifactId>jboss-jsf-api_2.2_spec</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Now we declare any tools needed -->

        <!-- Annotation processor to generate the JPA 2.0 metamodel classes for
            typesafe criteria queries -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-jpamodelgen</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Annotation processor that raising compilation errors whenever constraint
            annotations are incorrectly used. -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator-annotation-processor</artifactId>
            <scope>provided</scope>
        </dependency>

        <!-- Needed for running tests (you may also use TestNG) -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Optional, but highly recommended -->
        <!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
            JPA from JUnit/TestNG -->
        <dependency>
            <groupId>org.jboss.arquillian.junit</groupId>
            <artifactId>arquillian-junit-container</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.arquillian.protocol</groupId>
            <artifactId>arquillian-protocol-servlet</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <!-- Maven will append the version to the finalName (which is the name
            given to the generated war, and hence the context root) -->
        <finalName>${project.artifactId}</finalName>
        <plugins>

          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
              <archive>
                <manifest>
                <addClasspath>true</addClasspath>
                <mainClass>org.jReddit.service.rest.JaxRsActivator</mainClass>
                <classpathPrefix>dependency-jars/</classpathPrefix>
                </manifest>
              </archive>
            </configuration>
          </plugin>

            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>${version.war.plugin}</version>
                <configuration>
                          <failOnMissingWebXml>false</failOnMissingWebXml>

                    <archive>
                        <manifest>
                          <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>

            <!-- The WildFly plugin deploys your war to a local WildFly container -->
            <!-- To use, run: mvn package wildfly:deploy -->
            <plugin>
                <groupId>org.wildfly.plugins</groupId>
                <artifactId>wildfly-maven-plugin</artifactId>
                <version>${version.wildfly.maven.plugin}</version>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!-- The default profile skips all tests, though you can tune it to run
                just unit tests based on a custom pattern -->
            <!-- Seperate profiles are provided for running all tests, including Arquillian
                tests that execute in the specified container -->
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <artifactId>maven-surefire-plugin</artifactId>
                        <version>${version.surefire.plugin}</version>
                        <configuration>
                            <skip>true</skip>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>

        <profile>

            <!-- An optional Arquillian testing profile that executes tests
                in your WildFly instance -->
            <!--

This profile will start a new WildFly instance, and execute the
                test, shutting it down when done -->

            arq-wildfly-managed

                    org.wildfly
                    wildfly-arquillian-container-managed
                    test

    <profile>
        <!-- An optional Arquillian testing profile that executes tests
            in a remote WildFly instance -->
        <!-- Run with: mvn clean test -Parq-wildfly-remote -->
        <id>arq-wildfly-remote</id>
        <dependencies>
            <dependency>
                <groupId>org.wildfly</groupId>
                <artifactId>wildfly-arquillian-container-remote</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    </profile>

</profiles>

this is relevant jReddits pom
   <parent>
        <groupId>org.sonatype.oss</groupId>
        <artifactId>oss-parent</artifactId>
        <version>7</version>
    </parent>

<groupId>com.github.jreddit</groupId>
<artifactId>jreddit</artifactId>
<version>1.0.5</version>
<name>jReddit</name>
<description>jReddit is a wrapper for the Reddit API written in Java.      </description>
<url>https://github.com/karan/jReddit</url>

Imgur

A: I know this question was asked a long time ago, but since I had this problem, and I didn't find anything on Stackoverflow about this, I'll anwser myself.
Basically this happens when the project of the dependency, that you made the JAR file, is still open on your IDE.
That's because if you make changes on your dependecy you won't need to use the mvn package nor the mvn install, if you close your dependecy project you'll see that the folder will turn into the correctly JAR file as expected, and your main project will read the jar from your m2 folder.


text:
Q: How to display .txt file content via Javascript and change style? I created a tool that can automatically make some text passages bold. It should work like this: I have a .txt file where i want to insert my text that should be formatted. It is named hier.txt.
I then display the content of the txt file via a Javascript on the site.
Everything works until this point. I do have another Javascript that is supposed to then take the text and randomly make some passages of it appear in bold styling.
When i previously tried to insert the text directly in the code, it worked, but it is important that it works with the text file since it is gonna be easier to use.
Here is the code of what I achieved so far:
Script to display the .txt:
$( document ).ready(function() {
  $('#randomText').load("hier.txt");
});

Other Script to make some words bold:
<script>

        target = document.getElementById("randomText");
oldHTML = target.innerHTML;

for (j=0; j<25;j++){
  words = oldHTML.split(" ");
  wordCount = words.length;
  var newHTML = "";
  var highlightStart = Math.floor(Math.random() * wordCount) + 1;
  var highlightLength = Math.floor(Math.random() * 5) + 1;
  for (i = 0; i < wordCount; i++) {
    if (i == highlightStart) newHTML = newHTML + "<b>";
    newHTML = newHTML + words[i] + " ";
    if (i == highlightStart + highlightLength) newHTML = newHTML +          "</b>";
    target.innerHTML = newHTML;
  }//for i
    oldHTML = newHTML;
}// for j

</script>

A: Use .load() callback function to perform tasks after asynchronous AJAX call completes


text:
Q: Flutter: how to set dropdown text with default value and fetch record in datatable according to that value? I am displaying records in data table according to the selected month from drop down, but now I want to display default current month in dropdown and display its data in data table. and then user can able to select value from dropdown too.
i am getting record in datatable by using dropdown selected value index, i increment it by 1 as index starts from zero, i mention my this working in code in as add comments where i do what.
here is my code
String _selectedMonth;
int monthIndex;
int month;

var monthsList=<String>[
      'January',
      'Febuary',
      'March',
      'April',
      'May',
      'June',
      'July',
      'Augest',
      'September',
      'October',
      'November',
      'December'
  ];

  String getdate="";
    void _getDate() {
    final String formattedDateTime =
        DateFormat('MM').format(DateTime.now()).toString();
    _selectedMonth=DateFormat('MMMM').format(DateTime.now());
    setState(() {
      getdate = formattedDateTime;
      print(currentmonth);
     print("date  "+getdate);
    });
  }
   void initState() {
      _userDetails();
      _getDate();
      _getRecord();
  }

 Future<List<History>> _getRecord() async{
   Dio dio=new Dio();
   var data={
     'username':getName,
     'month':month,
     'token':getaccesstoken
   };
   return dio
    .post(localhostUrlAttendanceHistory,data: json.encode(data))
      .then((onResponse) async {
        Map<String, dynamic> map=onResponse.data;
        List<dynamic> data = map['data'];

        for (var h in data) {
          History history = History(
            h["_id"],
            h["Date"],
            h["TimeIn"],
            h["TimeOut"],
          );
          historyList.add(history);
          id=history.id.toString();
          print("id is ");
          print(id);
        }
        return historyList;
      })
      .catchError((onerror){
        print(onerror.toString());

    });
  }

//datatable code

 Widget attendanceHistory(List<History>
    historyList)=>
   Center(
     child:Padding(padding: EdgeInsets.fromLTRB(0, 0, 18, 0),
      child:SingleChildScrollView(
         scrollDirection: Axis.vertical,
        child: SingleChildScrollView(
           scrollDirection: Axis.horizontal,
           child:DataTable(
          decoration: BoxDecoration(border: Border.all(color: Colors.blue[500], width: 2)),
          headingRowColor: MaterialStateColor.resolveWith((states) => Colors.blue[500]),
          headingTextStyle: const TextStyle(fontWeight: FontWeight.bold, color: Colors.white),
          showBottomBorder: true,
          headingRowHeight: 60,
          horizontalMargin: 7,
          columnSpacing: 15,
          dataRowColor: MaterialStateColor.resolveWith((states) => Colors.blue[50]),
          dividerThickness: 4,
          columns: <DataColumn>[
        DataColumn(label: Text("Date")),
        DataColumn(label: Text("Time in")),
        DataColumn(label: Text("Time out"),numeric: true),
        DataColumn(label: Text("   Edit")),
    ],
    rows:
    historyList
      ?.map((element)=>DataRow(
        selected: true ,
      cells: <DataCell>[
      DataCell(Text(element?.date),),
      DataCell(Text(element?.timeIn)),
      DataCell(Text(element?.timeOut,)),
      DataCell(IconButton(icon:Icon(Icons.edit,color: Colors.blue,),onPressed: (){
        _getSelectedRowInfo(element?.id,element?.date,element?.timeIn,element?.timeOut);
      })

void _getSelectedRowInfo(dynamic id,dynamic date,dynamic timein,dynamic timeout) {

    AlertDialog alert = AlertDialog(
    scrollable: true,
    insetPadding: EdgeInsets.symmetric(vertical: 50),
    title: Text("Request to change time",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue[500])),

    content:Container(child: SingleChildScrollView(
      scrollDirection: Axis.vertical,
    child:Column(children:<Widget> [
      TextField(
        decoration: InputDecoration(labelText: date,hintText: "Date"),
        controller:dateController ,

      ),
      TextField(
        decoration: InputDecoration(labelText: timein,hintText: "Time in",icon: Icon(Icons.timer)),
        controller:timeinController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 10:51 PM
                      DateTime parsedTime = DateFormat.jm().parse(pickedTime.format(context).toString());
                      //converting to DateTime so that we can further format on different pattern.
                      print(parsedTime); //output 1970-01-01 22:53:00.000
                      String formattedTime = DateFormat('HH:mm:ss').format(parsedTime);
                      print(formattedTime); //output 14:59:00
                      //DateFormat() is from intl package, you can format the time on any pattern you need.

                      setState(() {
                        timeinController.text = formattedTime; //set the value of text field.
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),
      TextField(
        decoration: InputDecoration(labelText:timeout,hintText: "Time out",icon: Icon(Icons.timer_off)),
        controller:timeoutController ,
        readOnly:true,
        onTap: () async {
                  TimeOfDay pickedTime =  await showTimePicker(
                          initialTime: TimeOfDay.now(),
                          context: context,
                      );
        if(pickedTime != null ){
                      print(pickedTime.format(context));   //output 10:51 PM
                      DateTime parsedTime = DateFormat.jm().parse(pickedTime.format(context).toString());
                      //converting to DateTime so that we can further format on different pattern.
                      print(parsedTime); //output 1970-01-01 22:53:00.000
                      String formattedTime = DateFormat('HH:mm:ss').format(parsedTime);
                      print(formattedTime); //output 14:59:00
                      //DateFormat() is from intl package, you can format the time on any pattern you need.

                      setState(() {
                        timeoutController.text = formattedTime; //set the value of text field.
                      });
                  }else{
                      print("Time is not selected");
                  }
                },
      ),

     ]),
  )

  ),

  actions: [
      FlatButton(
    child: Text("Submit",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue[500],fontSize: 20),),
    onPressed: () {

    getupdatedTime();
    Dio dio=new Dio();
        var data={
          'id': id,
          'token':getaccesstoken,
          'TimeIn': timeinText,
          'TimeOut':timeoutText,

        };
        print("token is "+getaccesstoken);
        print("submit id is  "+id);
        print(data);
        dio
        .put(localhostUrlMarkCorrection, data: json.encode(data))
          .then((onResponse) async {
            Navigator.of(context, rootNavigator: true).pop('dialog');
            dialoguebox();

            print("mark correction");
            print(onResponse.data);
            print(onResponse.statusCode);

          }).catchError((onerror){
            print(onerror.toString());
        });
      }

    )],
  );
      showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );

}

Widget build(BuildContext context) {
    return Scaffold(
      appBar: new MyAppBar(title: Text("My Attendance"),onpressed: (){
       Navigator.push(context, MaterialPageRoute(builder: (context)=>Profile()));
   }),

    drawer:Emp_DrawerCode(),

    body:Stack(children: <Widget>[
//here is my dropdown code
        Container(
        padding: EdgeInsets.fromLTRB(45, 80, 10, 0),
        child:
        DropdownButton<String>(
        value: _selectedMonth==null?null:monthsList[monthIndex],
        items:
          monthsList
          .map<DropdownMenuItem<String>>((String value) {
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value)
            );
          }).toList(),
          hint:Text(
            "Please choose a month",
          ),
          onChanged: (String value) {
            setState(() {
              _selectedMonth=value;  //i am getting month here
              monthIndex = monthsList.indexOf(value);  //then getting its index, so that i can find month in number
              month=monthIndex+1;  //and as index start from 0 so i increment it by 1
              print(month);
              print(_selectedMonth);
            });
          },
        ),
      ),

class History {
  final String id;
  final String date;
  final String timeIn;
  final String timeOut;

  History(this.id,this.date, this.timeIn, this.timeOut);

}

please help, if anyone know how to do this.

A: You can simply get the current month in your initState function and start your index with this number:
(The -1 is because your array starts at 0 and not 1)
  @override
  void initState() {
    monthIndex = DateTime.now().month - 1;
    super.initState();
  }

This will display the current month by default thanks to monthIndex.
Use this variable to display the correct data in your datatable as well.


text:
Q: How to release objects which are created for Excel (C#) I use some objects like workbook, worksheet, app for Excel tasks. After I am done with Excel, I try releasing them by the code below. After all, I still see EXCEL.EXE at Task Manager. Why doesn't it release completely?
My class for Excel tasks:
Excel._Application app = new Excel.Application();
Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Excel._Worksheet worksheet = null;
app.Visible = true;

worksheet.Cells[1, 1] = "test string";

workbook.SaveAs("C:\testfile.xlsx");

object misValue = System.Reflection.Missing.Value;
workbook.Close(true, misValue, misValue);
app.Quit();

releaseObject(worksheet2);
releaseObject(workbook);
releaseObject(app);

releaseObject class:
    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Unable to release the Object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

EXCEL.EXE is still at Task Manager:

A: Already answered see:
How do I properly clean up Excel interop objects?
Basically COM objects are unmanaged objects (duh) and are not released when they go out of scope.
System.Runtime.InteropServices.Marshal.ReleaseComObject() can be used to release them before they get finalized (in the garbage collector), but you have to make sure to keep a reference of all the objects:
excelApp.Worksheets.Open() creates two objects: the collection 'Worksheets' and the 'Worksheet' opened with the Open() method.

A: It's very easy to kill the EXCEL object from the Task Manager using Process, see below & enjoy..
//Kill the all EXCEL obj from the Task Manager(Process)
System.Diagnostics.Process[] objProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL");

if (objProcess.Length > 0)
{
    System.Collections.Hashtable objHashtable = new System.Collections.Hashtable();

    // check to kill the right process
    foreach (System.Diagnostics.Process processInExcel in objProcess)
    {
        if (objHashtable.ContainsKey(processInExcel.Id) == false)
        {
             processInExcel.Kill();
        }
    }
    objProcess = null;
}

//In case of you want to quit what you have created the Excel object from your application //just use below condition in above,

    if(processInExcel.MainWindowTitle.ToString()== "")

A: It's been a while since I've done Office Interop (I actually was using it for Outlook, but the concepts should be the same). The only way I was able to completely release everything was to do this:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Give it a shot....

A: this is a problem that i could not solve. ive seen all of these answers before and i've implemented all of them, and still excel did not close. i had to do things with brute force. what i did was created a BAT file and ran it from my program. here are the contents of the file:
Taskkill /F /IM excel.exe

this will call ALL of your excels running. i would use this if you cannot figure out a different solution.

A: You need to close the excel application by doing like this as it opens excel program in background....
app .Application.Quit();

Add the above line code in your code in following way:
    object misValue = System.Reflection.Missing.Value;
    workbook.Close(true, misValue, misValue);
    app .Application.Quit();
    app.Quit();


text:
Q: How to make a debian package from ubuntu SDK? I have created an App using the Ubuntu SDK and now I can't find a way to package it.
The documentation says the easiest way to do so is using the publish button located on the left bar in ubuntu SDK, but in my case it is greyed out.
What should I do?

A: debian packaging feature is not available for qt creator , If you are intersted , you can create a qt creator plugin for that . currently ubuntu plugin for qtcreator support click packaging , but it is available for qml apps only :-)