text:
Q: Boolean variable in Webdriver I have definition of Boolean variable in Webdriver backed as:
boolean r1 = selenium.isTextPresent("something");

I used this in while loop. I want convert my code to Webdriver code and I tried:
boolean jr1 = driver.findElement(By.linkText("something")) != null;

But it works only when text is present and value is true. When value should be returned as false to my variable i receive in console error:
Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Unable to locate element: {"method":"link text","selector":"something"}

Can you give me any suggestions how i can do that?

A: I got around this by writing an isElementPresent method that returns true or false.
Edit - Having just seen this exact method in another answer, I no longer believe I wrote it. Apparently I found it ages ago and have been using it for so long that it feels like mine! All credit to original author
private boolean isElementPresent(By by) {
  try {
    driver.findElement(by);
    return true;
  } catch (NoSuchElementException e) {
    return false;
  }
}

You can then use:
boolean jr1 = isElementPresent(By.linkText("Something"));

Add this method to a base class and extend your test class from it, Or add it to each of your test classes.

A: For me the most straightforward implementation of isTextPresent as webdriver code is the following:
public boolean isTextPresent(String text) {
   String allText = webDriver.findElement(By.tagName("body")).getText();
   boolean isTextPresent = allText.contains(text);
   return isTextPresent;
}

A: If the element does not have the linktext 'something' Webdriver will always return the exception I'm afraid.
Have you tried the Expected Conditions?
try {
        wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("something")
        Boolean jr1 = True
    }
catch (Exception e) {
        Boolen jr1 = False
    }

It's a rather rough implementation but in this case I will try to find the element, if it finds it, True. If the request times out, False.

A: I got around this by using following approach:

*

*Initially I set the value of boolean msg not displayed to false

*waited for 50 seconds until element is clickable

*if the text in the table equals displayed text i.e. no records then return true

*else return false
public boolean isRecordDisplayed(String sDisplayText) {
            Boolean isNoRecordDisplayedMsg = false;
            WebElement search = (new WebDriverWait(webDriver, 50).until(ExpectedConditions.elementToBeClickable(table)));
        if (search.getText().equals(sDisplayText)) {
            isNoRecordDisplayedMsg = true;
        }
        return isRecordHostDisplayedMsg;
    }

By table = By.xpath("//div[contains(@class,'record')]//th");


text:
Q: How to handle exceptions in a JDBC ResultSet Iterator I have a couple of housekeeping and exception handling questions around processing JDBC ResultSets as Iterators (see code below -- specifically the sql function).
class SqlHelper(prop: Properties) {

  val conn = {
    Class.forName(prop.getProperty("drivername"))
    DriverManager.getConnection(prop.getProperty("jdbcurl"), prop.getProperty("username"), prop.getProperty("password"))
  }

  def sql(conn: Connection, s: String): Iterator[ResultSet] = {
    val rs = conn.createStatement.executeQuery(s)
    Iterator.
      continually(rs.next, rs).
      takeWhile(_._1).
      map(_._2)
  }
}

The caller would find work (to do) and pass it to an Akka worker actor. Once it is done, it will repeat that loop.
  def doWork = {
    val sqlhelper = new SqlHelper(new Properties())

    while (true) {
      try {
        sqlhelper.
          sql("select work_key from wip_table where need_to_process = 'Y'").
          foreach(k => worker ! Work(k.getString("work_key")))
        ?????? how to clean up after finishing ????
      } catch {
        case e: Exception =>
          e.printStackTrace()
          ?????? how to clean up after exception ????
      }
    }
  }

My questions are

*

*housekeeping - how do I close off the resultset and the statement once I am done? I can't think of a way to close the resources in the sql iterator.

*similarly, in the caller, I would like to wrap the iterator with a try/catch so that on exception, I can close the rs and statement. But I am not sure how to do that? For example, how do I get to the rs and statement to close it??

Thanks in advance for any advice or suggestions.

A: Try scala.util.Using perhaps like so
Using.resource(DriverManager.getConnection(...)) { conn =>
  val rs = conn.createStatement.executeQuery(s)
  Iterator
    .continually(rs.next, rs)
    .takeWhile(_._1)
    .map(_._2)
    .foreach(...)
}

According to Using.resource docs :

Performs an operation using a resource, and then releases the
  resource, even if the operation throws an exception. This method
  behaves similarly to Java's try-with-resources.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to load an Excel file using PHPExcel (Error with vml relationships)? The question is simple : how to load this Excel workbook (http://wftda.com/stats/wftda-stats-book.xlsx) with PHP Excel without throwing any errors ?
I use the following code (which is more or less the mwe explained in the doc):
$inputFileType = 'Excel2007';

$inputFileName = path_to/wftda-stats-book.xlsx';

//Create a new Reader of the type defined in $inputFileType
$objReader = PHPExcel_IOFactory::createReader($inputFileType);

//Load $inputFileName to a PHPExcel Object
$objPHPExcel = $objReader->load($inputFileName);

After 5 seconds or so of treatment, I get the following errors :
Notice: Trying to get property of non-object in /srv/web/www/dev/arbitrage/_inc/lib/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php on line 1378
Warning: Invalid argument supplied for foreach() in /srv/web/www/dev/arbitrage/_inc/lib/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php on line 1378
Notice: Undefined offset: 0 in /srv/web/www/dev/arbitrage/_inc/lib/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php on line 1394
Fatal error: Call to a member function attributes() on a non-object in /srv/web/www/dev/arbitrage/_inc/lib/PHPExcel/Classes/PHPExcel/Reader/Excel2007.php on line 1396

The part of the code where the errors lie seems to be related to vml relationships, whatever that is...

A: You have to include phpexcel libary in libary folder like this:
$this->load->libary('PHPExcel);

download phpexcel and paste it into libary folder.


text:
Q: How to get values from my datframe with two values? I'm trying to get the values after the commas on a dataframe that has two values in each column
My dataframe looks like this.

Thanks!
P.S. I started programming today

A: >>df = pd.DataFrame({'c1': [[10, 11], [12,13]], 'c2': [[100, 110], [120,130]]})
>>df
         c1          c2
0  [10, 11]  [100, 110]
1  [12, 13]  [120, 130]
>>> for index,row in df.iterrows():
...     print(row['c1'][1])
...
11
13

I suppose this is what you want


text:
Q: How do I translate AVR GCC-style C inline assembly to Rust inline assembly? I want to translate some Arduino code written originally in C++ to Rust but this line of inline assembly is giving me trouble.
    asm volatile(
      "     lds r16, %[timer0]    \n\t" //
      #if defined(__AVR_ATmega2560__)
      "     add r16, %[toffset]   \n\t" //
      #endif
      "     subi r16, %[tsync]    \n\t" //
      "     andi r16, 7           \n\t" //
      "     call TL               \n\t" //
      "TL:                        \n\t" //
      #if defined(__AVR_ATmega2560__)
      "     pop r17               \n\t" //ATMEGA2560 has a 22bit PC!
      #endif
      "     pop r31               \n\t" //
      "     pop r30               \n\t" //
      "     adiw r30, (LW-TL-5)   \n\t" //
      "     add r30, r16          \n\t" //
      //"   adc r31, __zero_reg__ \n\t" //
      "     ijmp                  \n\t" //
      "LW:                        \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      "     nop                   \n\t" //
      //"   nop                   \n\t" //
      "LBEND:                     \n\t" //
    :
    : [timer0] "i" (&TCNT0),
      [toffset] "i" ((uint8_t)DEJITTER_OFFSET),
      [tsync] "i" ((uint8_t)DEJITTER_SYNC)
    : "r30", "r31", "r16", "r17");

my best attempt is this:
    const TCNT0: *mut u8 = 70 as *mut u8;
    const DEJITTER_OFFSET: u8 = 1;
    const DEJITTER_SYNC: i8 = -2;

    asm!(
"     lds r16, %[timer0]
\t     subi r16, %[tsync]
\t     andi r16, 7
\t     call TL
\tTL:
\t     pop r31
\t     pop r30
\t     adiw r30, (LW-TL-5)
\t     add r30, r16
\t     ijmp
\tLW:
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\tLBEND:
\t"
    :
    : "{timer0}"(&TCNT0),
      "{toffset}"(DEJITTER_OFFSET),
      "{tsync}"(DEJITTER_SYNC)
    : "r30", "r31", "r16": "volatile");

I'm still far from being able to compile. The error shown when I try to compile is:
error: couldn't allocate input reg for constraint '{timer0}'
  --> /home/kirbylife/Proyectos/rvgax/src/lib.rs:53:9
   |
53 | /         asm!(
54 | | r"     lds r16, ${timer0}
55 | |      subi r16, ${tsync}
56 | |      andi r16, 7
...  |
77 | |       "{tsync}"(DEJITTER_SYNC)
78 | |     : "r30", "r31", "r16": "volatile");
   | |_______________________________________^

I'm using Cargo and rustc 1.38.0.

A: The immediate meaning of your error is that there's not registers called timer0, toffset, and tsync. The root cause is that "{}" syntax in Rust denotes register names for constraints, not symbolic names. In other words, it corresponds to the "" stuff in GCC, not the [] stuff. I don't see a way to use symbolic names, so just switch to numerical ones instead. Also, it uses $ instead of % for substituting from constraints. Try this instead:
    const TCNT0: *mut u8 = 70 as *mut u8;
    const DEJITTER_OFFSET: u8 = 1;
    const DEJITTER_SYNC: i8 = -2;

    asm!(
"     lds r16, $0
\t     subi r16, $2
\t     andi r16, 7
\t     call TL
\tTL:
\t     pop r31
\t     pop r30
\t     adiw r30, (LW-TL-5)
\t     add r30, r16
\t     ijmp
\tLW:
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\t     nop
\tLBEND:
\t"
    :
    : "i"(&TCNT0),
      "i"(DEJITTER_OFFSET),
      "i"(DEJITTER_SYNC)
    : "r30", "r31", "r16": "volatile");

(note: untested, since I don't currently have AVR-Rust installed)


text:
Q: If $c_n=\frac{1}{\sqrt{2\pi}}\int_{-\pi}^\pi e^{i(n-i)x}dx $ ,then find $\sum_{n\in \mathbb{Z}}|c_n|^2$ Let $$c_n=\frac{1}{\sqrt{2\pi}}\int_{-\pi}^\pi e^{i(n-i)x}dx .$$ Then what will be the value of $$\sum_{n\in \mathbb{Z}}|c_n|^2.$$
My attempt:

\begin{align*}
c_n & =\frac{1}{\sqrt{2\pi}}\int_{-\pi}^\pi e^{i(n-i)x}dx\\
    & = \frac{1}{\sqrt{2\pi}}\cdot\frac{1}{i(n-i)} \left(e^{i(n-i)x}\right) \Big|_{x=-\pi}^{x=\pi}\\
& =  \frac{1}{\sqrt{2\pi}}\cdot\frac{1}{i(n-i)} \cos (n\pi) (2\sinh \pi)\\
\implies |c_n|^2 &= \frac{1}{2\pi}\cdot \frac{1}{n^2+1} \cos^2n\pi (4\sinh^2\pi)\\
&= \frac{2\sinh^2\pi}{\pi(n^2+1)}
\end{align*}
So, $$\sum_{n\in \mathbb{Z}}\frac{2\sinh^2\pi}{\pi(n^2+1)}=\frac{2\sinh^2\pi}{\pi}\sum_{n\in \mathbb{Z}}\frac{1}{n^2+1}$$
After that I stuck, what to do?

A: Hint: There is a much simpler way to go. Have you heard of Parseval? Try to write $$e^{i(n-i)x} = e^{inx} e^x $$

A: from here David Cardon
$$\sum_{k=-\infty}^{\infty}\frac1{1+k^2}=\pi\coth (\pi)$$


text:
Q: how to use which.min in subset of data frame? I have this data frame
df <- structure(list(a = 1:20, b = c(4, 2, 5, 6, 2, 4, 7, 4, 9, 7, 6, 1, 1, 5, 2, 1, 9, 8, 6, 3), c = c(340, 200, 130, 730, 710, 340, 200, 130, 730, 710, 340, 200, 130, 730, 710, 340, 200, 130, 730, 710)), .Names = c("a", "b", "c"), row.names = c(NA, -20L), class = "data.frame")

My desired output is the index of
which.min(df[1:V,3])

where V is a row number, e.g.
V <- 10

However, I'd like the following restriction:
df[which(df$a<=df$b[V]),]

I think I've tried any combinition to bring these together (e.g. with with()) but I just cannot get it to work. What do I have to do?

A: Is this what you are looking for?
which.min(with(df, df[a<=b[V],])[1:V,3])
#[1] 3

A: Using data.table instead of data.frame this can be represented in a much more readable way:
library(data.table)
dt = as.data.table(df)

dt[a <= b[V]][1:V, which.min(c)]
#[1] 3


text:
Q: UNABLE_TO_GET_ISSUER_CERT_LOCALLY error when running - webdriver-manager start through npm I am trying to integrate protractor test cases in jenkins. However I am getting UNABLE_TO_GET_ISSUER_CERT_LOCALLY.
I have tried the following
RUN npm install -g protractor
RUN webdriver-manager clean # remove the downloaded driver files
#RUN webdriver-manager update --ignore_ssl # bypass network proxy
RUN webdriver-manager update --versions.chrome 2.24 --ignore_ssl=true
RUN webdriver-manager version # 12.0.6
RUN webdriver-manager start --ignore_ssl=true
RUN (cd protractorTests and protractor conf.js)

When i am on company network i get this error. However i cant go off network when i am running these commands in jenkins.
{ Error: unable to get local issuer certificate
    at TLSSocket.<anonymous> (_tls_wrap.js:1116:38)
    at emitNone (events.js:106:13)
    at TLSSocket.emit (events.js:208:7)
    at TLSSocket._finishInit (_tls_wrap.js:643:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:473:38) code: 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY' }

A: This error message...
Error: unable to get local issuer certificate
.
'UNABLE_TO_GET_ISSUER_CERT_LOCALLY'

...implies that npm was unable to initiate protractor properly.

Solution
A quick solution would be to turn strict-ssl to false as follows:
npm config set strict-ssl false

As an alternative you can also configure the npm as follows:
npm config set registry http://registry.npmjs.org/


text:
Q: How to know if a Gradle dependency is present in the remote binary repository? I know that doing:
gradle dependencies

Let's you download (fetch) dependencies defined in the build.gradle to the local gradle cache folder.
Now, I would like to know if a given dependency actually exists in whatever repo I defined in the build.gradle without actually trying to download them.
Does anybody happen to know which is the task I should run for just checking that?
Thanks in advance community!


text:
Q: Using Foreach or another function to reduce the amount of code please help. I have such a code with Checkboxes. I need to shorten it, namely to go through it through Foreach.
If you can shorten it in another way, then please write it..
let FormData = {
   DisplayName: $("#DisplayName").is(":checked"),
   Department: $("#Department").is(":checked"),
   Post: $("#Post").is(":checked"),
   Phone: $("#Phone").is(":checked"),
   Location: $("#Location").is(":checked"),
   Dinner: $("#Dinner").is(":checked")
}
console.log(JSON.stringify(FormData));

I haven't really tried anything yet. But I didn't really find the answer I needed..

A: You can declare the fields separately in an array and then use the Array.reduce method to make the object you want:
let FormData = ['DisplayName', 'Department', 'Post', 'Phone', 'Location', 'Dinner'].reduce((acc, field) => {
    acc[field] = $(`#${field}`).is(':checked');
    return acc;
}, {});

A: If you don't know the names of the checkboxes and you want to perform this operation of collecting their state on all the checkboxes of a form, you can use this code.
var jsonObject = {};

// For each checkbox - Feed Json object
$('input[type=checkbox]').each(function(index){ jsonObject[$(this).attr('id')] = $(this).is(':checked'); });

console.log(JSON.stringify(jsonObject));

The principle is to use a selection of the checkboxes present on the page to then perform a loop on this selection and recover for each of the boxes their ID and their state.


text:
Q: Can the text cursor be accessed from the DOM? I am wondering if it is possible to access the text cursor of an <input type="text">.
Does it have a specific node in the DOM?
My initial feeling is that this is OS-specific, but if any one knows of a way to access it via JS / jQuery / CSS / XSLT then please let me know (non-cross-browser inclusive).
Purposes for this could include changing its colour, thickness, blink rate, perhaps even substituting it for a custom cursor like a DOS-esque underscore, a .gif animation, anything other than the ubiquitous 1px pipe!

A: This question has been answered before on this site. See the link below for more information.
It talks about simulating the caret with javascript and it looks like that might be the best bet.
Styling text input caret


text:
Q: Is it possible to update an image layer while panning in OpenLayers 7? I am looking for a way to update an image layer while panning the map (holding down the mouse button), like the option updateWhileInteracting in vector layers or the old loadTilesWhileInteracting for the map object.
The default behavior in OpenLayers 7 is to wait to re-render the image until you release the mouse button.
I am using the packages ol 7.1.0 and proj4js 2.8.0.
This code is similar to what I have:
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import Static from 'ol/source/ImageStatic';
import View from 'ol/View';
import proj4 from 'proj4';
import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer';
import {getCenter} from 'ol/extent';
import {register} from 'ol/proj/proj4';
import {transform} from 'ol/proj';

proj4.defs(
  'EPSG:27700',
  '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 ' +
    '+x_0=400000 +y_0=-100000 +ellps=airy ' +
    '+towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 ' +
    '+units=m +no_defs'
);
register(proj4);

const imageExtent = [0, 0, 700000, 1300000];
const imageLayer = new ImageLayer();

const map = new Map({
  layers: [
    new TileLayer({
      source: new OSM(),
    }),
    imageLayer,
  ],
  target: 'map',
  view: new View({
    center: transform(getCenter(imageExtent), 'EPSG:27700', 'EPSG:3857'),
    zoom: 4,
  }),
});

const interpolate = document.getElementById('interpolate');

function setSource() {
  const source = new Static({
    url:
      'https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/' +
      'British_National_Grid.svg/2000px-British_National_Grid.svg.png',
    crossOrigin: '',
    projection: 'EPSG:27700',
    imageExtent: imageExtent,
    interpolate: interpolate.checked,
  });
  imageLayer.setSource(source);
}
setSource();

interpolate.addEventListener('change', setSource);

External runnable demo code (based on this ol example): https://github.com/cascading-jox/pan-and-update-gis


text:
Q: How can I use child component in CurrencyInput in react native                   <CurrencyInput

                    onChangeValue={(value) => setDepositAmount(value)}
                    minValue={0}

                  >
                    <CurrencyFormater
                       amount={depositAmount}
                       prefixStyle={styles.prefixTxt}
                       amountStyle=
                       {styles.InputAmountTxt}
                       amountCentStyle={styles.CentText} />
                  </CurrencyInput>

I need to add custom currency formatter inside my currenctInput. here I used 'react-native-currency-input' library. this nicely working in ios but not working in android.


text:
Q: Getting an "expected identified" error when it perfectly on an IDE I'm using SSH Secure Shell to run and submit my assignment.  I'm getting this error right now:
In file included from a1ms4.c:15:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
In file included from contacts.c:16:0:
contacts.h:37:4: error: expected identifier or â(â before â--â token
Which is bogus because the exact same code compiled on another IDE.  These are my C files that are reporting the error.  I am not missing a ( or a { or a ; anywhere in my code.  I went through this code for hours to find a potential mistake but couldn't spot anything and despite that, it won't let me submit my assignment.
a1ms4.c
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include "contacts.h"

int main(void)
{
    struct Contact contact;

    printf("Contact Management System\n-------------------------\n");

    getName(&contact.name);

    getAddress(&contact.address);

    getNumbers(&contact.numbers);

    printf("\nContact Details\n---------------");

    printf("\nName Details");

    printf("\nFirst name: %s", contact.name.firstName);

    printf("\nMiddle initial(s): %s", contact.name.middleInitial);

    printf("\nLast name: %s", contact.name.lastName);

    printf("\n");

    printf("\nAddress Details");

    printf("\nStreet number: %d", contact.address.streetNumber);

    printf("\nStreet name: %s", contact.address.street);

    printf("\nApartment: %d", contact.address.apartmentNumber);

    printf("\nPostal code: %s", contact.address.postalCode);

    printf("\nCity: %s", contact.address.city);

    printf("\n");

    printf("\nPhone Numbers:");

    printf("\nCell phone number: %s", contact.numbers.cell);

    printf("\nHome phone number: %s", contact.numbers.home);

    printf("\nBusiness phone number: %s", contact.numbers.business);

    printf("\n");

    printf("\nStructure test for Contact using functions done!\n");

    return 0;
}

contacts.c
#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

#include "contacts.h"

void getName(struct Name *name) {
    char one;
    struct Name temporaryName;

    printf("Please enter the contact's first name: ");
    scanf(" %[^\n]", temporaryName.firstName);
    printf("Do you want to enter a middle initial(s)? (y or n): ");
    scanf(" %c", &one);

    if (one == 'y' || one == 'Y') {
        printf("Please enter the contact's middle initial(s): ");
        scanf(" %[^\n]", temporaryName.middleInitial);
    }

    printf("Please enter the contact's last name: ");
    scanf(" %[^\n]", temporaryName.lastName);

    *name = temporaryName;

    return;
}

void getAddress(struct Address *address) {
    char two;
    struct Address temporaryAddress;

    printf("Please enter the contact's street number: ");
    scanf("%d", &temporaryAddress.streetNumber);

    printf("Please enter the contact's street name: ");
    scanf(" %[^\n]", temporaryAddress.street);

    printf("Do you want to enter an appartment number? (y or n): ");
    scanf(" %c", &two);

    if (two == 'y' || two == 'Y') {
        printf("Please enter the contact's appartment number: ");
        scanf(" %d", &temporaryAddress.apartmentNumber);
    }

    printf("Please enter the contact's postal code: ");
    scanf(" %[^\n]", temporaryAddress.postalCode);

    printf("Please enter the contact's city: ");
    scanf(" %[^\n]", temporaryAddress.city);

    *address = temporaryAddress;

    return;
}

void getNumbers(struct Numbers *numbers) {
    char three, four, five;
    struct Numbers temporaryNumbers;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf(" %c", &three);

    if (three == 'y' || three == 'Y') {
        printf("Please enter the contact's cell phone number: ");
        scanf(" %[^\n]", temporaryNumbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf(" %c", &four);

    if (four == 'y' || four == 'Y') {
        printf("Please enter the contact's home phone number: ");
        scanf(" %[^\n]", temporaryNumbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf(" %c", &five);

    if (five == 'y' || five == 'Y') {
        printf("Please enter the contact's business phone number: ");
        scanf(" %[^\n]", temporaryNumbers.business);
    }

    *numbers = temporaryNumbers;
    return;
}

contacts.h
/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

struct Name {
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address {
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers {
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact {
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

A: regarding contacts.h
it is missing the multiple include guard.
#ifndef CONTACTS_H
#define CONTACTS_H
....
#endif // CONTACTS_H

it is missing the prototypes for the functions in contacts.c
void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

The contacts.h file should look like the following:
/* -------------------------------------------
Name:
Student number:
Email:
Section:
Date:
----------------------------------------------
Assignment: 1
Milestone:  4
---------------------------------------------- */

#ifndef CONTACTS_H
#define CONTACTS_H

struct Name
{
    char firstName[31];
    char middleInitial[7];
    char lastName[36];
};

struct Address
{
    int streetNumber;
    char street[41];
    int apartmentNumber;
    char postalCode[8];
    char city[41];
};

struct Numbers
{
    char cell[21];
    char home[21];
    char business[21];
};

//This is a structure that includes the 3 previous structures.
struct Contact
{
    struct Name name;
    struct Address address;
    struct Numbers numbers;
};

// prototypes for functions in contacts.c
void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

#endif // CONTACTS_H

After making the above changes to contacts.h, the code cleanly compiles

A: The error:
error: expected identifier or â(â before â--â token

suggests that you most likely have an invalid character that is unrecognized by the compiler in your code that occurs in a pattern X...stuff...X (where X represents the unrecognized character).
The line being complained about is:
scanf(" %[^\n]", temporaryAddress.street);

The likely cause of the problem is you have included (copied/pasted or otherwise somehow acquired) a unicode or html variation of '"' (double quote) surrounding your scanf format string. (this is a common occurrence when a #ldquo; or #rdquo; (left-double-quote or right-double-quote) is accidentally included in your source file).  Most likely the result of a copy/paste of " %[^\n]" from some web page. Go double check that your double quotes are all ASCII 0x22 (decimal 34) characters.
The error is not apparent in your code above (most likely because in your copy/paste to stack overflow the funky quotes were lost in translation)
The only errors you need to fix in your code (not including all little nits, etc.) are:
a1ms4.c: In function 'main':
a1ms4.c:12:5: warning: implicit declaration of function 'getName' [-Wimplicit-function-declaration]
    getName(&contact.name);
 ^
A1ms4.c:14:5: warning: implicit declaration of function 'getAddress' [-Wimplicit-function-declaration]
 getAddress(&contact.address);
 ^
a1ms4.c:16:5: warning: implicit declaration of function 'getNumbers' [-Wimplicit-function-declaration]
 getNumbers(&contact.numbers);
 ^

Which you remedy by including your function declarations from contacts.c in contacts.h, e.g. include the following at the end of contacts.h
void getName(struct Name *name);
void getAddress(struct Address *address);
void getNumbers(struct Numbers *numbers);

Your code then compiles fine -- without error or warning (well done).
The only other thing that stands out is you should initialize struct Numbers temporaryNumbers in contacts.c. Not knowing if you are compiling on Win7 with VS 10 or on a later version, simply using the C89 compatible initializer as follows works:
struct Numbers temporaryNumbers = {{0},{0},{0}};

Your code then compiles fine, e.g.
cl /nologo /Wall /wd4820 /Ox /Fecontacts /Tc a1ms4.c contacts.c

(the /Fecontacts just telling the compiler to create contacts.exe as the executable name)
(note: you can create a bin and obj directory to place the executables and object files in to keep your source directory clean. Just add /Foobj/ /Febin/contacts after /Ox to place all object files in obj (the /Fo option) and create the contacts.exe executable in bin (the /Fe option), the /wd4820 just disables the compiler reporting the number of padding bytes added to each struct as a warning)
If you do create and use the bin and obj subdirectories, then your compile string in full would be:
cl /nologo /Wall /wd4820 /Ox /Foobj/ /Febin/contacts /Tc a1ms4.c contacts.c


text:
Q: File open issue, after file deleted. fopen status is failing in VC++ fopen example
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
    FILE * pFile;
    for(int i=0; i < 1000000; i++)
    {
        bool ret = remove("C:\\abc.txt");
        pFile = fopen ("C:\\abc.txt","w");
        if (pFile!=NULL)
        {
            fputs ("fopen example",pFile);
            fclose (pFile);
        }
        else
        {
            printf("%d fopen() fails \n", count);
        }
    }
    return 0;
}

Here, after remove is called, pFile = fopen ("C:\abc.txt","w");is called,
Sometimes even in C:\ the abc.txt file is not present after remove called, but the fopen pFile pointer is null.
This is reproduced some times not always. In this example this issue is reproduced 50/60 times.
Please suggest some solution.

A: If you have already established that is is a problem of race condition in the underlying file system, the correct way to fix it is (as suggested by BLUEPIXY) to simply remove the remove call :
pFile = fopen ("C:\\abc.txt","w");

will create the file if it does not exist and truncate it to 0 size if it exists, what is exactly what you need.

A: If you need to create a file surely after the file was removed, you can delay the fopen until you confirm that the old "abc.txt" file removed.
For that you need to introduce some loop to confirm it like below,
bool ret = remove("C:\\abc.txt");
FILE * rFile;
while(true)
{
    rFile = fopen ("C:\\abc.txt","r");
    if(rfile == null)
       break; //File Removed confirmed!!
    else
       sleep(100); //Loop around again...
}
pFile = fopen ("C:\\abc.txt","w");
if (pFile!=NULL)


text:
Q: How do i run my ionic android app on an emulator without installing/running the android studio? Android studio is too heavy and slows down my pc for development. i am an ionic developer and i only need the android emulator to have a better test environment for my mobile application. I only make use of the android studio because i am trying to set up the virtual emulator following the steps in this video Ionic 3 Tutorial #16 Run app on Android Emulator
I will like to know if there is another way out to test and run my ionic app either on a real or virtual android emulator. I will like to know if i can run the emulator through my vs code or a lighter IDE

A: If you have set up the emulator already it is enough to execute "ionic cordova run android" in Visual Studio Code.
VSCode than checks for physical devices connected. If not, it will take the emulator.
Or you could use another emulator like Droid4X or BlueStacks.
=> Build the APK (ionic cordova build android) and install it on one of those.

A: One option might be use ionic serve to run it in the browser then in the console activate Toggle device toolbar is not android emulator but might be useful for mobile debug.


text:
Q: Vertical scroll over FlexSlider 2 (responsive) initializes a horizontal slide swipe Not sure I've worded it just right, but when I touch scroll over the flexslider, if my finger isn't perfectly moving in a straight vertical line, the scroll stops and the flexslider begins to scroll horizontally.
Anyone experience this or have a fix?

A: I had this issue too, but only on iOS Devices, Android worked fine.
For me, turning off CSS-Transitions did it.
While initializing your flexslider set you can set use of CSS-transitions to false like this:
<script>
    $('.flexslider').flexslider({
        useCSS: false
    });
</script>

Further information: http://www.woothemes.com/flexslider/ -> Tab "Advanced"


text:
Q: jQuery mobile button alignment issue I am trying my hand at jQuery Mobile and I find it a bit confusing because it's a mark-up driven framework.
I created a test page in which I am just trying to align one button to the right, but I am not able to do that. I tried float: right but it's not working. Although margin-left is working by giving a particular percentage, the same is not working when I resize the page.
Here is my Fiddle code. Any help would be great.

Test

            Welcome to my page

                    Username:*
                    <input id="userId1" class="required" name="uid_r" placeholder="" type="text">

                    Password:*
                    <input id="Password1" class="required" name="pwd_r" value="" type="password">

                <button id="login" data-theme="a" type="button" href="home.html" data-mini="false" data-inline="true" >Login</button>

BLOCK A ADS

                BLOCK C

A: Use ui-btn-right. It's easier, less verbose and (I think) the jquery way to do things.
Login

A: The previous answer is correct, but you should use CSS styles instead (aling="" is deprecated)

<button data-inline="true">Login</button>

A: You can run into problems if you want multiple buttons...
Try:

    <button data-inline="true">Login</button>

if you want to have multiple buttons (both left and right aligned).
If you use:

    <button data-inline="true">Login</button>

the div will start a new block below any existing buttons, so you can't have other icons on the left hand side.
Class ui-btn-icon-left|right lets you align the buttons left|right but I've found that using two buttons with ui-btn-icon-right will overlap them.
The template below worked for me for two left aligned buttons and two right in a footer:
Home
Intro

    Review
    Exit

A: Why not place your button inside a div and right align the div? everything inside the parent div including the button will be right aligned.

<button id="login" data-theme="a" type="button" href="home.html" data-mini="false" data-inline="true" >Login</button>

Check out the fiddle http://jsfiddle.net/mayooresan/96s59/2/


text:
Q: Overclocking: Memory clock changed after changing FSB from 333 to 400 MHz? I'm trying to overclock an old system with an Intel Core2Duo E8500 from 3.16 GHz to 3.8 GHz. I was able to do that by changing the FSB from 333 MHz to 400 MHz and raising the VCore to 1.3125. Now I noticed something strange: HWiNFO64 is showing the memory clock as 600 MHz now (400x1.5). Before changing the FSB it was 400 MHz (333x1.2). Is my memory really overclocked by 50% now? Is this bad for the RAM? Is there a way to get it to 400 MHz again? Or is HWiNFO64 just showing wrong information?

*

*Before overclocking my cpu: http://www.userbenchmark.com/UserRun/6646727

*After overclocking my cpu: http://www.userbenchmark.com/UserRun/6647131
The memory performance is a bit better after overclocking.


text:
Q: Dropdown menu - save the choice on reload I need to create popup language dropdown menu with country name, flag and link to the language version of the site. After user select menu item - it should take you to the needed url (language version of the page) and this choice should stay visible on the new page (after reload). Example of the menu - https://prnt.sc/sjumj8 (https://www.farfetch.com/shopping/women/items.aspx)
Here is an example of what I'm trying to create: https://jsfiddle.net/Okean/8x0atLpy/62/

[SELECT]

   Language 1

  Language 2

  Language 3

  Language 4

A:
 tag element won't ever trigger a .change event,
you can't even use li.val() as it doesn't have an actual value attribue.
So you need to workaround a little, something like this
$(document).ready(() => {
 // cache selectors for better performance
  const listItem = $("ul");
  const listSelected = listItem.find('.init');
  const allOptions = listItem.children('li:not(.init)');

  listItem.on('click', '.init', () => {
    listItem.children('li:not(.init)').toggle();
  });

  listItem.on('click', 'li:not(.init)', (e) => {
    const that = $(e.target);
    const setHTML = that.html();
    allOptions.removeClass('selected');
    that.addClass('selected');
    listSelected.html(setHTML);
    allOptions.toggle();
    sessionStorage.setItem('SelItem', setHTML);
  });

  const selectItem = $("#select-lang");
  const storedItem = sessionStorage.getItem('SelItem');
  if (storedItem) {
    listSelected.html(storedItem);
  }
});

this should work as expected, storing target
 HTML inside SelItem on sessionStorage


text:
Q: Stored procedure Date From and Date To I am trying to create a stored procedure for filtering orders. Basically the users have the option of filtering the order by date from and date to. So they can do search via date from, date to or use both if it makes sense?
Anyhow here is my SQL Server stored procedure so far
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
    @CustomerID int,
    @OrderItemWRClass varchar(max) = NULL,
    @OrderItemSKUName varchar(50) = NULL,
    @OrderItemDateFrom Datetime,
    @OrderItemDateTo Datetime
AS
BEGIN
    SET NOCOUNT ON;

    IF DATEDIFF(d, @OrderItemDateFrom, '01/01/1970') = 0
       SET @OrderItemDateFrom = null
    IF DATEDIFF(d, @OrderItemDateTo, '01/01/1970') = 0
       SET @OrderItemDateTo = null

    -- Insert statements for procedure here
    SELECT
        COM_OrderItem.OrderItemID, COM_Order.OrderID,
        COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
        COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
        COM_OrderItem.OrderItemSKUID
    FROM
        COM_OrderItem
    INNER JOIN
        COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
    WHERE
        COM_Order.OrderCustomerID = @CustomerID
        OR COM_OrderItem.OrderItemWRClass LIKE @OrderItemWRClass + '%'
        OR COM_OrderItem.OrderItemSKUName LIKE @OrderItemSKUName + '%'
        OR CONVERT(VARCHAR, COM_Order.OrderDate, 120) LIKE @OrderItemDateFrom + '%'
    ORDER BY
        COM_Order.OrderDate DESC

However I am not sure on how to put the date from (OrderItemDateFrom) and date to (OrderItemDateTo) in the final SQL statement?
Should I be using OR CONVERT(VARCHAR, COM_Order.OrderDate, 120) LIKE @OrderItemDateFrom + '%' -- which gives me an error

Conversion failed when converting date and/or time from character string.

I know in a normal SQL query I would use Between OrderItemDateFrom and OrderItemDateTo
Thanks

A: Use this logic
    ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
-- Add the parameters for the stored procedure here
@CustomerID int,
@OrderItemWRClass varchar(max) = NULL,
@OrderItemSKUName varchar(50) = NULL,
@OrderItemDateFrom Datetime,
@OrderItemDateTo Datetime
AS
BEGIN

SET NOCOUNT ON;

IF DATEDIFF(d,@OrderItemDateFrom,'01/01/1970')=0 SET @OrderItemDateFrom = '01/01/1970';
IF DATEDIFF(d,@OrderItemDateTo,'01/01/1970')=0 SET @OrderItemDateTo = '31/12/2199';

-- Insert statements for procedure here
SELECT COM_OrderItem.OrderItemID, COM_Order.OrderID, COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount, COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
COM_OrderItem.OrderItemSKUID
FROM COM_OrderItem
INNER JOIN COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE COM_Order.OrderCustomerID = @CustomerID OR COM_OrderItem.OrderItemWRClass LIKE @OrderItemWRClass + '%' OR COM_OrderItem.OrderItemSKUName LIKE @OrderItemSKUName + '%'
OR (COM_OrderDate>=@OrderItemDateFrom && COM_OrderDate<=@OrderItemDateTo )
ORDER BY COM_Order.OrderDate DESC

Try it . It should work.

A: Your logic can be simplified a little by allowing NULL values for @OrderItemDateFrom and @OrderItemDateTo. Also, if filters values and column values are all DATETIMEs, you should try to compare directly to allow indexes usages (if any applied on the DATETIME column):
ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
    @CustomerID int,
    @OrderItemWRClass varchar(max) = NULL,
    @OrderItemSKUName varchar(50) = NULL,
    @OrderItemDateFrom Datetime = NULL, -- TODO: change caller to not provide parameter, or leave it to null
    @OrderItemDateTo Datetime = NULL    -- TODO: change caller to not provide parameter, or leave it to null
AS
BEGIN
    SET NOCOUNT ON;

    -- when working with dates try to use an unambiguous format like 'YYYY-MM-DD'
    SET @OrderItemDateFrom = ISNULL(@OrderItemDateFrom, '1970-01-01')
    -- assign a very large date to act like not provided
    -- going one day after to catch DATETIMEs with provided time
    SET @OrderItemDateTo = DATEADD(day, 1, ISNULL(@OrderItemDateTo, '3000-01-01'))

    -- Insert statements for procedure here
    SELECT
        COM_OrderItem.OrderItemID, COM_Order.OrderID,
        COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
        COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
        COM_OrderItem.OrderItemSKUID
    FROM COM_OrderItem
    INNER JOIN COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
    WHERE COM_Order.OrderCustomerID = @CustomerID
        OR COM_OrderItem.OrderItemWRClass LIKE @OrderItemWRClass + '%'
        OR COM_OrderItem.OrderItemSKUName LIKE @OrderItemSKUName + '%'
        -- between can be used
        OR (COM_OrderDate BETWEEN @OrderItemDateFrom AND @OrderItemDateTo)
    ORDER BY
        COM_Order.OrderDate DESC
END

Another option is to use dynamic SQL and construct it based on parameters values (i.e. insert WHERE condition if filter value is provided). This is particularly useful when filters numbers is relatively low compared to the total number of filters, as ORs are not performance friendly.
NOTE: shouldn't your filters apply in conjuction (i.e. use AND instead of OR)? It would make sense to allow the user to filter by several value in the same time.

A: ALTER PROCEDURE [dbo].[CN_GetOrderItemByCustID]
@CustomerID int,
@OrderItemWRClass varchar(max) = NULL,
@OrderItemSKUName varchar(50) = NULL,
@OrderItemDateFrom Datetime,
@OrderItemDateTo Datetime
AS
BEGIN
SET NOCOUNT ON;

IF DATEDIFF(d, @OrderItemDateFrom, '01/01/1970') = 0
   SET @OrderItemDateFrom = null
IF DATEDIFF(d, @OrderItemDateTo, '01/01/1970') = 0
   SET @OrderItemDateTo = null

-- Insert statements for procedure here
SELECT
    COM_OrderItem.OrderItemID, COM_Order.OrderID,
    COM_Order.OrderDate, COM_OrderItem.OrderItemUnitCount,
    COM_OrderItem.OrderItemStatus, COM_OrderItem.OrderItemSKUNAME,
    COM_OrderItem.OrderItemSKUID
FROM
    COM_OrderItem
INNER JOIN
    COM_Order ON COM_Order.OrderID = COM_OrderItem.OrderItemOrderID
WHERE
    COM_Order.OrderCustomerID = @CustomerID
    OR COM_OrderItem.OrderItemWRClass LIKE @OrderItemWRClass + '%'
    OR COM_OrderItem.OrderItemSKUName LIKE @OrderItemSKUName + '%'
    OR (@OrderItemDateFrom IS NULL OR COM_Order.OrderDate >=@OrderItemDateFrom)
    OR (@OrderItemDateTo IS NULL OR COM_Order.OrderDate <=@OrderItemDateTo)
ORDER BY
    COM_Order.OrderDate DESC

You should Try this.
OR (@OrderItemDateFrom IS NULL OR COM_Order.OrderDate >=@OrderItemDateFrom)
OR (@OrderItemDateTo IS NULL OR COM_Order.OrderDate <=@OrderItemDateTo)

Just Edit and try this condition..


text:
Q: php take data from mysql db and store them in xml file i write a php file to connect in a mysql db and take back the last insert. i want this last insert to store in xml file but i didnt find any solution. i want the values from mysql to store them in a XML file but i dont know the way.my code is this:
'<?php
 mysql_connect("000.000.000.000", "xxxx", "xxxx") or die(mysql_error());
 mysql_select_db("arduino_db") or die(mysql_error());
 $data = mysql_query("SELECT * FROM `weather` order by `add` desc limit 1")
 or die(mysql_error());
 echo "
";
 while($info = mysql_fetch_array( $data ))
 {
 echo "
";
 echo "currentDirection :	 ".$info['currentDirection'] . "	 ";
 echo "
";
 echo "light :	 ".$info['light'] . "	 ";
 echo "
";
 echo "pressure :	 ".$info['pressure'] . "	 ";
 echo "
";
 echo "lhumidity :	 ".$info['humidity'] . "	 ";
 echo "
";
 echo "tempC :	 ".$info['tempC'] . "	 ";
 echo "
";
 echo "rainin :	 ".$info['rainin'] . "	 ";
 echo "
";
 echo "windSpeed :	 ".$info['windSpeed'] . "	 ";
 }
 echo "
";

 ?> '

A: $xml_file = new DOMDocument();

$windSpeed = $info['windSpeed'];

$xml_windSpeed = $xml->createElement("windSpeed");
$xml_windSpeed->appendChild($windSpeed);
$xml_file->appendChild( $xml_windSpeed );

$xml_file->save("/documents/windSpeed.xml"); //Put there your path

A: 1. The answer to your question - UPDATE
With rows:
<?php
mysql_connect("000.000.000.000", "xxxx", "xxxx") or die(mysql_error());
mysql_select_db("arduino_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM `weather` order by `add` desc limit 1") or die(mysql_error());

$xml = new DOMDocument( "1.0", "UTF-8" );

while($info = mysql_fetch_array( $data ))
{
    $row = $xml->createElement( 'row' . $i++ . '' );
    $xml_row->appendChild( $row );

    $currentDirection = $xml->createElement( 'currentDirection', '' . $info['currentDirection'] . '' );
    $xml_row->appendChild( $currentDirection );
    $light = $xml->createElement( 'light', '' . $info['light'] . '' );
    $xml_row->appendChild( $light );
    $pressure = $xml->createElement( 'pressure', '' . $info['pressure'] . '' );
    $xml_row->appendChild( $pressure );
    $humidity = $xml->createElement( 'humidity', '' . $info['humidity'] . '' );
    $xml_row->appendChild( $humidity );
    $tempC = $xml->createElement( 'tempC', '' . $info['tempC'] . '' );
    $xml_row->appendChild( $tempC );
    $rainin = $xml->createElement( 'rainin', '' . $info['rainin'] . '' );
    $xml_row->appendChild( $rainin );
    $windSpeed = $xml->createElement( 'windSpeed', '' . $info['windSpeed'] . '' );
    $xml_row->appendChild( $windSpeed );
}

$xml_file_contents = $xml->saveXML();
$filename = 'your_xml_file_name.xml';

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $xml_file_contents will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
     echo "Cannot open file ($filename)";
     exit;
    }

    // Write $xml_file_contents to our opened file.
    if (fwrite($handle, $xml_file_contents) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
    }

    echo "Success, wrote ($xml_file_contents) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}

?>

1. The answer to your question
<?php
mysql_connect("000.000.000.000", "xxxx", "xxxx") or die(mysql_error());
mysql_select_db("arduino_db") or die(mysql_error());
$data = mysql_query("SELECT * FROM `weather` order by `add` desc limit 1") or die(mysql_error());

$xml = new DOMDocument( "1.0", "UTF-8" );

while($info = mysql_fetch_array( $data ))
{
    $currentDirection = $xml->createElement( 'currentDirection', '' . $info['currentDirection'] . '' );
    $xml->appendChild( $currentDirection );
    $light = $xml->createElement( 'light', '' . $info['light'] . '' );
    $xml->appendChild( $light );
    $pressure = $xml->createElement( 'pressure', '' . $info['pressure'] . '' );
    $xml->appendChild( $pressure );
    $humidity = $xml->createElement( 'humidity', '' . $info['humidity'] . '' );
    $xml->appendChild( $humidity );
    $tempC = $xml->createElement( 'tempC', '' . $info['tempC'] . '' );
    $xml->appendChild( $tempC );
    $rainin = $xml->createElement( 'rainin', '' . $info['rainin'] . '' );
    $xml->appendChild( $rainin );
    $windSpeed = $xml->createElement( 'windSpeed', '' . $info['windSpeed'] . '' );
    $xml->appendChild( $windSpeed );
}

$xml_file_contents = $xml->saveXML();
$filename = 'your_xml_file_name.xml';

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $xml_file_contents will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
     echo "Cannot open file ($filename)";
     exit;
    }

    // Write $xml_file_contents to our opened file.
    if (fwrite($handle, $xml_file_contents) === FALSE) {
    echo "Cannot write to file ($filename)";
    exit;
    }

    echo "Success, wrote ($xml_file_contents) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}

?>

2. More about writing XML files
// "Create" the document.
$xml = new DOMDocument( "1.0", "ISO-8859-15" ); // or 'UTF-8'

// Create some elements.
$xml_album = $xml->createElement( "Album" );
$xml_track = $xml->createElement( "Track", "The ninth symphony" );

// Set the attributes.
$xml_track->setAttribute( "length", "0:01:15" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );

// Create another element, just to show you can add any (realistic to computer) number of sublevels.
$xml_note = $xml->createElement( "Note", "The last symphony composed by Ludwig van Beethoven." );

// Append the whole bunch.
$xml_track->appendChild( $xml_note );
$xml_album->appendChild( $xml_track );

// Repeat the above with some different values..
$xml_track = $xml->createElement( "Track", "Highway Blues" );

$xml_track->setAttribute( "length", "0:01:33" );
$xml_track->setAttribute( "bitrate", "64kb/s" );
$xml_track->setAttribute( "channels", "2" );
$xml_album->appendChild( $xml_track );

$xml->appendChild( $xml_album );

// Parse the XML.
print $xml->saveXML();

Source: http://www.php.net/manual/en/class.domdocument.php
createElement( name, value ) // just to clarify how this will look in an xml file: <name>value</name>

3. more about writing normal text files
This is the minimum required code, to write some data to a file:
$fp = fopen('data.txt', 'w');
fwrite($fp, '' . $your_text . '');
fclose($fp);

But use something like this, for better security:
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
       echo "Cannot open file ($filename)";
       exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
      echo "Cannot write to file ($filename)";
      exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

Source: http://www.php.net/manual/en/function.fwrite.php
You can write objects/arrays to a file with JSON (which serializes when writing and deserializes when reading the data): http://si1.php.net/manual/en/book.json.php
Check these 2 links also: http://si1.php.net/manual/en/function.json-encode.php and http://si1.php.net/manual/en/function.json-decode.php
And then you can read your file with :
$file = file_get_contents('./people.txt');

or to read only a part of the file:
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>

http://www.php.net/manual/en/function.file-get-contents.php

A: Your question is pretty broad and you might just have it more easy to isolate sub-problems here. Stackoverflow works best asking a single, concrete question.

*

*How do I get the last inserted ID of a MySQL table in PHP?

*How to append to a XML file with PHP preferably with SimpleXML
So if you divide your problem, you can more easily solve the overall problem by solving the sub-steps. Not only is that easier then for you, but also the format of Stackoverflow requires that you ask a single, concrete programming question at a time. Otherwise the answers tend to become bloated and aren't helpful any longer. Because they become unclear over time, your question is easy to misread etc. .
I hope these two example questions leave you at least the pointers to write the code you need.
I also highly recommend you to use a more modern database API (preferable PDO), as it's easier to deal with (e.g. overall API and the looping is much improved).


text:
Q: Running executables on nfs with "./" command I have a small cluster system running on Centos 7. I've setup nfs and pbs pro to run jobs on parallel. While everything was working smoothly, I guessed, at some point, I messed up something. Thus, some of the nodes stopped running jobs and started giving errors such as "permission denied" for the executables. Executable file is located inside the nfs directory. I tried to run the executable specifically on that problematic node. But it does not run with "./executable_file" command. However, it can be executed with "bash executable_file" command. Other slave nodes can execute the file with "./" and "bash" command without any issue. So, I assume this may be the reason my jobs are failing on that specific node. Would appreciate it if someone tell me how to set up/mount nfs with running executables with "./" .

A: When I checked the /etc/mtab file, I noticed "noexec" inside it. I removed mtab file and then unmount and remounted NFS directory. As a last step, /etc/fstab is updated with "exec" and mounted again with mount-a without restarting the node.


text:
Q: how to 'Find lines' in binary picture? apology first if all these might seem confusing. i try to make it as clear as possible.
One challenge question from my class is to  write a program which finds line segments on black and white images. The lines will always be one pixel wide, black on a white background, no grayscale or other colors. Each image will contain up to 2 lines. The output of my program should be the coordinates of the start and end of each line segment if there are any. The coordinates will be always whole pixel coordinates.
The images will be represented by text files. One row in the file is one row of the image. Each character in the row is one pixel. A pixel can have a value of 0 or 1. 0 means, this pixel is not part of a line (it's white). 1 means, this pixel is part of a line (it's black).
As usual, when representing images, the top-left pixel has (0, 0) coordinates. The X axis increases to the right, whereas the Y axis increases downwards.
In the regular input set the lines will not be touching or intersecting each other.
The output of the program should have one row for each image. The row should begin with the filename of the image, followed by the coordinates of the endpoints. Each coordinate should be surrounded by parentheses. The first value for each coordinate should be the X position, the second the Y position. The values should be separated by comas. The coordinates should be separated by spaces. The two endpoints of the same line should follow each other in the output.
So I also get a set of 'pictures' composed of 1s and 0s. basically it looks like one below:

I am completely out of any clue how to even start on this kind of question. There is even a bonus part which they ask you to make the program able to find lines which touch each other
Thanks a lot in advance!
Here is a sample of one of the 'picture' I got. it is actually a txt file since everything inside is just 0s and 1s
000000000000000000000000000100000000000000
000000000000000000000000000100000000000000
000000000000000000000000000100000000000000
000000000000000000000000000100000000000000
000000000000000000000000001000000000000000
000000000000000000000000001000000000000000
000000000000000000000000001000000000000000
000000000000000000000000001000000000000000
000000000000000000000000001000000000000000
000000000000000000000000010000000000000000
000000000000000000000000010000000000000000
000000000000000000000000010000000000000000
000000000000000000000000010000000000000000
000000000000000000000000010000000000000000
000000000000000000000000010000000000000000
000000000000000000000000100000000000000000
000000000000000000000000100000000000000000
000000000000000000000000100000000000000000
000000000000000000000000100000000000000000
000000000000000000000000100000000000000000
000000000000000000000001000000000000000000
000000000000000000000001000000000000000000
000000000000000000000001000000000000000000

A: If the lines are not touching each other you can check every pixel in your image one after another. As soon as you find a line (which you have not already seen) you follow this line and remember it.
An algorithm in pseudocode could look like this:
list<lines> find_lines(int[][] image) {//here the image is represented as an int array, because it's only numbers
    lines = new empty list //where the entries in this list should be lines consisting of coordinates

    for int y from 0 to image.length {//iterate over each line of the image
        for int x from 0 to image[0].length {//iterate over each column of the image
            if (image[y][x] == 1 && coordinate(x, y) not in lines) {//line that is not known yet
                lines.add(follow_line(image, x, y))//follow the line and add the new line to the list
            }
        }
    }

    return lines
}

line follow_line(int[][] image, int x, int y) {
    line = new empty list of coordinates //the coordinates of all pixels in the line
    new_fields_in_line = new empty list of coordinates //the coordinates of new found pixels in the line

    new_fields_in_line.add(coordinate(x, y)) //add the first known pixel to start the loop

    while (!new_fields_in_line.isEmpty()) {
        line.addAll(new_fields_in_line) //add all fields found to the list of lines

        //find all pixels that are part of the line by finding the ones near the new_fields_in_line coordinates
        next_new_fields = empty list of coordinates
        foreach field in new_fields_in_line {
            if (a pixel near the current field is also a black pixel) {
                next_new_fields.add(the found pixel)
            }
        }

        new_fields_in_line.clear() //empty the list of new fields
        new_fields_in_line.addAll(next_new_fields)
    }

    return line

An algorithm like this will find all the lines in your image. Afterwards you just have to print the lines in the correct formatt.
    }


text:
Q: RoboSpice and TCP Connection I'm not sure if I should post this here or on github, but I got a weird ticket raised by a client saying :

One of the problem we see, that might be the root cause of the API
  dying is that the API replies to the App with the data and HTTP 200 OK
  and closes the TCP session.
However the app does not acknowledge the closing of the session and
  continues trying to use the same old TCP session that is in close wait
  state on the server.

Now I'm not an HTTP stack expert nor have time to dig in the Robospice code, so my question is : Is it a client side or a server side issue ? If it's client side, is it a Robospice issue, or a "code12, dumb programmer at work" issue.
The API is written in Python (Flask) and runs along an OpenStack infrastructure.
My project currently use :
Android 4.+
compile 'com.octo.android.robospice:robospice-retrofit:1.4.14'

Thanks for any suggestions !


text:
Q: Compound distribution of Uniform and Exponential I am trying to take the compound distribution of a uniform distribution on the interval $(0, \frac{t}{2})$ where $t$ is parameterized by the exponential distribution $\varepsilon (\lambda)$.
Taking the compound distribution I believe gives the following integral
$$\int_0^\infty \frac 2 t \lambda e^{-\lambda t} \, dt$$
I am not able to evaluate this integral. Have I made a mistake in my reasoning anywhere. Any help would be appreciated.

A: First of all, notice that:
$$P(X<x \mid  T = t) = \begin{cases}
\displaystyle\int_0^x\frac{2}{t}ds & \text{if } x<\displaystyle\frac{t}{2}\\
0 & \text{if } x>\displaystyle\frac{t}{2}\\
\end{cases} = \begin{cases}
\displaystyle\frac{2x}{t} & \text{if } x<\displaystyle\frac{t}{2}\\
0 & \text{if } x>\displaystyle\frac{t}{2}\\
\end{cases}$$
Then, using the law of total probability, we get that:
$$P(X<x) = \int_0^{+\infty}P(X<x \mid T = t) f_T(t) \, dt,$$
where $f_T(t) = \lambda e^{-\lambda t}$ is the pdf of $T$. The previous integral is rewritten as follows:
$$P(X<x) = \int_{2x}^{+\infty} \frac{2x}{t} \lambda e^{-\lambda t} \, dt.$$
Unfortunately, the last integral can't be solved using known functions. Moreover, as pointed out by Michael Hardy, I'm not sure that it converges.


text:
Q: When did server add listener to request in Node.js? var http = require("http");

http.createServer(function(request, response) {
    request.addListener("data", function(postDataChunk) {
        // some code here
    });

    request.addListener("end", function() {
        // some code here
    });
}).listen(8888);

As I know, in node, the anonymous function would execute when server received request. But in the sample code, the function would add listener to request which had received by server. However, it really works.
And my question is why it works. When did server add listener to request in node?

A: It's not entirely clear to me what exactly which part of the process you're asking for help understand, but here's how your code works.

*

*http.createServer() creates a server and the callback function you pass it is automatically registered as an event handler for the request event.

*The request event calls it's callback with two arguments, the request and response objects.  The request object is of type http.IncomingMessage which implements the readable stream interface.

*When the request callback is call, it executes request.addListener('data', ...) and this adds a listener for incoming data on the readable stream in the request argument.

*So, as soon as data is available on that readable stream, it will call that listener with that chunk of data.  You can read a lot more about readable streams in the node doc to understand better how they work.

*The listener for the end event tells you when the readable stream has finished giving you its data.

When did server add listener to request in node?

This happens each time there is a new incoming http request to the server.  That's when the callback to the http.createServer() is called.  And, for each new incoming request, a new http.IncomingMessage object is created for that callback.


text:
Q: Start VPN from SSIS package? Using SSIS I need to retrieve data from a server outside my network/domain.
I can only get to this server through a VPN.
I created 2 packages:

*

*StartVPN - using some VB this package starts the VPN. Works great. :)

*Import Files - This package is called from StartVPN and should import some data.

When I run package 2 directly with the VPN already started this package runs great.
When I run package 2 from package 1 without the task that starts the VPN but with the VPN manually started this package runs great.
However, if I call this package from package 1 it fails with the error:
The AcquireConnection method call to the connection manager "MyConnection" failed with error code 0xC0202009.
It does not matter if the VPN was already started or not.
How can I runn package 2 with the VPN only running during execution of the package?

A: I solved it!
I needed to add a wait between package1 (starting the VPN) and package2 (doing the import)
After setting up the VPN, package1 was made to wait 5 secs before continuing. Now everything works swell :)
SO: Package 1 containg a VB scriptask for starting up the (existing) VPN:
Dim VPNConnectionName As String = "MyVPN"
Dim VPNlogin As String = "MyUser"
Dim VPNPassword As String = "MyPass"

Shell("RASDIAL " & Chr(34) & VPNConnectionName & Chr(34) & " " & VPNlogin & " " & VPNPassword, vbNormalFocus)
        '
System.Threading.Thread.Sleep(5000)
Dts.TaskResult = ScriptResults.Success

Then from package1 call package 2 for the actual import
And  a VB scripttask for closing the VPN:
Dim VPNConnectionName As String = "MyConnection"

Shell("RASDIAL " & Chr(34) & VPNConnectionName & Chr(34) & " /DISCONNECT", vbNormalFocus)
            '
Dts.TaskResult = ScriptResults.Success


text:
Q: R plot(): Why does xlab only appear after quartz window size adjustment? When I use the plot() command internally in R, the xlab doesn't appear until I resize the quartz window. Why?
Reproducible example:
 plot(x = c(1,2,3), y = c(1,2,3), xlab = "where are you?")

When I plot this I do not see the xlab until making an arbitrary resize of the window.
My sessionInfo():
> sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] grid      splines   stats     graphics  grDevices utils
[7] datasets  methods   base

other attached packages:
 [1] pROC_1.5.4         snowfall_1.84-4    snow_0.3-12
 [4] glmnet_1.9-5       Matrix_1.0-12      languageR_1.4
 [7] e1071_1.6-1        class_7.3-7        caret_5.16-24
[10] reshape2_1.2.2     plyr_1.8           lattice_0.20-15
[13] foreach_1.4.1      cluster_1.14.4     randomForest_4.6-7
[16] neuralnet_1.32     verification_1.35  CircStats_0.2-4
[19] boot_1.3-9         fields_6.8         maps_2.3-2
[22] spam_0.29-3        ROCR_1.0-5         gplots_2.11.3
[25] MASS_7.3-28        KernSmooth_2.23-10 caTools_1.14
[28] gdata_2.13.2       relaxo_0.1-2       quadprog_1.5-5
[31] lasso2_1.2-16      ada_2.0-3          nnet_7.3-7
[34] lars_1.2           rpart_4.1-1        waveslim_1.7.1
[37] gtools_3.0.0       Hmisc_3.12-2       Formula_1.1-1
[40] survival_2.37-4    foreign_0.8-54

loaded via a namespace (and not attached):
[1] bitops_1.0-5    codetools_0.2-8 iterators_1.0.6
[4] stringr_0.6.2   tools_3.0.1


text:
Q: create a basic contact form on the homepage of a rails app (step by step) I would like to create a simple contact form on a one page site for the user, where the will write to the website owner.
I just need a basic form with this simple fields:
Name
Email
Message (text)
The logic is simple: a user write a feedback in the form >> the app check if everything is correct (I need a validation),take the form inputs and send a mail to a specific email (the admin email).
No data saved, just send a mail.
I am new to RoR (really at the beginning) and I have tried to find some tutorials and gems to create this form with controller, models etc.
But I didn't find a solution...
Everybody could help me?
Please let me know, thanks


text:
Q: Perl one-liner if else logic I'm evaluating whether or not certain variables match expected values.  The variables are set in memory by a certain program, the values of which can be access from the shell with a custom program.
I'm piping the output of the shell command to awk to get the specific field I want and then I want to run it through perl to see if it matches the expected value.  For example,
ysgrp autostart | awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'

However, I'm getting complaints from perl about compilation errors near "} else".  How does one handle if/then/else logic in a perl one-liner?

A: This part:
awk -F\: '{print $1}' | perl -e 'print {"True"} else {print "False"} if /on/'

can be handled in perl (if I remember awk correctly):
perl -F/:/ -lane 'print $F[0] =~ /on/ ? "True" : "False"'

Note the use of the -n switch, without which your perl one-liner will not work. Also note the -l switch, which adds a newline to your print, which is something I assume you want. Otherwise your output will be something like:
TrueTrueTrueFalseTrueFalse

A: You can't use an else condition in a postfix conditional. You can either use a ternary conditional operator like this:
perl -e 'print /on/ ? "True" : "False"'

Or use explicit blocks like this:
perl -e 'if ( /on/ ) { print "True" } else { print "False" }'

A: One does not, except by using the ternary ?: operator; the foo if bar syntax does not support else.

A: You could do:
 ... | perl -ne 'print /on/ ? "True" : "False"'

but please don't!  You'd be better off doing:
... | grep -qF on && echo True || echo False


text:
Q: .net core handle PostreSQL db exceptions I have a .net core web api. Db is PostreSQL. I have a simple POST request that create an entity with two fields:
    public class ClientDto{
        public string Name {get;set;}
        public int ClientId{get;set;}
}

ClientId - FK foreign key to table Clients.
Some client (Postman for exapmle) execute request, but in data model send ClientId that not exists in db.
I have global exeption handler and there I handle db exception, but exception object don't include separated information.
I would like to show to user beautiful message something like "Client with id = 1 not exists".
What the best practis to handle db exceptions?
May be before save object in db I need check if client with id = 1 exists in db? But it is an additional query.

A:
May be before save object in db I need check if client with id = 1 exists in db? But it is an additional query.

I'd do this.
If your client doesn't give you good information in its exception then your probably better to do the additional query. If you're querying on an indexed field (which i'd expect given you are using a foreign key) then it will be a very quick query.
Exception throwing and catching is fairly expensive anyway and i'd probably be happy enough with the extra call.


text:
Q: Bernoulli trials are run until 3 successful trials are completed. If probability of a success is 0.3 what is the expected number of failures? Bernoulli trials are run until 3 successful trials are completed. If probability of a success is 0.3 what is the expected number of failures?
My attempt:
Average number of successes in a n trials is $E[X] = np$. We know that the last trial must be a success, so perhaps we could find how many trails were likely made before the last trial in this way $n*0.3=2$, we get $n=6.7\approx 7$, then the answer is 7-2=5. I have no faith in this solution and I would like to see what you think is the correct way to solve this.

A: Let $p$ be the probability of success (here $p = 0.3$), and $q = 1 - p$, the probability of failure (here $q = 0.7$). $X = k$ if there are $k - 1$ trials with exactly $2$ successes and $k - 3$ failures, and the $k$th trial is success.
The probability of exactly $2$ successes in a sequence of $k - 1$ trials is $^{k-1}\text{C}_2\, p^2 q^{k - 3}$ (by using a binomial distribution with $n = k - 1$). Multiplying this with $p$, the probability of success in the $k$th trial, we obtain
$$P(X = k) = ^{k-1}\text{C}_2\, p^3 q^{k - 3},\ k = 3, 4, \ldots$$
$\begin{align}
E[X] & = \sum_{k = 3}^{\infty} kP(X = k)\\
\mu & = \sum_k \dfrac{k(k - 1)(k - 2)}{2} p^3 q^{k - 3}\\
 & = \dfrac{p^3}{2}\sum_k k(k - 1)(k - 2) q^{k - 3}\\
\int \mu\, dq & = \dfrac{p^3}{2}\sum_k k(k - 1) q^{k - 2}\\
\iint \mu\, dq\,dq & = \dfrac{p^3}{2}\sum_k k q^{k-1}\\
\iiint \mu\, dq\,dq\,dq & = \dfrac{p^3}{2}\sum_k q^k\\
 & = \dfrac{p^3}{2} \left(\dfrac{1}{1 - q}\right)\\
\mu & = \dfrac{p^3}{2}\dfrac{d^3}{dq^3}\left( \dfrac{1}{1 - q} \right)\\
& = \dfrac{p^3}{2}\left( \dfrac{6}{(1 - q)^4} \right)\\
& = \dfrac{p^3}{2}\left( \dfrac{6}{p^4} \right)\\
& = \boxed{\dfrac{3}{p}}
\end{align}$
Thus, the expected number of trials is $\dfrac{3}{p} = \dfrac{3}{0.3} = 10$. Then the expected number of failures is $10 - 3 = 7$.

A: The answer 3/p-3 is correct. Simple derivation: the length of each of the 3 failure runs (delineated by single successes) has a geometric distribution p(1-p)^k with well known expectation value 1/p-1. The expected total length of 3 such  (independent) failure runs is then just 3 times that number.


text:
Q: Tag Tally Discrepancy between Web and Mobile Client Mobile App: Stack Exchange iOS App version 1.6.6.2
Does anyone else have a discrepancy between their Tag Tallies when looking in the web (my dba.se profile):

as compared to my dba.se profile in the mobile app:

In particular, I'm looking at the 389 vs 486 for the sql-server tag (as well as the other sql-server-20XX tags) and also the total count being reflected of 186 vs 166.  I'm not worried about the numbers so much as the fact that they just don't match.
Upon further digging this looks like this is site agnostic as my Stack Overflow profile shows similar discrepancies matching the calculation breakdowns as identified by Peter Vandivier in the answers below.
Stack Overflow Web site:

Stack Overflow Profile in Mobile Client:

A: Per this Meta answer, this looks to be intentional.
The desktop site aggregation sums only answers while mobile sums both questions and answers (display format being sum-tag-count). Curiously - drill down on both sites reveals all posts regardless of type. Count appears to be consistent between the two.
Anecdotally from my top tags (as of right now, see screencaps below) I'll select a few that are easy to compare
+-----------------+-------------+-------------+
|                 | mobile      | desktop     |
+-----------------+-----+-------+-----+-------+
| tag             | sum | count | sum | count |
+-----------------+-----+-------+-----+-------+
| restore         | 13  | 3     | 8   | 3     |
+-----------------+-----+-------+-----+-------+
| powershell      | 11  | 5     | 7   | 5     |
+-----------------+-----+-------+-----+-------+
| sql-server-2012 | 11  | 4     | 7   | 4     |
+-----------------+-----+-------+-----+-------+

restore drill-down (screencap) shows...

*

*+1 (answer)

*+7 (answer)

*+5 (question)

..which should be 13/3 mobile | 8/3 desktop
powershell drill-down (screencap) shows...

*

*+2 (question)

*+2 (answer)

*+2 (question)

*+1 (answer)

*+4 (answer)

...which should be 11/5 mobile | 7/5 desktop
sql-server-2012 drill-down (screencap) shows...

*

*+1 (answer)

*+2 (answer)

*+2 (answer) (community wiki - but this isn't displayed in the summary page)

*+4 (answer)

*+4 (question)

...which should be 13/5 mobile | 9/5 desktop until you exclude the community wiki answer which brings it to the displayed tallies of 11/4 mobile | 7/4 desktop


text:
Q: Not able to write to a json file I'm trying to be able to write to a json file. I think maybe I missed something because I'm not able to write to the json file and no errors show up.
Here is my code
public function writingToFile($id, $from, $to)
{

    mkdir($this->getStoragePath($id, "/file/$to"));

    foreach(['name', 'area'] as $file){
        copy($this->getStoragePath($id, "/file/$from/$file.json"), $this->getStoragePath($id, "/file/$to/$file.json"));
    }

    $version_file->area = $to;
    $json_file = file_get_contents($this->getStoragePath($id, '/file/$to/area.json'));
    $version_file = json_decode($json_file);

    file_put_contents($this->getStoragePath($id, "/file/$to/area.json"), json_encode($version_file, JSON_PRETTY_PRINT));

}


text:
Q: Kubernetes DNS resolution issues with CoreDNS and Ubuntu 18.04 cluster deployed with Kubeadm I have a Kubernetes cluster deployed on an OVH baremetal servers. Cluster was deployed using Kubeadm and Operating system is Ubuntu 18.04.5 LTS. Calico is used as the CNI and I'm having intermittent DNS resolution issues with my PODs.
here is the output of the DNS resolution in a pod
bash-5.0# nslookup s3.amazonaws.com
Server:     10.96.0.10
Address:    10.96.0.10:53

Non-authoritative answer:
Name:   s3.amazonaws.com
Address: 52.217.88.54

Non-authoritative answer:

bash-5.0# nslookup s3.amazonaws.com
Server:     10.96.0.10
Address:    10.96.0.10:53

Name:   s3.amazonaws.com
Address: 52.217.88.54

bash-5.0# nslookup s3.amazonaws.com
;; connection timed out; no servers could be reached

bash-5.0# nslookup s3.amazonaws.com
;; connection timed out; no servers could be reached

bash-5.0# nslookup s3.amazonaws.com
;; connection timed out; no servers could be reached

bash-5.0# nslookup s3.amazonaws.com
Server:     10.96.0.10
Address:    10.96.0.10:53

Non-authoritative answer:

Non-authoritative answer:
Name:   s3.amazonaws.com
Address: 52.217.102.142

I know some issues are there with Ubuntu and kubeadm clusters but any comment or answer was not able to fix my issues. Initially, I felt that this is because of the 127.0.0.1 nameserver entry in my /etc/resolv.conf file. If I update the file it is being updated by the /run/systemd/resolve/resolv.conf file and I have stopped the systemd-resolved.service and changed the DNS servers to google DNS. Even after that, I didn't see any improvements. If I changed the /etc/resolv.conf file inside the pod working as expected.
I also removed the files entry in the nsswitch.conf file to check the DNS servers directly as a troubleshooting step and it worked soon after the change and new pod is having the issue again.
here is the host entry
cat /etc/nsswitch.conf | grep hosts
hosts:          dns

Since the intermittent connectivity I can confirm that no Firewall port issues and I'm clueless about this issue. Can anyone please assist me to fix this.

A: You can add this ConfiMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: kube-dns
  namespace: kube-system
data:
  upstreamNameservers: |
    ["8.8.8.8"]

This will redirect the dns resolution to Google DNS
https://blog.yaakov.online/kubernetes-getting-pods-to-talk-to-the-internet


text:
Q: Jenkins release automation Is there a way to configure a single Jenkins job to perform the release of each newer version of my application?
i.e, I would like to know in detail if it's possible to do the following tasks without any human intervention. I'm using SVN as well as Artifactory.

*

*Branch from the tag to be released

*Change the snapshot versions in pom files to release versions (for each dependency defined in pom)

*Take release build (EAR)

*Deploy it in Weblogic instance.

*Prepare release note

*Tag the release
Thanks in advance.

A: It can be fully automated using Multijob plugin (Also with a regular single job, but using Multijob it will be easier and you can use Maven targets instead of some manual shell scripting ).
The workflow starts with:

*

*commit and push to git

*hook in git should trigger a job by http POST, so u need to configure your job to accept remote triggering. You can pass the branch name as parameter

*job started, cloning the branch (git plugin)

*start Maven project to mvn clean install and check unit tests (optional)

*start Maven project to mvn release:prepare and mvn release:perform to omit the SNAPSHOT from pom.xml

*tag the branch (using shell block and simple git commands)

*merge to master branch (optionally)

*start Maven project to mvn deploy to deploy to weblogic (weblogic should be configured in ~/.m2/settings.xml as the repository for deploying the artifacts
NOTE: all tasks can be also in 1 job with some shell scripting. the best practices is to use plugins but sometimes you will find it easier to use shell scripting for some tasks.


text:
Q: C++ using GCOV/LCOV in a CMake project I'm working in a C++ Project  with a structure similiar to the following:
---  /src
    |--comms
    |--utils
    |--interfaces
    …
    CMakeList.txt
--- /test
    |---test1/
              |--main.cpp
              |--CMakelists.txt

--CMakeLists.txt

I do need to control the coverage of my tests and for this purpose I use GCOV and LCOV in this way:

*

*Enable coverage flags in all CMakeLists.txt to let the generation of .gcno files.
SET(CMAKE_CXX_FLAGS "-g -O0 -Wall -fprofile-arcs -ftest-coverage")
SET(CMAKE_C_FLAGS "-g -O0 -Wall -W -fprofile-arcs -ftest-coverage")
SET(CMAKE_EXE_LINKER_FLAGS "-fprofile-arcs -ftest-coverage")

*Run test, generating the corresponding .gcda files.
At this point, files gcno and gcda are located in the same directory as the corresponding .o file. I cannot move these files, because if I do it the report coverage generation doesn't work.

*From the directory in which files .gcno and .gcda are located I do the following:
lcov –c –d . –o name.info

*Generate the HTML report by using:
genhtml  name.info.

When I compile my project, I have duplicated .gcno files due to the fact that when tests are compiled they need to recompile their dependencies (comms, utils, …) because I don't generate libraries for theses dependencies. I think there is no way to avoid that if I don't use libraries.
However when I try to generate the index.html (coverage report) for the global project, it doesn't work.
I use a Shell script that creates the same folder structure of  my project and copy each .gcno and .gcda to the corresponding directory. And I execute the commands lcov and genhtml, nevertheless the index.html does not include all project coverage.
I would appreciate any help.

A: try to put --ignore-errors with genhtml command like that :
genhtml -o out name.info --ignore-errors source


text:
Q: Regular expression for matching functions I am using the following regular expression (from http://www.simple-talk.com/dotnet/asp.net/regular-expression-based-token-replacement-in-asp.net/)
(?<functionName>[^\$]*?)\((?:(?<params>.**?)(?:,|(?=\))))*?)
it works fine, except when I what to include brackets within the parameters such
as "<b>hello<b> renderHTML(""GetData(12)"") "
so I want "GetData(12)" instead I get "GetData(12".
Is there a way to ignore any matches if they are wrapped in double quotes?

A: There are ways to ignore the parens inside of quotes but this will not solve your problem.  Function calls in C# cannot be matched with a regular expression .  Regular expressions cannot match nested structures such as they way both parens and < appear inside of a function call.  To match these you need to use a grammar of sorts.
I while back I wrote a blog post which goes into a bit more detail about this problem

*

*http://blogs.msdn.com/b/jaredpar/archive/2008/10/15/regular-expression-limitations.aspx
I don't mean to be avoiding the answer here.  But any answer to this question will just be broken by a slightly more complex (or sometimes even simpler) function call.


text:
Q: How do i arrange the widget Icon into right side always Hello I am new on flutter and I am currently working on a design which I saw but the problem is that I am having issue on putting the Icon on the right side and the Row is not same size as others. I hope you can help me so it will broaden my knowledge on this flutter. I just started Flutter this week.
Design intended :

Current work :

Code :
      @override
  Widget build(BuildContext context) {
    // TODO: implement build
    Widget titleText = Container(
        padding: const EdgeInsets.all(32),
        child: Center(
          child: Text('Select Screen Lock',style: TextStyle(fontSize: 32.0,fontWeight: FontWeight.bold),),
        )
    );

    Widget subTitleText = Container(
      padding: const EdgeInsets.all(32),
      child: Center(
        child: Text('Secure your phone with a screen lock style,',style: TextStyle(fontSize: 16,fontWeight: FontWeight.normal),),
      ),
    );

    Widget selectionContainer = Container(
      width: 200,
      child: IntrinsicWidth(
        child:  Column(
          children: <Widget>[
            _selectMenu('Password'),
            _selectMenu('Pin Code'),
            _selectMenu('Finger Print')
          ],
        ),
      )
    );

    return MaterialApp(
      home: Scaffold(
        body: ListView(
          children: <Widget>[
            titleText,
            subTitleText,
            Center(
              child:
              selectionContainer,
            )
          ],
        ),
          ),
        );
      }

 Column _selectMenu(String title){
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Text(title), Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey,
              size: 16,
            )
          ],
        )
      ],
    );
  }

A: Problem here:
Column _selectMenu(String title){
    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Text(title), Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey,
              size: 16,
            )
          ],
        )
      ],
    );

First of all, remove Column(why we need it here?), and add space between items(please check mainAxisAlignment and crossAxisAlignment), then we get
Widget _selectMenu(String title){
    return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(title), Icon(
              Icons.arrow_forward_ios,
              color: Colors.grey,
              size: 16,
            )
          ]);


text:
Q: Hibernate doesn't close connections/sessions on DB I have a problem using Hibernate. Each time I call a method that performs a query or update on the database, hibernate opens a session in the database and then does not close. I've tried everything, but actually every time it's called em.getTransaction.begin (); It creates a session in Oracle bd and does not close anymore.
Below is the details of my code (persistence.xml, GenericDAO, etc.)
<persistence version="2.0"
             xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="FilaTrello" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>integration.wcc.model.Chamado</class>

        <properties>
            <property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@//10.ip.aqui/xxxint.xxx.com.br"/>
            <property name="javax.persistence.jdbc.user" value="x_SUPORTE"/>
            <property name="javax.persistence.jdbc.password" value="x_SUPORTE"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle9iDialect"/>
            <property name="hibernate.connection.shutdown" value="true"/>
            <!-- <property name="hibernate.hbm2ddl.auto" value="none"/> -->
            <property name="hibernate.synonyms" value="true"/>
            <property name="hibernate.show_sql" value="true"/>
            <property name="hibernate.format_sql" value="false"/>
          </properties>

    </persistence-unit>
</persistence>

GenericDAO:
package integration.wcc.dao;

import javax.persistence.*;
import javax.persistence.criteria.CriteriaQuery;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
abstract class GenericDAO<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("FilaTrello");
    private EntityManager em = emf.createEntityManager();;

    private Class<T> entityClass;

    public void beginTransaction() {
            em.clear();
            em.getTransaction().begin();

    }

    public void commit() {
        em.getTransaction().commit();
    }

    public void rollback() {
        em.getTransaction().rollback();
    }

    public void closeTransaction() {
       em.close();
    }

    public void commitAndCloseTransaction() {
        commit();
        closeTransaction();
    }

    public void flush() {
        em.flush();
    }

    public void joinTransaction() {
        em = emf.createEntityManager();
        em.joinTransaction();
    }

    public GenericDAO(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public void save(T entity) {
        em.persist(entity);

    }

    public void delete(Object id, Class<T> classe) {
        T entityToBeRemoved = em.getReference(classe, id);

        em.remove(entityToBeRemoved);
    }

    public T update(T entity) {
        return em.merge(entity);
    }

    public T find(int entityID) {
        return em.find(entityClass, entityID);
    }

    public T findL(Long entityID) {
        return em.find(entityClass, entityID);
    }

    public T findReferenceOnly(int entityID) {
        return em.getReference(entityClass, entityID);
    }

    // Using the unchecked because JPA does not have a
    // em.getCriteriaBuilder().createQuery()<T> method
    @SuppressWarnings({"unchecked", "rawtypes"})
    public List<T> findAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return em.createQuery(cq).getResultList();
    }

    // Using the unchecked because JPA does not have a
    // query.getSingleResult()<T> method
    @SuppressWarnings("unchecked")
    protected T findOneResult(String namedQuery, Map<String, Object> parameters) {
        T result = null;

        try {
            Query query = em.createNamedQuery(namedQuery);

            // Method that will populate parameters if they are passed not null and empty
            if (parameters != null && !parameters.isEmpty()) {
                populateQueryParameters(query, parameters);
            }

            result = (T) query.getSingleResult();

        } catch (NoResultException e) {
            System.out.println("No result found for named query: " + namedQuery);
        } catch (Exception e) {
            System.out.println("Error while running query: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    @SuppressWarnings("unchecked")
    protected List<T> findListResult(String namedQuery, Map<String, Object> parameters) {
        List<T> result = null;

        try {
            Query query = em.createNamedQuery(namedQuery);

            // Method that will populate parameters if they are passed not null and empty
            if (parameters != null && !parameters.isEmpty()) {
                populateQueryParameters(query, parameters);
            }

            //result = (T) query.getSingleResult();
            result = (List<T>) query.getResultList();

        } catch (NoResultException e) {
            System.out.println("No result found for named query: " + namedQuery);
        } catch (Exception e) {
            System.out.println("Error while running query: " + e.getMessage());
            e.printStackTrace();
        }

        return result;
    }

    private void populateQueryParameters(Query query, Map<String, Object> parameters) {
        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            query.setParameter(entry.getKey(), entry.getValue());
        }
    }
}

Access DAO class:
public class FilaChamadoDAO extends GenericDAO<FilaChamado> {

    private static final long serialVersionUID = 1L;

    public FilaChamadoDAO() {
        super(FilaChamado.class);
    }

public List<FilaChamado> findTicketsByFila(int idFila,String listType) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("filaNumber", idFila);
        parameters.put("listParam", listType);

        return super.findListResult(FilaChamado.FIND_TICKETS_FILA_BY_FILA, parameters);
    }

Ai eu tenho uma classe facade para cada Model meu, que faz a interface de acesso ao DAO:
I have a Facade class for each Model class, which makes the DAO access interface:
 public class FilaChamadoFacade {

        private FilaChamadoDAO FilaChamadoDAO = new FilaChamadoDAO();

        public List<FilaChamado> listAll() {
            FilaChamadoDAO.beginTransaction();
            List<FilaChamado> result = FilaChamadoDAO.findAll();
            FilaChamadoDAO.closeTransaction();
            return result;
        }

public List<FilaChamado> findTicketsByFila(int idFila,String listaDestino) {
        List<FilaChamado> result = null;
        try {
            FilaChamadoDAO.beginTransaction();
            result = FilaChamadoDAO.findTicketsByFila(idFila, listaDestino);
            FilaChamadoDAO.flush();
        } catch (HibernateException e) {
            if (FilaChamadoDAO != null) {
                FilaChamadoDAO.rollback();
            }
            e.printStackTrace();
        } finally {
            FilaChamadoDAO.closeTransaction();

        }
        return result;
    }

When I call ListAll() function or any namedWaury, I can't anyway close these opened connections.
I've made a simple test in a Main class:
public class TestNamedQuery {
    public static void main(String[] args) {

        TrelloUser trelloU = new TrelloUser();
        TrelloUserFacade facade2 = new TrelloUserFacade();
        List<TrelloUser> trelloUsers1 = new ArrayList<TrelloUser>();
        trelloUsers1 = facade2.listAll();

        for (TrelloUser trelloUser : trelloUsers1) {
            if(trelloUser.getUserToken() != null) {
                System.out.println("Selectss do usuario: "+trelloUser.getUserName());
                ChamadoCard cards = new ChamadoCard();
                cards.InsereChamado(trelloUser);
            }
        }

    }
}

As you can see, in my facade class every time I start a transaction ,I close it, but this does not happen in Oracle, where a session is created for each beginTransaction of my EntityManager.

A: After a lot of attempts, I just found a post saying that I have to commitor rollback every time I call beginTransaction()method to my Entity Manager.
So I change my code like this in theGenericDA.javaclass:
public void closeTransaction() {
        em.getTransaction().commit();
        em.close();
    }

I still trying to understand why Hibernate forces me to COMMIT a transaction even in a query statement, and I think that i can earn a great performance without do it.
But that change work like a charm for me.


text:
Q: why pid of child and its process are different? Here my code:
extern int errno;
pid_t system1(const char * command)
{
    pid_t pid;

    pid = fork();
    cout<<"PID in child "<<(int)pid<<endl;
    if (pid < 0) {
        return pid;
    } else if (pid == 0) {
        execl("/bin/sh", "sh", "-c", command, (char*)NULL);
        _exit(1);
    }

    int stat_val;
    pid_t child_pid;
    cout << "Hello1" << endl;
    child_pid = wait(&stat_val);
    cout << "child_pid = " <<(int)child_pid<< endl;//LINE 1
    if(WIFEXITED(stat_val))
    printf("Child has terminated with exit code %d\n", WIFEXITED(stat_val));
    else
    printf("Child has existed abnormally\n");
    return child_pid;
}

int main( )
{
    int pid_1 = system1("setup.csh &");;
    struct stat status;
    sleep(10);
    cout<<"errno  = "<<errno<<endl;
    int i = kill(pid_1,0);
    cout<<"Pid id = "<<pid_1<<endl;
    cout<<"i === "<<i<<endl;
    cout<<"errno  = "<<errno<<endl;
    if(errno == ESRCH)
    {
        cout<<"process does not exist";
    }
    else
    {
        cout<<"process exist"<<endl;
    }
    return 0;
}

In above code I am getting different PID of child at LINE 1 and PID of process setup.csh . Can anybody please help me out. I want to get PID of my process setup.csh.
I am looking other PID value using ps -u user | grep setup.csh in console.

A: When you run:
sh -c 'setup.csh &'

the original shell process forks another child process to run csh. The process hierarchy is:
YourProgram
    sh -c 'setup.csh &'
        csh setup.csh

There's no way to get this PID directly in the original program. Why don't you run setup.csh directly from your program, instead of going through the shell?
Actually, there's a way you can accomplish this. If you use the exec shell command, it runs the specified command in its own process, rather than forking a child:
system1('exec setup.csh &');


text:
Q: How to pass command line argument to an function in PHP? I need to pass a string (in command line as, php test.php dad) and check whether its a palindrome or not. I dont know how to pass string argumnet to a function. please explain, sample code is given below,
function Palindrome($string){
    if (strrev($string) == $string){
        return 1;
    }
    else{
        return 0;
    }
}
# I need to pass DAD as an argument in command line
$original = "DAD";
if(Palindrome($original)){
    echo "Palindrome";
}
else {
echo "Not a Palindrome";
}
?>

A: You can use variable  $argv . For your case, it's $argv[1]


text:
Q: Timestamp in log4net, is it the time when the log entry is generated or when it is written to file? We are testing the whole time delay between several software components which are communicating with each other through several IPC methods. Since some components are not written by us, the only tools we have are the log files generated by log4net (those components are wirtten in C#). We have configured the rolling file logger whose configuraitons look like this:
<appender name="RollingPerfAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="D:\Logs\my_log.log"/>
  <appendToFile value="true"/>
  <rollingStyle value="Size"/>
  <maxSizeRollBackups value="-1"/>
  <maximumFileSize value="20MB"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date{yyyy-MM-dd HH:mm:ss.ffffff}, %-5level, server, %-25.25logger, "%message"%newline"/>
  </layout>
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="FATAL" />
    <levelMax value="FATAL" />
  </filter>
</appender>

So now the log items look like this:
2021-06-10 10:39:52.987672, ERROR, server, "MY CUSTOM LOG GENERATED ON 2021-06-10 10:39:52.885126"

Now my question is, what is the tiemstamp (2021-06-10 10:39:52.987672) of it? Is it when the log entry is generated in the code, or when it is written to the file? I am asking because in this custom log I actually put the execution time in the log message (2021-06-10 10:39:52.885126), and we can see the time difference is as big as 100ms (I tried to set ImmediateFlush to True and changed it to False, it doesn't make much difference). But 100ms is too big for us to analyze the performance , because there are many other log items whose log messages are not controlled by us so we can only use the timestamp in the log itself. But if they are not exactly (or very close to) when those logs are generated in the code, the whole analysis will not be accurate enough (the whole delay is 200ms something, so 100ms inaccuracy in the log is way too big).
So how can I make the timestamp on the log items (close to) the time when it is generated in the code?