问:
how to start new activity from onpostexecute in async task
**I have this three classes. My Mainactivity,newactivity and the one that extends the AsyncTask, Now in one that extends Asynctask I need to start new activity on OnPostExecute() in the AsyncTask. How can I do that? i have done with context but i am getting error from mainactivity executing backgroundtask line but app crashes please help **

This is mainactivity class

```<code>public class MainActivity extends AppCompatActivity {

    Button click;
    //public static TextView data;
    public static LineChart mchart;
    List<Entry> x;
    ArrayList<String> y;
    private fetchdata list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        click=(Button)findViewById(R.id.button);
        mchart=(LineChart)findViewById(R.id.linechart);
        //data=(TextView)findViewById(R.id.fetcheddata);
        list=new fetchdata();
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchdata process=new fetchdata();
                process.execute();

            }
        });

    }
}

 public class fetchdata extends AsyncTask<Void,Void,Void> {
        String data="";
        String dataparsed="";
        String singleparsed="";
        List<Entry> x;
        List<String> y;
        boolean flag=false;

        @Override
        protected Void doInBackground(Void... voids) {

            x = new ArrayList<Entry>();
            y = new ArrayList<String>();
            try {
                URL url=new URL("https://io.adafruit.com/api/v2/Yarev/feeds/pir-sensor/data");
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=httpURLConnection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                String line="";
                while (line!=null)
                {
                    line=bufferedReader.readLine();
                    data=data+line;
                }
                JSONArray JA=new JSONArray(data);
                for(int i=0;i<JA.length();i++)
                {
                    JSONObject JO= (JSONObject) JA.get(i);
                    singleparsed="Value:"+JO.get("value")+"\n"+
                            "Feed key:"+JO.get("feed_key")+"\n"+
                            "Created:"+JO.get("created_at")+"\n";
                    int value=JO.getInt("value");
                    float v1=value;
                    x.add(new Entry(i,v1));
                    dataparsed=dataparsed+singleparsed;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);

            //start new activity?????

        }
        public List<Entry> getList() {
            return x;
        }

    }
</code>```

答:
You have to create constructor with context

```<code>public class fetchdata extends AsyncTask<Void,Void,Void> {
        String data="";
        String dataparsed="";
        String singleparsed="";
        List<Entry> x;
        List<String> y;
        boolean flag=false;

        private WeakReference<Context> contextRef;

        public fetchdata(Context context) {
            contextRef = new WeakReference<>(context);
        }

        @Override
        protected Void doInBackground(Void... voids) {

            x = new ArrayList<Entry>();
            y = new ArrayList<String>();
            try {
                URL url=new URL("https://io.adafruit.com/api/v2/Yarev/feeds/pir-sensor/data");
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=httpURLConnection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                String line="";
                while (line!=null)
                {
                    line=bufferedReader.readLine();
                    data=data+line;
                }
                JSONArray JA=new JSONArray(data);
                for(int i=0;i<JA.length();i++)
                {
                    JSONObject JO= (JSONObject) JA.get(i);
                    singleparsed="Value:"+JO.get("value")+"\n"+
                            "Feed key:"+JO.get("feed_key")+"\n"+
                            "Created:"+JO.get("created_at")+"\n";
                    int value=JO.getInt("value");
                    float v1=value;
                    x.add(new Entry(i,v1));
                    dataparsed=dataparsed+singleparsed;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);

           if (context != null) {
            // start new activity with context
             Intent intent=new Intent(context,NewActivity.class);
             context.startActivity(intent);
           }

        }
        public List<Entry> getList() {
            return x;
        }

    }
</code>```

start your tack:

```<code>new fetchdata(this).execute();
</code>```

Body:
**I have this three classes. My Mainactivity,newactivity and the one that extends the AsyncTask, Now in one that extends Asynctask I need to start new activity on OnPostExecute() in the AsyncTask. How can I do that? i have done with context but i am getting error from mainactivity executing backgroundtask line but app crashes please help **

This is mainactivity class

public class MainActivity extends AppCompatActivity {

    Button click;
    //public static TextView data;
    public static LineChart mchart;
    List<Entry> x;
    ArrayList<String> y;
    private fetchdata list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        click=(Button)findViewById(R.id.button);
        mchart=(LineChart)findViewById(R.id.linechart);
        //data=(TextView)findViewById(R.id.fetcheddata);
        list=new fetchdata();
        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchdata process=new fetchdata();
                process.execute();

            }
        });

    }
}

 public class fetchdata extends AsyncTask<Void,Void,Void> {
        String data="";
        String dataparsed="";
        String singleparsed="";
        List<Entry> x;
        List<String> y;
        boolean flag=false;

        @Override
        protected Void doInBackground(Void... voids) {

            x = new ArrayList<Entry>();
            y = new ArrayList<String>();
            try {
                URL url=new URL("https://io.adafruit.com/api/v2/Yarev/feeds/pir-sensor/data");
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=httpURLConnection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                String line="";
                while (line!=null)
                {
                    line=bufferedReader.readLine();
                    data=data+line;
                }
                JSONArray JA=new JSONArray(data);
                for(int i=0;i<JA.length();i++)
                {
                    JSONObject JO= (JSONObject) JA.get(i);
                    singleparsed="Value:"+JO.get("value")+"\n"+
                            "Feed key:"+JO.get("feed_key")+"\n"+
                            "Created:"+JO.get("created_at")+"\n";
                    int value=JO.getInt("value");
                    float v1=value;
                    x.add(new Entry(i,v1));
                    dataparsed=dataparsed+singleparsed;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);

            //start new activity?????

        }
        public List<Entry> getList() {
            return x;
        }

    }

Body:
You have to create constructor with context

public class fetchdata extends AsyncTask<Void,Void,Void> {
        String data="";
        String dataparsed="";
        String singleparsed="";
        List<Entry> x;
        List<String> y;
        boolean flag=false;

        private WeakReference<Context> contextRef;

        public fetchdata(Context context) {
            contextRef = new WeakReference<>(context);
        }

        @Override
        protected Void doInBackground(Void... voids) {

            x = new ArrayList<Entry>();
            y = new ArrayList<String>();
            try {
                URL url=new URL("https://io.adafruit.com/api/v2/Yarev/feeds/pir-sensor/data");
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                InputStream inputStream=httpURLConnection.getInputStream();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                String line="";
                while (line!=null)
                {
                    line=bufferedReader.readLine();
                    data=data+line;
                }
                JSONArray JA=new JSONArray(data);
                for(int i=0;i<JA.length();i++)
                {
                    JSONObject JO= (JSONObject) JA.get(i);
                    singleparsed="Value:"+JO.get("value")+"\n"+
                            "Feed key:"+JO.get("feed_key")+"\n"+
                            "Created:"+JO.get("created_at")+"\n";
                    int value=JO.getInt("value");
                    float v1=value;
                    x.add(new Entry(i,v1));
                    dataparsed=dataparsed+singleparsed;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            super.onPostExecute(aVoid);

           if (context != null) {
            // start new activity with context
             Intent intent=new Intent(context,NewActivity.class);
             context.startActivity(intent);
           }

        }
        public List<Entry> getList() {
            return x;
        }

    }

start your tack:

new fetchdata(this).execute();


来源: stackexchange

问:
how to overcome error in images array in javascript
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedImage" style="width:800px; height:500px;float:left;
border: 1px solid black">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html></code>```

I expect the output to be the image I click on, but the actual output is the 7th image of my array

答:
Instead of appending a new child to the expandedImage div why don't you create a new image tag inside expanded image div with the id as expandedImage and change the src of that image on each image scroll bar click.

Hope this helps.

Here is working JSFiddle link

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "https://www.technology-solved.com/wp-content/uploads/2019/03/password-best-practices-image.png",
  "https://mycomputerexperts.net/wp-content/uploads/2018/04/webbrowsing.jpg",
  "https://www.royaloakindia.com/uploads/ROYIND-royaloak-amber-computer-table-small-800x50072.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (let i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    // console.log(img);
    document.getElementById('expandedImage').src = image[i];
  },false);
  div.appendChild(img);
  // img = null;
}

// Default image
document.getElementById('expandedImage').src = image[0];

// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#expandedWrapper {
  width: 100vw;
  max-width: 800px;
  max-height: 500px;
  border: 1px solid black;
  margin: auto;
}</code>```

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" src='index.css'>

</body
```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to insert images (at present there are 7 images)into an array using a for loop and preview(display) those images in a scroll bar. the particular image from the scroll bar on click should appear in the given div.(the should be expanded to the size of the div)
this is for a certificate generator

this js code I triedenter image description here so far

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "themes/theme1.jpg",
  "themes/theme2.jpg",
  "themes/theme3.jpg",
  "themes/theme4.jpg",
  "themes/theme5.jpg",
  "themes/theme6.jpg",
  "themes/theme7.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    console.log(img);
    document.getElementById('expandedImage').appendChild(img);
  },false);
  div.appendChild(img);
  // img = null;
}
// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }

<!DOCTYPE html>

<link rel="stylesheet" type="text/css" src='index.css'>

</body

I expect the output to be the image I click on, but the actual output is the 7th image of my array

Body:
Instead of appending a new child to the expandedImage div why don't you create a new image tag inside expanded image div with the id as expandedImage and change the src of that image on each image scroll bar click.

Hope this helps.

Here is working JSFiddle link

// var div = document.createElement("div");
// div.style.width = "300px";
// div.style.height = "300px";
// div.style.background = "red";
// document.getElementById("con").appendChild(div);
var image=
[
  "https://www.technology-solved.com/wp-content/uploads/2019/03/password-best-practices-image.png",
  "https://mycomputerexperts.net/wp-content/uploads/2018/04/webbrowsing.jpg",
  "https://www.royaloakindia.com/uploads/ROYIND-royaloak-amber-computer-table-small-800x50072.jpg"
];
var arrayLength=image.length;
var i;
var div = document.getElementById("main");
for (let i =0;i<arrayLength;i++)
{
  var img=document.createElement("img");
  img.setAttribute("src",image[i]);
  img.setAttribute("width","100");
  img.setAttribute("height","100");
  img.addEventListener('click', function click(event) {
    // console.log(img);
    document.getElementById('expandedImage').src = image[i];
  },false);
  div.appendChild(img);
  // img = null;
}

// Default image
document.getElementById('expandedImage').src = image[0];

// function myFunction(img) {
//   var expandImg = document.getElementById("expandedImg");
//   var main = document.getElementById("main");
//   expandImg.src = img.src;
//   expandImg.parentElement.style.display = "block";
// }

#expandedWrapper {
  width: 100vw;
  max-width: 800px;
  max-height: 500px;
  border: 1px solid black;
  margin: auto;
}

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" src='index.css'>
</head>
<body>
  <div id="expandedWrapper">
    <img id="expandedImage" src="">
  </div>
  <!-- <div id="con"></div> -->
  <div id="main" style="width:150px; height: 500px; overflow-y:
scroll;float:right">
  </div>
  <script src="index.js"></script>
</body
</html>


问:
html class names... but not really?
Looking at the sourcecode for a website i see in th html tag all this stuff in the class tag

```<code>  class=" yui3-js-enabled
      js
      flexbox
      canvas
      canvastext
      webgl
      no-touch
      hashchange
      history
      draganddrop
      rgba
      hsla
      multiplebgs
      backgroundsize
      borderimage
      borderradius
      boxshadow
      textshadow
      opacity
      cssanimations
      csscolumns
      cssgradients
      cssreflections
      csstransforms
      no-csstransforms3d
      csstransitions
      video
      audio
      svg
      inlinesvg
      svgclippaths
      wf-futurapt-n4-active
      wf-futurapt-n5-active
      wf-bebaskai-n4-active
      wf-futurapt-n7-active
      wf-hypatiasanspro-n2-active
      wf-hypatiasanspro-n4-active
      wf-hypatiasanspro-n6-active
      wf-hypatiasanspro-n7-active
      wf-futurapt-i4-active
      wf-futurapt-n3-active
      wf-futurapt-i5-active
      wf-futurapt-i7-active wf-active"
</code>```

what on earth is all this stuff? is it necessary?

For example, I know what rgba is in terms of using it for say a background like

```<code>#p1 {background-color:rgba(255,0,0,0.3);} /* red with opacity*/
</code>```

but what does it do if you just put

```<code><html class="rgba">
</code>```

答:
Many of those are just marker classes indicating browser support for various features.

These classes get added by javascript that does tests on page load to see what features are supported in this particular browser.

This allows the page or app to adapt to the environment it's in. For example, you might have css rules that style a component differently on the basis of whether flexbox is supported:

html.flexbox .myComponent {
  display: flex; /* flex supported. use it. */
}

html:not(.flexbox) .myComponent {
  display: block; /* no flex support. do something else. */
}
```

Title: html class names... but not really?

Body:
Looking at the sourcecode for a website i see in th html tag all this stuff in the class tag

  class=" yui3-js-enabled
      js
      flexbox
      canvas
      canvastext
      webgl
      no-touch
      hashchange
      history
      draganddrop
      rgba
      hsla
      multiplebgs
      backgroundsize
      borderimage
      borderradius
      boxshadow
      textshadow
      opacity
      cssanimations
      csscolumns
      cssgradients
      cssreflections
      csstransforms
      no-csstransforms3d
      csstransitions
      video
      audio
      svg
      inlinesvg
      svgclippaths
      wf-futurapt-n4-active
      wf-futurapt-n5-active
      wf-bebaskai-n4-active
      wf-futurapt-n7-active
      wf-hypatiasanspro-n2-active
      wf-hypatiasanspro-n4-active
      wf-hypatiasanspro-n6-active
      wf-hypatiasanspro-n7-active
      wf-futurapt-i4-active
      wf-futurapt-n3-active
      wf-futurapt-i5-active
      wf-futurapt-i7-active wf-active"

what on earth is all this stuff? is it necessary?

For example, I know what rgba is in terms of using it for say a background like

#p1 {background-color:rgba(255,0,0,0.3);} /* red with opacity*/

but what does it do if you just put


问:
JSONDecodeError: Expecting value: line 1 column 1 (char 0) using Translate API
While parsing a large text, and translating English language into Hindi, this error arises.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have tried initializing the api in every loop. Still no result. Tried again after 2 days, the error still arises. How to know if my IP is getting blocked?

```<code>eng_words= []
for i in nltk_tokens:
    translator = Translator()
    langs = translator.detect(i)
    if all( [langs.lang == "en", langs.confidence > 0.91] ):
        eng_words.append(i)
    else:
        language = translator.translate(i, dest='hi')
        word = language.text

 Error :
 <ipython-input-12-a89f1985a6a7> in detect_lang(nltk_tokens)
  4     translator = Translator()
  5     for i in nltk_tokens:
  ----> 6         langs = translator.detect(i)
  7         if all( [langs.lang == "en", langs.confidence > 0.91] ):
  8             eng_words.append(i)

  JSONDecodeError: Expecting value: line 1 column 1 (char 0)
</code>```

答:
I'm pretty sure your IP would have gotten blocked from too many requests(Google has a translate API that costs money to use so they want to stop free usage from other apis). The normal way to check if you are blocked is to check if you get a 5xx HTTP error response.

GoogleTrans API Error - Expecting value: line 1 column 1 (char 0)

Body:
While parsing a large text, and translating English language into Hindi, this error arises.
JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I have tried initializing the api in every loop. Still no result. Tried again after 2 days, the error still arises. How to know if my IP is getting blocked?

eng_words= []
for i in nltk_tokens:
    translator = Translator()
    langs = translator.detect(i)
    if all( [langs.lang == "en", langs.confidence > 0.91] ):
        eng_words.append(i)
    else:
        language = translator.translate(i, dest='hi')
        word = language.text

 Error :
 <ipython-input-12-a89f1985a6a7> in detect_lang(nltk_tokens)
  4     translator = Translator()
  5     for i in nltk_tokens:
  ----> 6         langs = translator.detect(i)
  7         if all( [langs.lang == "en", langs.confidence > 0.91] ):
  8             eng_words.append(i)

  JSONDecodeError: Expecting value: line 1 column 1 (char 0)


问:
Using different compilers - what does that do?
By my understanding compilers like mingw, clang, mvs c++ simply take source code written in C++ and try to generate senseful object code and maybe create an executeable that may or may not follow the developer's intentions.

However I noticed that for example OpenCV may cause linkage errors, if OpenCV and the code using it were compiled by different compilers. Why is that? What does using different compilers accomplish?

答:
Why is that? What does using different compilers accomplish?

Well, using different compilers might accomplish using different (and incompatible) ABI's.

In general the libraries you use should be compiled that these are compatible with your target compiler (linker) ABI.


问:
Setup Mailgun with Cloudflare subdomain
I'm trying to setup my domain to receive emails through Mailgun and Cloudflare, and i think i'm really closest but can't make it work.

In Mailgun, i've all DNS verified:

I think the problem is in Cloudflare, configuring the subdomain (that Mailgun suggest me to create mg.mydomain.com)

I have not got any record related with the subdomain (mg.mydomain.com). Is any change i'm something?

Also, I already setup a Route in mailgun to redirect incoming emails to my email address.

Thanks in advance!

答: For the CNAME record, you just need to make sure that the status is configured as 'DNS Only' (the little cloud on the right is grey)

ContentLicense: CC BY-SA 3.0

Title: Setup Mailgun with Cloudflare subdomain


问:
Reduce spacing between buttons and image on mobile devices
I'm serving 2 images, one for big screens and other for mobile devices on this site:

stickersgallito.pe (In case you need another css class)

The image for mobile devices is way down than desired. I can make the image go up with: top: -40px; but this generates a gap between the green banner and the image.

CSS class:

```<code>.my_home_banner_image {
         bottom: 0;
         top: 0;
         position: relative;
         z-index: 0;
         width: 100%;
         display: block;
         margin-right: auto;
         margin-left: 0px;
 }
</code>```

Gap:

I'd like to:

1) get the image closer to the orange button by 40px.

2) make more space between blue and orange buttons (BONUS).

Complete MediaQuery:

```<code>@media (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 100%;
        display: block;
        margin-right: auto;
        margin-left: 0px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}
</code>```

Codepen

https://codepen.io/anon/pen/mYaRKO

答:
I offer you a new structure.
1) Change the tags:

old tags:

```<code><div class="container-fluid my_home_banner my_header_bg_color">
    <div class="row">
        <div class="col-md-6 my_home_banner-left">
            <br>
            <br>
            <div class="my_home_banner_left">

                <div class="my_home_banner_lef_text">
                    <p class="my_home_banner_title">Stickers Personalizados</p>
                    <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
                </div>
                <div class="row ">
                    <div class="col-md-6">
                        <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
                    </div>
                    <br>
                    <div class="col-md-6">
                        <a href="/muestras/"
                           class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
                    </div>
                </div>
            </div>
            <br>
            <br>
        </div>
        <div class="col-md-6">
            <picture>
                <source media="(max-width: 480px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_mobiles.png">
                <source media="(max-width: 2056px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
                <img class="my_home_banner_image" src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
            </picture>
        </div>
    </div>
</div>
</code>```

NEW:

```<code>  <div class="container-fluid my_home_banner my_header_bg_color homebanner">
    <div class="row">
      <div class="col-md-6 my_home_banner-left">
        <br>
        <br>
        <div class="my_home_banner_left">

          <div class="my_home_banner_lef_text">
            <p class="my_home_banner_title">Stickers Personalizados</p>
            <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
          </div>
          <div class="row ">
            <div class="col-md-6">
              <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
            </div>
            <br>
            <div class="col-md-6">
              <a href="/muestras/" class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
            </div>
          </div>
        </div>
        <br>
        <br>
      </div>

    </div>
  </div>
</code>```

2) CSS:

```<code>.homebanner {
    background-image: url(https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png);
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 50%;
    background-position: 100% 100%;
}
@media (max-width: 1280px) {
.homebanner {
    background-size: 75%;
}
}
@media (max-width: 991px) {
.homebanner {
    background-size: 100%;
}
}
@media (max-width: 767px) {
.homebanner {
    padding-bottom: 36%;
    background-size: 80%;
    background-position: 50% 100%;
}
}
@media (max-width: 667px) {
.homebanner {
    padding-bottom: 39%;
    background-size: 90%;
    background-position: 50% 100%;
}
}
@media (max-width: 480px) {
.homebanner {
    padding-bottom: 49%;
    background-size: 100%;
    background-position: 50% 94%;
}
}
</code>```

Working method:

.homebanner {
    background-image: url(https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png);
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 50%;
    background-position: 100% 100%;
}
@media (max-width: 1280px) {
.homebanner {
    background-size: 75%;
}
}
@media (max-width: 991px) {
.homebanner {
    background-size: 100%;
}
}
@media (max-width: 767px) {
.homebanner {
    padding-bottom: 36%;
    background-size: 80%;
    background-position: 50% 100%;
}
}
@media (max-width: 667px) {
.homebanner {
    padding-bottom: 39%;
    background-size: 90%;
    background-position: 50% 100%;
}
}
@media (max-width: 480px) {
.homebanner {
    padding-bottom: 49%;
    background-size: 100%;
    background-position: 50% 94%;
}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Stickers Gallito Perú">
  <meta name="google-site-verification" content="fGkwUY2RcijkVzB6DiwIuAToP1y5xw8ECXQQabRAOIM" />
  <link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/custom.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/navbar.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/header.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/preloader.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/loader.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/footer.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/size-quantity-styles.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
  <link rel="shortcut icon" type="image/png" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/gallito_favicon.png" />

  <title>Stickers Gallito</title>

</head>

<body>
  <!-- Google Tag Manager (noscript) -->
  <noscript>
    <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TPXWL88"
            height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="general-container">

  </div>

  <nav class="navbar navbar-expand-md navbar-dark fixed-top navbar-bg">
      <img src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/stickers_gallito_logo.png" width="20px" height="30px">
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          Stickers <span class="sr-only">(current)</span>
        </li>

      </ul>

      <ul class="navbar-nav ml-auto">

        <li class="nav-item active">
          <i class="fas fa-shopping-cart"
                                                    style="color:white !important;"></i> ( 0)

        </li>

        <li class="nav-item active">
          <i class="fas fa-user-circle"></i> ogonzales
          <div class="dropdown-menu dropdown-menu-right">
            Historial de compras
          </div>

        </li>
        <li class="nav-item active">
          Salir <i class="fas fa-sign-out-alt"></i>
        </li>

      </ul>
    </div>
  </nav>

  <br>

  <div class="container-fluid my_home_banner my_header_bg_color homebanner">
    <div class="row">
      <div class="col-md-6 my_home_banner-left">
        <br>
        <br>
        <div class="my_home_banner_left">

          <div class="my_home_banner_lef_text">
            <p class="my_home_banner_title">Stickers Personalizados</p>
            <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
          </div>
          <div class="row ">
            <div class="col-md-6">
              Comprar
            </div>
            <br>
            <div class="col-md-6">
              Muestras
            </div>
          </div>
        </div>
        <br>
        <br>
      </div>

    </div>
  </div></code>```

It remains only to edit it.

Heading

Body:
I'm serving 2 images, one for big screens and other for mobile devices on this site:

stickersgallito.pe (In case you need another css class)

The image for mobile devices is way down than desired. I can make the image go up with: top: -40px; but this generates a gap between the green banner and the image.

CSS class:

.my_home_banner_image {
         bottom: 0;
         top: 0;
         position: relative;
         z-index: 0;
         width: 100%;
         display: block;
         margin-right: auto;
         margin-left: 0px;
 }

Gap:

I'd like to:

1) get the image closer to the orange button by 40px.

2) make more space between blue and orange buttons (BONUS).

Complete MediaQuery:

@media (max-width: 480px) {
    /* smartphones, iPhone, portrait 480x320 phones */
    .my_home_banner {
        bottom: 0;
        margin-right: 8%;
        z-index: -600;
    }

    .productos_finales_home img {

        padding-bottom: 15px;
    }

    .my_home_banner_image {

        bottom: 0;
        top: 0;
        position: relative;
        z-index: 0;
        width: 100%;
        display: block;
        margin-right: auto;
        margin-left: 0px;
    }

    .my_home_banner_title {
        color: white;
        font-size: 36px;
        font-weight: bold;
    }

    .my_home_banner_subtitle {
        margin-top: 0%;
        padding-top: 0%;
    }

    .btn, h2, p {
        margin-bottom: 10px;
    }

    .btn-comentario {
        text-decoration: none;
        background-color: #969696;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        cursor: pointer;
        color: #fff;
        font-weight: 700;
        font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        text-shadow: 0 -1px 0 rgba(0, 0, 0, .25);
        letter-spacing: 0;
        line-height: 1.2;
        -webkit-font-smoothing: antialiased;
        -webkit-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -ms-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -moz-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        -o-box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        box-shadow: inset 0 -2px 0 rgba(0, 0, 0, .15);
        background-image: linear-gradient(to bottom, rgba(255, 255, 255, .09) 0%, rgba(0, 0, 0, .09) 100%);
        font-size: 1.4rem;
        padding: 22px 30px;
        border-radius: 6px;
        border: none;
    }

.my_home_banner_left {
    margin-left: 10px;
    z-index: 100;
}

.stickers_referenciales {
    margin-bottom: 5px;
}

}

Codepen

https://codepen.io/anon/pen/mYaRKO

Body:
I offer you a new structure.
1) Change the tags:

old tags:

<div class="container-fluid my_home_banner my_header_bg_color">
    <div class="row">
        <div class="col-md-6 my_home_banner-left">
            <br>
            <br>
            <div class="my_home_banner_left">

                <div class="my_home_banner_lef_text">
                    <p class="my_home_banner_title">Stickers Personalizados</p>
                    <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
                </div>
                <div class="row ">
                    <div class="col-md-6">
                        <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
                    </div>
                    <br>
                    <div class="col-md-6">
                        <a href="/muestras/"
                           class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
                    </div>
                </div>
            </div>
            <br>
            <br>
        </div>
        <div class="col-md-6">
            <picture>
                <source media="(max-width: 480px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_mobiles.png">
                <source media="(max-width: 2056px)" srcset="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
                <img class="my_home_banner_image" src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png">
            </picture>
        </div>
    </div>
</div>

NEW:

  <div class="container-fluid my_home_banner my_header_bg_color homebanner">
    <div class="row">
      <div class="col-md-6 my_home_banner-left">
        <br>
        <br>
        <div class="my_home_banner_left">

          <div class="my_home_banner_lef_text">
            <p class="my_home_banner_title">Stickers Personalizados</p>
            <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
          </div>
          <div class="row ">
            <div class="col-md-6">
              <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
            </div>
            <br>
            <div class="col-md-6">
              <a href="/muestras/" class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
            </div>
          </div>
        </div>
        <br>
        <br>
      </div>

    </div>
  </div>

2) CSS:

.homebanner {
    background-image: url(https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png);
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 50%;
    background-position: 100% 100%;
}
@media (max-width: 1280px) {
.homebanner {
    background-size: 75%;
}
}
@media (max-width: 991px) {
.homebanner {
    background-size: 100%;
}
}
@media (max-width: 767px) {
.homebanner {
    padding-bottom: 36%;
    background-size: 80%;
    background-position: 50% 100%;
}
}
@media (max-width: 667px) {
.homebanner {
    padding-bottom: 39%;
    background-size: 90%;
    background-position: 50% 100%;
}
}
@media (max-width: 480px) {
.homebanner {
    padding-bottom: 49%;
    background-size: 100%;
    background-position: 50% 94%;
}
}

Working method:

.homebanner {
    background-image: url(https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/home/banner_home_lion.png);
    width: 100%;
    height: 100%;
    background-repeat: no-repeat;
    background-size: 50%;
    background-position: 100% 100%;
}
@media (max-width: 1280px) {
.homebanner {
    background-size: 75%;
}
}
@media (max-width: 991px) {
.homebanner {
    background-size: 100%;
}
}
@media (max-width: 767px) {
.homebanner {
    padding-bottom: 36%;
    background-size: 80%;
    background-position: 50% 100%;
}
}
@media (max-width: 667px) {
.homebanner {
    padding-bottom: 39%;
    background-size: 90%;
    background-position: 50% 100%;
}
}
@media (max-width: 480px) {
.homebanner {
    padding-bottom: 49%;
    background-size: 100%;
    background-position: 50% 94%;
}
}

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Stickers Gallito Perú">
  <meta name="google-site-verification" content="fGkwUY2RcijkVzB6DiwIuAToP1y5xw8ECXQQabRAOIM" />
  <link href="https://fonts.googleapis.com/css?family=Bree+Serif" rel="stylesheet">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/custom.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/home.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/navbar.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/header.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/preloader.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/loader.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/footer.css">
  <link rel="stylesheet" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/css/size-quantity-styles.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
  <link rel="shortcut icon" type="image/png" href="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/gallito_favicon.png" />

  <title>Stickers Gallito</title>

</head>

<body>
  <!-- Google Tag Manager (noscript) -->
  <noscript>
    <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-TPXWL88"
            height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div class="general-container">

  </div>

  <nav class="navbar navbar-expand-md navbar-dark fixed-top navbar-bg">
    <a class="navbar-brand" href="/">&emsp;&emsp;<img src="https://stickers-gallito-uploaded-files.s3.amazonaws.com/static/img/stickers_gallito_logo.png" width="20px" height="30px"></a>
    <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarCollapse">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="/stickers">Stickers <span class="sr-only">(current)</span></a>
        </li>

      </ul>

      <ul class="navbar-nav ml-auto">

        <li class="nav-item active">
          <a class="nav-link" href="/carrito_de_compras/"><i class="fas fa-shopping-cart"
                                                    style="color:white !important;"></i> ( 0)</a>

        </li>

        <li class="nav-item active">
          <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fas fa-user-circle"></i> ogonzales</a>
          <div class="dropdown-menu dropdown-menu-right">
            <a href="/ordenes/historial_de_compras/" class="dropdown-item">Historial de compras</a>
          </div>

        </li>
        <li class="nav-item active">
          <a class="nav-link" href="/salir/">Salir <i class="fas fa-sign-out-alt"></i></a>
        </li>

      </ul>
    </div>
  </nav>

  <br>

  <div class="container-fluid my_home_banner my_header_bg_color homebanner">
    <div class="row">
      <div class="col-md-6 my_home_banner-left">
        <br>
        <br>
        <div class="my_home_banner_left">

          <div class="my_home_banner_lef_text">
            <p class="my_home_banner_title">Stickers Personalizados</p>
            <p class="my_home_banner_subtitle my_title"><b>Fácil de ordenar por internet.</b> <br><b> Envíos a todo el Perú.</b></p>
          </div>
          <div class="row ">
            <div class="col-md-6">
              <a href="stickers" class="my_home_buttons btn btn-azul text-white btn-block">Comprar</a>
            </div>
            <br>
            <div class="col-md-6">
              <a href="/muestras/" class="my_home_buttons btn btn-naranja text-white btn-block">Muestras</a>
            </div>
          </div>
        </div>
        <br>
        <br>
      </div>

    </div>
  </div>

It remains only to edit it.

Heading


问:
How to calculate profit formula with multiple user input text
I'm trying to make a simple calculation formula but I don't know how to add all the variables simultaneously.

I already tried this but it is giving an error and is being super inaccurate.

```<code>var fee :Int = Int(0.866)
var otherFee:Int = Int(0.30)

@IBAction func calculateProfit(_ sender: Any) {
    let sold = Int(soldTextField.text!)!
    let paid = Int(paidTextField.text!)!
    let shipping = Int(shippingTextField.text!)!

    profitTotal.text = String(sold * fee - otherFee - paid - shipping )
}
</code>```

I suspect that when I hit the button it will multiply, subtract, subtract simultaneously.

答:
```<code>var fee :Int = Int(0.866)
var otherFee:Int = Int(0.30)
</code>```

Now both values are 0. And multiplying other values with this will return 0. Don't use Int for such calculations. Use Double like

```<code>var fee = 0.866
var otherFee = 0.30

@IBAction func calculateProfit(_ sender: Any) {
    let sold = Double(soldTextField.text!) ?? 0
    let paid = Double(paidTextField.text!) ?? 0
    let shipping = Double(shippingTextField.text!) ?? 0

    profitTotal.text = String(sold * fee - otherFee - paid - shipping)
}
</code>```

Body:
I'm trying to make a simple calculation formula but I don't know how to add all the variables simultaneously.

I already tried this but it is giving an error and is being super inaccurate.

var fee :Int = Int(0.866)
var otherFee:Int = Int(0.30)

@IBAction func calculateProfit(_ sender: Any) {
    let sold = Int(soldTextField.text!)!
    let paid = Int(paidTextField.text!)!
    let shipping = Int(shippingTextField.text!)!

    profitTotal.text = String(sold * fee - otherFee - paid - shipping )
}

I suspect that when I hit the button it will multiply, subtract, subtract simultaneously.

Body:
var fee :Int = Int(0.866)
var otherFee:Int = Int(0.30)

Now both values are 0. And multiplying other values with this will return 0. Don't use Int for such calculations. Use Double like

var fee = 0.866
var otherFee = 0.30

@IBAction func calculateProfit(_ sender: Any) {
    let sold = Double(soldTextField.text!) ?? 0
    let paid = Double(paidTextField.text!) ?? 0
    let shipping = Double(shippingTextField.text!) ?? 0

    profitTotal.text = String(sold * fee - otherFee - paid - shipping)
}


问:
Function to insert text line by line from a file into string array passed by pointer
I'm trying to create a function read_lines that takes a file *fp, a pointer to char** lines, and pointer to int num_lines. The function should insert each line of text into lines, and increase num_lines to however many lines the file has.

Its probably really simple but I've been trying to insert the text for several hours now.

This is what main.c would look like. Everything but read_lines is already defined and working.

```<code>int main(int argc, char* argv[]){

    char** lines = NULL;
    int num_lines = 0;
    FILE* fp = validate_input(argc, argv);
    read_lines(fp, &lines, &num_lines);
    print_lines(lines, num_lines);
    free_lines(lines, num_lines);
    fclose(fp);

    return 0;
}
</code>```

This is one of my attempts at trying to append lines, but I couldn't figure it out.

read_lines.c

```<code>void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int i;
    int N = 0;
    char s[200];
    for (i=0; i<3; i++)
    {
        while(fgets(s, 200, fp)!=NULL){N++;}
        char strings[50][200];

        rewind(fp);
        fgets(s, 200, fp);
        strcpy(lines[i],s);
    }

}
</code>```

I'd appreciate any help at solving this, thanks.

答:
A solution (without headers and error checking for readability):

```<code>void read_lines(FILE *stream, char ***lines_ptr, size_t *num_lines_ptr) {
   char **lines = NULL;
   size_t num_lines = 0;
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;
   while ((nread = getline(&line, &len, stream)) != -1) {
      lines = lines == NULL
         ? malloc(sizeof(char*))
         : realloc(lines, (num_lines+1)*sizeof(char*));

      lines[num_lines] = malloc(nread+1);
      memcpy(lines[num_lines], line);
      ++num_lines;
   }

   free(line);
   *lines_ptr = lines;
   *num_lines_ptr = num_lines;
}
</code>```

The full solution:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// lines_ptr:     Output. Initial value ignored. To be freed by caller on success.
// num_lines_ptr: Output. Initial value ignored.
// Returns:       0 on error (errno set). 1 on success.
int read_lines(FILE *stream, char ***lines_ptr, size_t *num_lines_ptr) {
   char ***lines = NULL;
   size_t num_lines = 0;
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;
   while ((nread = getline(&line, &len, stream)) != -1) {
      char **new_lines = lines == NULL
         ? malloc(sizeof(char*))
         : realloc(lines, (num_lines+1)*sizeof(char*));
      if (new_lines == NULL)
         goto error;

      lines = new_lines;

      lines[num_lines] = malloc(nread+1);
      if (lines[num_lines] == NULL)
         goto error;

      memcpy(lines[num_lines], line);
      ++num_lines;
   }

   if (ferror(stream))
      goto error;

   free(line);
   *lines_ptr = lines;
   *num_lines_ptr = num_lines;
   return 1;

error:
   for (size_t i=num_lines; i--; )
      free(lines[i]);

   free(lines);
   free(line);
   *lines_ptr = NULL;
   *num_lines_ptr = 0;
   return 0;
}
</code>```

(You could save three lines by using the ..._ptr vars instead of setting them at the end, but is that really worth the readability cost?)

Body:
I'm trying to create a function read_lines that takes a file *fp, a pointer to char** lines, and pointer to int num_lines. The function should insert each line of text into lines, and increase num_lines to however many lines the file has.

Its probably really simple but I've been trying to insert the text for several hours now.

This is what main.c would look like. Everything but read_lines is already defined and working.

int main(int argc, char* argv[]){

    char** lines = NULL;
    int num_lines = 0;
    FILE* fp = validate_input(argc, argv);
    read_lines(fp, &lines, &num_lines);
    print_lines(lines, num_lines);
    free_lines(lines, num_lines);
    fclose(fp);

    return 0;
}

This is one of my attempts at trying to append lines, but I couldn't figure it out.

read_lines.c

void read_lines(FILE *fp, char ***lines, int *num_lines) {
    int i;
    int N = 0;
    char s[200];
    for (i=0; i<3; i++)
    {
        while(fgets(s, 200, fp)!=NULL){N++;}
        char strings[50][200];

        rewind(fp);
        fgets(s, 200, fp);
        strcpy(lines[i],s);
    }

}

I'd appreciate any help at solving this, thanks.

Body:
A solution (without headers and error checking for readability):

void read_lines(FILE *stream, char ***lines_ptr, size_t *num_lines_ptr) {
   char **lines = NULL;
   size_t num_lines = 0;
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;
   while ((nread = getline(&line, &len, stream)) != -1) {
      lines = lines == NULL
         ? malloc(sizeof(char*))
         : realloc(lines, (num_lines+1)*sizeof(char*));

      lines[num_lines] = malloc(nread+1);
      memcpy(lines[num_lines], line);
      ++num_lines;
   }

   free(line);
   *lines_ptr = lines;
   *num_lines_ptr = num_lines;
}

The full solution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// lines_ptr:     Output. Initial value ignored. To be freed by caller on success.
// num_lines_ptr: Output. Initial value ignored.
// Returns:       0 on error (errno set). 1 on success.
int read_lines(FILE *stream, char ***lines_ptr, size_t *num_lines_ptr) {
   char ***lines = NULL;
   size_t num_lines = 0;
   char *line = NULL;
   size_t len = 0;
   ssize_t nread;
   while ((nread = getline(&line, &len, stream)) != -1) {
      char **new_lines = lines == NULL
         ? malloc(sizeof(char*))
         : realloc(lines, (num_lines+1)*sizeof(char*));
      if (new_lines == NULL)
         goto error;

      lines = new_lines;

      lines[num_lines] = malloc(nread+1);
      if (lines[num_lines] == NULL)
         goto error;

      memcpy(lines[num_lines], line);
      ++num_lines;
   }

   if (ferror(stream))
      goto error;

   free(line);
   *lines_ptr = lines;
   *num_lines_ptr = num_lines;
   return 1;

error:
   for (size_t i=num_lines; i--; )
      free(lines[i]);

   free(lines);
   free(line);
   *lines_ptr = NULL;
   *num_lines_ptr = 0;
   return 0;
}

(You could save three lines by using the ..._ptr vars instead of setting them at the end, but is that really worth the readability cost?)


问:
Array creates duplicate tags (wordpress)
I have an associative array which outputs a list of values. Under each value, there are supposed to be links to wordpress posts with that value.

These links should output as:
Title

For some reason, they output as:
Title

It looks like the  tag is being created for both title and URL.

Here's the code:

```<code> <?php
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

$results = [];
while ( $the_query->have_posts() ) {

    $the_query->the_post();
    $credits = get_field('colors');
    if( !empty($colors) ) {

        foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

    }

}

foreach ($results as $color => $posts) {

    echo '<div><h2>'.$color.'</h2>';

    foreach($posts as $post) {
        echo '<a href="'.$post['link'].'">'.$post['title'].'</a>';
    }
    echo '</div>';
}

wp_reset_postdata();?>
</code>```

A couple of tests:

foreach($posts as $post) {echo '
'.$post['title'].'
';}

outputs
Title
 but for every title, there are two blanks without the title:

```<code><div><a href="">Title1</a></div>
<div><a href=""></a></div>
<div><a href=""></a></div>
<div><a href="">Title2</a></div>
<div><a href=""></a></div>
<div><a href=""></a></div>
</code>```

Similarly, foreach($posts as $post) { echo '
'.$post['link'].''.$post['title'].'
';} is creating blank containers:

```<code><div>Title1</div>
<div>URL1</div>
<div></div>
<div>Title2</div>
<div>URL2</div>
<div></div>
</code>```

答:
Here is the problem:

```<code> foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }
</code>```

You are using [] for the same array 2 times. And this splits color-link couple from each other. They are saved into different array. Use defined indexes instead

```<code> $i=0;
 foreach( $colors as $color ) {
             $results [$color][$i]['title'] = get_the_title();
             $results [$color][$i]['link'] = get_attachment_link();
             $i++;
        }
</code>```

or you can simply do it with single line

```<code>foreach( $colors as $color ) {
           $results [$color][]=array('title' => get_the_title(),
           'link' => get_attachment_link());
       }
</code>```

Body:
I have an associative array which outputs a list of values. Under each value, there are supposed to be links to wordpress posts with that value.

These links should output as:
Title

For some reason, they output as:
Title

It looks like the  tag is being created for both title and URL.

Here's the code:

 <?php
$the_query = new WP_Query(array(
    'post_type'     => 'post',
    'post_status'   => 'publish',
    'meta_key'      => 'colors',
));

$results = [];
while ( $the_query->have_posts() ) {

    $the_query->the_post();
    $credits = get_field('colors');
    if( !empty($colors) ) {

        foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

    }

}

foreach ($results as $color => $posts) {

    echo '

'.$color.'
';

    foreach($posts as $post) {
        echo ''.$post['title'].'';
    }
    echo '
';
}

wp_reset_postdata();?>

A couple of tests:

foreach($posts as $post) {echo '
'.$post['title'].'
';}

outputs
Title
 but for every title, there are two blanks without the title:

Title1

Title2

Similarly, foreach($posts as $post) { echo '
'.$post['link'].''.$post['title'].'
';} is creating blank containers:

Title1

URL1

Title2

URL2

Body:
Here is the problem:

 foreach( $colors as $color ) {
            $results [$color][]['title'] = get_the_title();
            $results [$color][]['link'] = get_attachment_link();
        }

You are using [] for the same array 2 times. And this splits color-link couple from each other. They are saved into different array. Use defined indexes instead

 $i=0;
 foreach( $colors as $color ) {
             $results [$color][$i]['title'] = get_the_title();
             $results [$color][$i]['link'] = get_attachment_link();
             $i++;
        }

or you can simply do it with single line

foreach( $colors as $color ) {
           $results [$color][]=array('title' => get_the_title(),
           'link' => get_attachment_link());
       }


答:
OpenCV may cause linkage errors, if OpenCV and the code using it were
  compiled by different compilers. Why is that?

Different C++ compilers may have different name mangling. As a result, the linking process is not able to link names generated by different compilers.

What does using different compilers accomplish?

Using different compilers allows a developer to find out issues with portability of the code.

Title: Using different compilers - what does that do?

Body:
By my understanding compilers like mingw, clang, mvs c++ simply take source code written in C++ and try to generate senseful object code and maybe create an executeable that may or may not follow the developer's intentions.

However I noticed that for example OpenCV may cause linkage errors, if OpenCV and the code using it were compiled by different compilers. Why is that? What does using different compilers accomplish?


问:
Does Puppet Bolt have the same feature set as Red Hat Ansible?
I was at a conference yesterday speaking with some folks about Puppet Lab's Bolt 1.0.  I'm trying to figure out whether the tools is comparable to Ansible, but can take advantage of all the puppet modules that already exist or if it is different in some other manner.

I'm not super familiar with either tool and was hoping that somebody who was more knowledgable thane would be able to explain the difference between the two tools.

I can see both are agent-less which I see as a plus - but I'm unclear on the other differences and why one would pick one over the other.  Not looking for a subjective answer - but an actual list of what differentiates the two tools

答:
Puppet Bolt and RedHat Ansible both try to solve the same problems of agentless, push-based orchestration and configuration management. Naturally, though, they don't have exactly the same features.

I would keep the following in mind:

Ansible is a mature product in this space (at the time of writing), and Bolt is a new product. A consequence of this is you'll find Ansible roles already written for many tasks, whereas in Bolt, you may find fewer code examples to get you on your way.

Bolt is written in Ruby whereas Ansible is written in Python. Bolt uses Ruby and Puppet's DSL whereas Ansible uses a YAML DSL. Some will choose one or the other tool on the basis of which of these languages they know and/or prefer. (Although, as noted in comments, Bolt Tasks can be written in many languages, and there is also a YAML option for plans.)

As you say, Bolt allows easy integration with Puppet configuration management, use of Puppet's modules and its DSL in Bolt plans. If you already use Puppet, Bolt is the natural choice.

But I would definitely try them both out and choose the one that seems a better fit to the actual problems you are trying to solve.


问:
Handle exceptions caused by parsing nullable parameters in controller action
I have an endpoint

```<code>[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)
</code>```

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

答:
I've just made a simple IModelBinder that converts a string into a instance of the desired type if it supports default convertation

code is looking like this:

```<code>public Task BindModelAsync(ModelBindingContext bindingContext)
{
    var targetType = bindingContext.ModelType;
    var targetName = bindingContext.ModelName;
    var stringValue = bindingContext.ValueProvider.GetValue(targetName).FirstValue;

    var isNullableOrReference = Nullable.GetUnderlyingType(targetType) != null ||
                                !targetType.IsValueType;

    var valueProvider = bindingContext.ValueProvider.GetValue(targetName);
    try
    {
        var converter = TypeDescriptor.GetConverter(targetType);
        var resultValue = converter.ConvertFromString(stringValue);

        bindingContext.Result = ModelBindingResult.Success(resultValue);
        bindingContext.ModelState.SetModelValue(targetName, valueProvider);
    }
    catch (NotSupportedException e)
    {
        bindingContext.Result = ModelBindingResult.Failed();
        return Task.CompletedTask;
    }
    catch (Exception e)
    {
        bindingContext.Result = ModelBindingResult.Success(isNullableOrReference ? null : Activator.CreateInstance(targetType));
        bindingContext.ModelState.SetModelValue(targetName, valueProvider);
    }

    return Task.CompletedTask;
}
</code>```

It needs to be a bit tuned, but it works as I wanted it to be

Body:
I have an endpoint

[HttpGet]
public async Task<ActionResult> GetNodes([FromQuery] Guid? parentId)

And call it like that
GET .../api/nodes?parentId=null

Asp.net throws an exception when parsing parameter "The value 'null' is not valid."

How to override that behaviour to make it parse nullable types to null if an exception occurs?

I expect:

GET .../api/nodes?parentId=null should call action with parentId == null

GET .../api/nodes?parentId=50d21ddd-6a95-46db-bff9-c943cf5b0df1 should call action with parentId = "50d21ddd-6a95-46db-bff9-c943cf5b0df1"

GET .../api/nodes?parentId=something_not_parsable_to_guid should call action with parentId = null

Body:
I've just made a simple IModelBinder that converts a string into a instance of the desired type if it supports default convertation

code is looking like this:

public Task BindModelAsync(ModelBindingContext bindingContext)
{
    var targetType = bindingContext.ModelType;
    var targetName = bindingContext.ModelName;
    var stringValue = bindingContext.ValueProvider.GetValue(targetName).FirstValue;

    var isNullableOrReference = Nullable.GetUnderlyingType(targetType) != null ||
                                !targetType.IsValueType;

    var valueProvider = bindingContext.ValueProvider.GetValue(targetName);
    try
    {
        var converter = TypeDescriptor.GetConverter(targetType);
        var resultValue = converter.ConvertFromString(stringValue);

        bindingContext.Result = ModelBindingResult.Success(resultValue);
        bindingContext.ModelState.SetModelValue(targetName, valueProvider);
    }
    catch (NotSupportedException e)
    {
        bindingContext.Result = ModelBindingResult.Failed();
        return Task.CompletedTask;
    }
    catch (Exception e)
    {
        bindingContext.Result = ModelBindingResult.Success(isNullableOrReference ? null : Activator.CreateInstance(targetType));
        bindingContext.ModelState.SetModelValue(targetName, valueProvider);
    }

    return Task.CompletedTask;
}

It needs to be a bit tuned, but it works as I wanted it to be


问:
Changing Border Color of AWT TextField
In AWT application I need to set border color of TextField.

In JTextField, I know that we do can do the following

```<code>JTextField tf = new JTextField();
tf.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));
</code>```

But setBorder() method is not availiable in awt TextField. Is there any workaround for this problem?

答:
Create a line border with the specified color and width

```<code>Border border = BorderFactory.createLineBorder(Color.BLUE, 5);
</code>```

Set the border of this component

```<code> JTextField.setBorder(border);
</code>```

Title: Changing Border Color of AWT TextField

Body:
In AWT application I need to set border color of TextField.

In JTextField, I know that we do can do the following

JTextField tf = new JTextField();
tf.setBorder(BorderFactory.createLineBorder(Color.decode("#2C6791")));

But setBorder() method is not availiable in awt TextField. Is there any workaround for this problem?

Body:
Create a line border with the specified color and width

Border border = BorderFactory.createLineBorder(Color.BLUE, 5);

Set the border of this component

 JTextField.setBorder(border);


问:
How to perform particular operation by button click
I want to perform more than 2 operation in single HTML page by button click. In menu bar have 5 options. i.e when i click Home it perform some operation and when i click profile it perform particular operation. I write separate functions for each operation. How to do multiple functions operations for single page.

views.py

```<code>def home(request):
    return render(request, 'index.html', {})

def profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            first_name = request.session['username']
            print(first_name)
            test = Profile.objects.filter(first_name=first_name).values()
            for i in test:
                dict1 = i
                return render(request, 'index.html',
                              {'first_name': first_name, 'last_name': dict1['last_name'],
                               'phone_number': dict1['phone_number'], 'email': dict1['email'],
                               'address': dict1['address'], 'image': dict1['image']})
    else:
        form = ProfileForm()
        return render(request, 'profile.html', {'form': form})

def friends(request):
    friends_obj = Friends.objects.all()
    return render(request, 'index.html', {'friends_obj': friends_obj})
</code>```

urls.py

```<code>urlpatterns = [
    path('home/', views.home, name="home"),
    path('profile/', views.profile, name="profile"),
    path('friends/', views.friends, name="friends"),
]
</code>```

menu bar look like thisI want to perform all operations by clicking menu options.

答:
def friends(request): and def home(request): are with Get method and def profile(request): is with Post method. so first step we can serate them with if request.method == "POST" . for separate process with same method we need attach some flag to process from front-end (Html-javascript and etc) before sending to django view.something like this:
template.html:

```<code><form action="/navbar_aggregation" method="get">
  <input type="text" name="type" value="friends" hidden>
  <!-- other input tag will be here as you need-->
  <input type="submit" value="Submit">
</form>
</code>```

then you can access to type in view like this. view.py:

```<code>def navbar_aggregation(request):
    type = request.get.Get("type")  # name of hidden input
    if (type == "friends"):
        # do same thing like 'def freinds(request)'
    elif(type == "family"):
        # do process for family form
    else :
        # do process for 'def home(request)'
</code>```

so now we know how can seprate method="Get" or method="POST" . so your view will be like this:

view.py:

```<code>def navbar_aggregation(request):
   if request.method == "POST":
         form = ProfileForm(request.POST)
         if form.is_valid():
            first_name = request.session['username']
            print(first_name)
            test = Profile.objects.filter(first_name=first_name).values()
            for i in test:
                dict1 = i
                return render(request, 'index.html',
                              {'first_name': first_name, 'last_name': dict1['last_name'],
                               'phone_number': dict1['phone_number'], 'email':
                                  dict1['email'],
                               'address': dict1['address'], 'image': dict1['image']})
   else : # we are in method="GET"
      type = request.get.Get("type")  # name of hidden input
      if(type == "friends"):
              friends_obj = Friends.objects.all()
              return render(request, 'index.html', {'friends_obj': friends_obj})
      elif(type == "form"):
            form = ProfileForm()
            return render(request, 'profile.html', {'form': form})
      elif(type == "foo"):
            # do something for foo's form
            return something
      else:  # for sure it should be home's request because haven't any tag for "type"
         return render(request, 'index.html', {})
</code>```

dear friend i'm new in django too so i think my answer code have some bug, but maybe help you .I answered your question because i see not any pro developer not answering your question .

Body:
I want to perform more than 2 operation in single HTML page by button click. In menu bar have 5 options. i.e when i click Home it perform some operation and when i click profile it perform particular operation. I write separate functions for each operation. How to do multiple functions operations for single page.

views.py

def home(request):
    return render(request, 'index.html', {})

def profile(request):
    if request.method == 'POST':
        form = ProfileForm(request.POST)
        if form.is_valid():
            first_name = request.session['username']
            print(first_name)
            test = Profile.objects.filter(first_name=first_name).values()
            for i in test:
                dict1 = i
                return render(request, 'index.html',
                              {'first_name': first_name, 'last_name': dict1['last_name'],
                               'phone_number': dict1['phone_number'], 'email': dict1['email'],
                               'address': dict1['address'], 'image': dict1['image']})
    else:
        form = ProfileForm()
        return render(request, 'profile.html', {'form': form})

def friends(request):
    friends_obj = Friends.objects.all()
    return render(request, 'index.html', {'friends_obj': friends_obj})

urls.py

urlpatterns = [
    path('home/', views.home, name="home"),
    path('profile/', views.profile, name="profile"),
    path('friends/', views.friends, name="friends"),
]

menu bar look like thisI want to perform all operations by clicking menu options.

Body:
def friends(request): and def home(request): are with Get method and def profile(request): is with Post method. so first step we can serate them with if request.method == "POST" . for separate process with same method we need attach some flag to process from front-end (Html-javascript and etc) before sending to django view.something like this:
template.html:

<form action="/navbar_aggregation" method="get">
  <input type="text" name="type" value="friends" hidden>
  <!-- other input tag will be here as you need-->
  <input type="submit" value="Submit">
</form>

then you can access to type in view like this. view.py:

def navbar_aggregation(request):
    type = request.get.Get("type")  # name of hidden input
    if (type == "friends"):
        # do same thing like 'def freinds(request)'
    elif(type == "family"):
        # do process for family form
    else :
        # do process for 'def home(request)'

so now we know how can seprate method="Get" or method="POST" . so your view will be like this:

view.py:

def navbar_aggregation(request):
   if request.method == "POST":
         form = ProfileForm(request.POST)
         if form.is_valid():
            first_name = request.session['username']
            print(first_name)
            test = Profile.objects.filter(first_name=first_name).values()
            for i in test:
                dict1 = i
                return render(request, 'index.html',
                              {'first_name': first_name, 'last_name': dict1['last_name'],
                               'phone_number': dict1['phone_number'], 'email':
                                  dict1['email'],
                               'address': dict1['address'], 'image': dict1['image']})
   else : # we are in method="GET"
      type = request.get.Get("type")  # name of hidden input
      if(type == "friends"):
              friends_obj = Friends.objects.all()
              return render(request, 'index.html', {'friends_obj': friends_obj})
      elif(type == "form"):
            form = ProfileForm()
            return render(request, 'profile.html', {'form': form})
      elif(type == "foo"):
            # do something for foo's form
            return something
      else:  # for sure it should be home's request because haven't any tag for "type"
         return render(request, 'index.html', {})

dear friend i'm new in django too so i think my answer code have some bug, but maybe help you .I answered your question because i see not any pro developer not answering your question .


问:
How can i align contents of my print page?
This is the print previewI'm using a javascript function to print a page. But the print preview is having alignment mistakes and I've tried
both using link tag
and also @media print. Both are not working for me.
Any and all help would be great.Thankyou.</p>

```<code>function ClickHereToPrint() {
    try {
        var printContent = document.getElementById('divToPrint').innerHTML;
        var windowUrl = 'about:blank';
        var uniqueName = new Date();
        var windowName = 'Print' + uniqueName.getTime();
        var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');
        printWindow.document.write(printContent);
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    }
    catch (e) {
        self.print();
    }
}

<div id="divToPrint">
    <div class="imgcontainer">
    <img align="left" hspace="15" src="Dotline/images/neridioLogo.png" alt="Edit" height="150" width="150">
      <span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
    </div>
    <br/>
    <h6 align="center"><b>Migrated Files</b></h6>
    <p align="center"> hell0.txt </p>
    <p align="center"> hell0.txt </p>
    <h6 align="center"><b>Failed Files</b></h6>
    <p align="center"> failed.txt </p>
    <p align="center"> failed.txt </p>
</div>
</code>```

答:
There are many ways to achieve the desired layout using HTML and CSS.

Here's one way using display:inline-block:

.image,
.text {
  display: inline-block;
  vertical-align: top;
}

.image {
  margin: 0 2em 0 0;
}

.close {
  vertical-align: top;
  margin: 0 0 0 0.5em;
}

.text h6 {
  margin: 0;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="divToPrint">
  <div class="image">
    <img src="https://picsum.photos/id/237/150/150" alt="Edit" height="150" width="150">
    <span class="close" title="Close Modal">×</span>
  </div>
  <div class="text">
    <h6>Migrated Files</h6>
    <p>hell0.txt</p>
    <p>hell0.txt</p>
    <h6>Failed Files</h6>
    <p>failed.txt</p>
    <p>failed.txt</p>
  </div>
</div></code>```

Here's another way using flexbox:

#divToPrint {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.image {
  margin: 0 2em 0 0;
}

.close {
  vertical-align: top;
  margin: 0 0 0 0.5em;
}

.text h6 {
  margin: 0;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="divToPrint">
  <div class="image">
    <img src="https://picsum.photos/id/237/150/150" alt="Edit" height="150" width="150">
    <span class="close" title="Close Modal">×</span>
  </div>
  <div class="text">
    <h6>Migrated Files</h6>
    <p>hell0.txt</p>
    <p>hell0.txt</p>
    <h6>Failed Files</h6>
    <p>failed.txt</p>
    <p>failed.txt</p>
  </div>
</div></code>```

For reference, see Learn to style HTML using CSS.

Body:
This is the print previewI'm using a javascript function to print a page. But the print preview is having alignment mistakes and I've tried
both using link tag
and also @media print. Both are not working for me.
Any and all help would be great.Thankyou.

function ClickHereToPrint() {
    try {
        var printContent = document.getElementById('divToPrint').innerHTML;
        var windowUrl = 'about:blank';
        var uniqueName = new Date();
        var windowName = 'Print' + uniqueName.getTime();
        var printWindow = window.open(windowUrl, windowName, 'left=50000,top=50000,width=0,height=0');
        printWindow.document.write(printContent);
        printWindow.document.close();
        printWindow.focus();
        printWindow.print();
        printWindow.close();
    }
    catch (e) {
        self.print();
    }
}

      ×

Migrated Files

 hell0.txt

 hell0.txt

Failed Files

 failed.txt

 failed.txt

Body:
There are many ways to achieve the desired layout using HTML and CSS.

Here's one way using display:inline-block:

.image,
.text {
  display: inline-block;
  vertical-align: top;
}

.image {
  margin: 0 2em 0 0;
}

.close {
  vertical-align: top;
  margin: 0 0 0 0.5em;
}

.text h6 {
  margin: 0;
  font-weight: bold;
}

<div id="divToPrint">
  <div class="image">
    <img src="https://picsum.photos/id/237/150/150" alt="Edit" height="150" width="150">
    <span class="close" title="Close Modal">&times;</span>
  </div>
  <div class="text">
    <h6>Migrated Files</h6>
    <p>hell0.txt</p>
    <p>hell0.txt</p>
    <h6>Failed Files</h6>
    <p>failed.txt</p>
    <p>failed.txt</p>
  </div>
</div>

Here's another way using flexbox:

#divToPrint {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}

.image {
  margin: 0 2em 0 0;
}

.close {
  vertical-align: top;
  margin: 0 0 0 0.5em;
}

.text h6 {
  margin: 0;
  font-weight: bold;
}

<div id="divToPrint">
  <div class="image">
    <img src="https://picsum.photos/id/237/150/150" alt="Edit" height="150" width="150">
    <span class="close" title="Close Modal">&times;</span>
  </div>
  <div class="text">
    <h6>Migrated Files</h6>
    <p>hell0.txt</p>
    <p>hell0.txt</p>
    <h6>Failed Files</h6>
    <p>failed.txt</p>
    <p>failed.txt</p>
  </div>
</div>

For reference, see Learn to style HTML using CSS.


问:
Regex help - match to number or end of string
Struggling to work this one out as I'm not great with regex. I have strings like this:

```<code>Method
Lorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.

Agam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.
42
Aliquip voluptua appetere
</code>```

Which I can detect fine with the following regex: /^Method\n(.*[\s\S]*)(?:\d\d)/

https://regex101.com/r/Uw3XzK/1

The problem comes in occassionally the string I am detecting does not end in a number. Here I generally just need to go to the end of the string.

```<code>Method
Lorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.

Agam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.
</code>```

I have tried adding a ? to the stirng. /^Method\n(.[\s\S])(?:\d\d)? however this then breaks the matching of the first string.

What can I do to first and foremost match string 1, but then fall back to matching to the end of the file?

答:
The following pattern in fact works with PHP, when using preg_match_all in dot all mode:

```<code>\bMethod.*?(?=\d{2}|$)
</code>```

Sample script:

```<code>$input = "Method\nLorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.\nAgam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.\n42\nAliquip voluptua appetere";
preg_match_all("/\bMethod.*?(?=\d{2}|$)/s", $input, $matches);
print_r($matches);
</code>```

Body:
Struggling to work this one out as I'm not great with regex. I have strings like this:

Method
Lorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.

Agam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.
42
Aliquip voluptua appetere

Which I can detect fine with the following regex: /^Method\n(.*[\s\S]*)(?:\d\d)/

https://regex101.com/r/Uw3XzK/1

The problem comes in occassionally the string I am detecting does not end in a number. Here I generally just need to go to the end of the string.

Method
Lorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.

Agam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.

I have tried adding a ? to the stirng. /^Method\n(.[\s\S])(?:\d\d)? however this then breaks the matching of the first string.

What can I do to first and foremost match string 1, but then fall back to matching to the end of the file?

Body:
The following pattern in fact works with PHP, when using preg_match_all in dot all mode:

\bMethod.*?(?=\d{2}|$)

Sample script:

$input = "Method\nLorem ipsum dolor sit amet, id pro lorem consulatu, ut nemore principes vel. Nibh aliquam iracundia ea est, probo utamur placerat at duo. Nam an perfecto voluptaria temporibus, no dicat dolores eum. Doming dissentias eloquentiam sit id, sit eu etiam scriptorem appellantur, ne explicari voluptaria nec.\nAgam erroribus cum id, vis ei nominavi copiosae. Per unum atomorum ut, amet atqui moderatius in mel, ex mucius concludaturque vix. Ei quodsi admodum conclusionemque duo, pro vidit nonumy fastidii at. Aliquip voluptua appetere eam id.\n42\nAliquip voluptua appetere";
preg_match_all("/\bMethod.*?(?=\d{2}|$)/s", $input, $matches);
print_r($matches);


问:
LotusScript - How to create button to change values in certain fields and refresh form?
Currently reworking an old form in LotusNotes where if user edits the form certain fields will be reset to blank. Now I need to place that function into a button so that users can simply edit without the need to reset those fields, but still allow them to use the reset function if needed.

What I basically did was copy the LotusScript code in the Form portion which enables this function and paste it into a button action:

```<code>------------------------------------------------
Reset Approval (Action) : (Declaration)
------------------------------------------------

Dim editflag as string

------------------------------------------------
Reset Approval (Action) : Click
------------------------------------------------

Sub Click(Source As button)

Dim w As New NotesUIWorkspace
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim uidoc As NotesUIDocument

Set db = session.CurrentDatabase
Set uidoc = w.CurrentDocument

 ' Get value for Approver 1 and 2

Approver_1 = uidoc.FieldGetText( "Approver_1" )
Approver_2 = uidoc.FieldGetText( "Approver_2" )
status1 = uidoc.FieldGetText( "status1" )
status2 = uidoc.FieldGetText( "status2" )
author = uidoc.FieldGetText( "Author" )
submit = uidoc.FieldGetText( "submit" )
cname = session.CommonUserName & "/ASY/MAWA"
aname = session.UserName

'Msgbox submit
'Cannot edit if user is not the author or approver 1 and 2
If (aname <> author And cname <> Approver_1  And  cname <> Approver_2) Then
    Msgbox "You Dont Have The Authorization To Edit This Document", 16, "Access Restricted"
    Continue = False
    Exit Sub
End If

 '''''''''''''If user is the author prompt warning if the form already approved
If (aname = author And (status1 = "Yes" Or status2 = "Yes")) Then
    Message = "Editing This Document Will Reset The Approval Status" & Chr$(13) &_
    "Do you wish to continue?"
    YesNo = Messagebox(Message,36,"Continue?")
    If YesNo = 7 Then
        continue = False
        Exit Sub
    Else
        editflag = "Y"
    End If
End If

Dim doc1 As NotesDocument
Dim source1 As NotesUIDocument
'Use backend notes object to assign value to current document
Set doc1 = source1.Document

'Check if document in edit mode
If (source1.EditMode = True) Then
    'If edit flag is "Y" then reset status1 and status2 value
    If (editflag = "Y") Then
        doc1.ReplaceItemValue "status1", ""
        doc1.ReplaceItemValue "status2" ,""
        doc1.ReplaceItemValue "submit" ,"progress"
    End If
End If
'Refresh document to anable send button
Call source1.Refresh

End Sub
</code>```

When I save the changes I didn't get any error messages so I assumed it's OK. But when I try to test it I get an Object Variable is not set error and the form doesn't change. What am I missing?

答:
First of all: NEVER write even one line of LotusScript without error handler. Put these lines around your code:

```<code>On error goto ErrorHandler

...your code...

EndOfRoutine:
  Exit Sub
ErrorHandler:
  Msgbox err+"-"+error+" in line "+erl
  Resume EndOfRoutine
</code>```

Then you will find that the error occurs in the line

```<code>Set doc1 = source1.document
</code>```

As you never set uidoc1 but only uidoc.

Change it to

```<code>Set doc1 = uidoc.Document
</code>```

and replace all other instances of source1 with uidoc (you can remove the Dim source1 as NotesUiDocument line) then it will work.

Body:
Currently reworking an old form in LotusNotes where if user edits the form certain fields will be reset to blank. Now I need to place that function into a button so that users can simply edit without the need to reset those fields, but still allow them to use the reset function if needed.

What I basically did was copy the LotusScript code in the Form portion which enables this function and paste it into a button action:

------------------------------------------------
Reset Approval (Action) : (Declaration)
------------------------------------------------

Dim editflag as string

------------------------------------------------
Reset Approval (Action) : Click
------------------------------------------------

Sub Click(Source As button)

Dim w As New NotesUIWorkspace
Dim session As New NotesSession
Dim db As NotesDatabase
Dim doc As NotesDocument
Dim uidoc As NotesUIDocument

Set db = session.CurrentDatabase
Set uidoc = w.CurrentDocument

 ' Get value for Approver 1 and 2

Approver_1 = uidoc.FieldGetText( "Approver_1" )
Approver_2 = uidoc.FieldGetText( "Approver_2" )
status1 = uidoc.FieldGetText( "status1" )
status2 = uidoc.FieldGetText( "status2" )
author = uidoc.FieldGetText( "Author" )
submit = uidoc.FieldGetText( "submit" )
cname = session.CommonUserName & "/ASY/MAWA"
aname = session.UserName

'Msgbox submit
'Cannot edit if user is not the author or approver 1 and 2
If (aname <> author And cname <> Approver_1  And  cname <> Approver_2) Then
    Msgbox "You Dont Have The Authorization To Edit This Document", 16, "Access Restricted"
    Continue = False
    Exit Sub
End If

 '''''''''''''If user is the author prompt warning if the form already approved
If (aname = author And (status1 = "Yes" Or status2 = "Yes")) Then
    Message = "Editing This Document Will Reset The Approval Status" & Chr$(13) &_
    "Do you wish to continue?"
    YesNo = Messagebox(Message,36,"Continue?")
    If YesNo = 7 Then
        continue = False
        Exit Sub
    Else
        editflag = "Y"
    End If
End If

Dim doc1 As NotesDocument
Dim source1 As NotesUIDocument
'Use backend notes object to assign value to current document
Set doc1 = source1.Document

'Check if document in edit mode
If (source1.EditMode = True) Then
    'If edit flag is "Y" then reset status1 and status2 value
    If (editflag = "Y") Then
        doc1.ReplaceItemValue "status1", ""
        doc1.ReplaceItemValue "status2" ,""
        doc1.ReplaceItemValue "submit" ,"progress"
    End If
End If
'Refresh document to anable send button
Call source1.Refresh

End Sub

When I save the changes I didn't get any error messages so I assumed it's OK. But when I try to test it I get an Object Variable is not set error and the form doesn't change. What am I missing?

Body:
First of all: NEVER write even one line of LotusScript without error handler. Put these lines around your code:

On error goto ErrorHandler

...your code...

EndOfRoutine:
  Exit Sub
ErrorHandler:
  Msgbox err+"-"+error+" in line "+erl
  Resume EndOfRoutine

Then you will find that the error occurs in the line

Set doc1 = source1.document

As you never set uidoc1 but only uidoc.

Change it to

Set doc1 = uidoc.Document

and replace all other instances of source1 with uidoc (you can remove the Dim source1 as NotesUiDocument line) then it will work.


答:
It is because of image you used on the left side, and the element first
 and
 tag takes the position of the center after that logo image if you want to align it, you have to give padding or margin to both
 and
 element

Title: How can i align contents of my print page?

Body: It is because of image you used on the left side, and the element first <h6> and <p> tag takes the position of the center after that logo image if you want to align it, you have to give padding or margin to both <h6> and <p> element


问:
What's the purpose of stack pointer alignment in the prologue of main()
In the prologue of the main function (of a simple toy program) that was compiled using gcc -g -o program -m32 program.c on a 64-bit machine (running ubuntu 14.04) I get the following disassembly:

```<code>dump of assembler code for function main:
   0x08048e24 <+0>: push   %ebp
   0x08048e25 <+1>: mov    %esp,%ebp
   0x08048e27 <+3>: and    $0xfffffff0,%esp
   ...
</code>```

What's the purpose of the instruction at <+3>?
That is, why should the $esp point to an 16-aligned address?

答:
Modern versions of the i386 System V ABI have the same 16-byte stack alignment requirement / guarantee as x86-64 System V (which @ouah's answer mentions).

This includes a guarantee that the kernel will have aligned %esp by 16 at _start.  So CRT startup code that also maintains 16-byte alignment will call main with the stack 16-byte aligned.

Historically, the i386 System V ABI only required 4-byte stack alignment, and aligning the stack by 16 was just something compilers could choose to do; GCC defaulted to -mpreferred-stack-boundary=4 when it was just a good idea, not the law (on MacOS and Linux).

Some BSD versions I think still don't require 16-byte stack alignment in 32-bit code, so 32-bit code that want to use aligned memory for a double,  int64_t, or especially an XMM vector, does need to manually align the stack instead of relying on incoming stack alignment.

But even on modern Linux, GCC's 32-bit-mode (-m32) behaviour for main doesn't assume that main's caller (or the kernel) follows the ABI, and manually aligns the stack.

See Responsibility of stack alignment in 32-bit x86 assembly for more; another question where the obsolete instruction led to confusion based on the assumption that it was needed.

GCC on x86-64 does not do this, and does just take advantage of the fact that 16-byte stack alignment has always been a requirement in the x86-64 System V ABI.  (And the Windows x64 ABI).

Body:
In the prologue of the main function (of a simple toy program) that was compiled using gcc -g -o program -m32 program.c on a 64-bit machine (running ubuntu 14.04) I get the following disassembly:

dump of assembler code for function main:
   0x08048e24 <+0>: push   %ebp
   0x08048e25 <+1>: mov    %esp,%ebp
   0x08048e27 <+3>: and    $0xfffffff0,%esp
   ...

What's the purpose of the instruction at <+3>?
That is, why should the $esp point to an 16-aligned address?