text:
Q: Trying to print out points for each word I'm trying to make a points problem game where each letter equals a certain amount of points and then reads the word in the text file and prints out the total points for each word, but all its doing for me is printing 0, I can't figure out why it is doing so. This is what I have got so far.
 File file = new File(fileName);
 Scanner sc = new Scanner(file);

 while (sc.hasNextLine()) {
        String line = sc.nextLine();
        int point = 0;
        switch (point) {
                case 'a':
                    point = 1;
                case 'e':
                    point += 1;
                case 'i':
                    point += 1;
                case 'l':
                    point += 1;
                case 'n':
                    point += 1;
                case 'o':
                    point += 1;
                case 'r':
                    point += 1;
                case 's':
                    point += 1;
                case 't':
                    point += 1;
                case 'u':
                    point += 1;
                case 'd':
                    point += 2;
                case 'g':
                    point += 2;
                case 'b':
                    point += 3;
                case 'c':
                    point += 3;
                case 'm':
                    point += 3;
                case 'p':
                    point += 3;
                case 'f':
                    point += 4;
                case 'h':
                    point += 4;
                case 'v':
                    point += 4;
                case 'w':
                    point += 4;
                case 'y':
                    point += 4;
                case 'k':
                    point += 5;
                case 'j':
                    point += 8;
                case 'x':
                    point += 8;
                case 'q':
                    point += 10;
                case 'z':
                    point += 10;
            }
System.out.println(line + " - Is worth " + point + " Points");

A: In the code you submitted you are checking the value of the integer point in your switch statement. That does not work because you are essentially saying does this integer have a value of this character at any point. Even if you were to change the switch to the input from the Scanner that is still returning a String and your switch statement is setup for a char.


text:
Q: Why does this code cause data race? 1 package main
2
3 import "time"
4
5 func main() {
6     m1 := make(map[string]int)
7     m1["hello"] = 1
8     m1["world"] = 2
9     go func() {
10         for i := 0; i < 100000000; i++ {
11             _ = m1["hello"]
12         }
13     }()
14     time.Sleep(100 * time.Millisecond)
15     m2 := make(map[string]int)
16     m2["hello"] = 3
17     m1 = m2
18 }

I run command go run --race with this code and get:
==================
WARNING: DATA RACE
Read at 0x00c420080000 by goroutine 5:
  runtime.mapaccess1_faststr()
      /usr/local/go/src/runtime/hashmap_fast.go:208 +0x0
  main.main.func1()
      /Users/meitu/test/go/map.go:11 +0x80

Previous write at 0x00c420080000 by main goroutine:
  runtime.mapassign()
      /usr/local/go/src/runtime/hashmap.go:485 +0x0
  main.main()
      /Users/meitu/test/go/map.go:16 +0x220

Goroutine 5 (running) created at:
  main.main()
      /Users/meitu/test/go/map.go:13 +0x1aa
==================

m1 and m2 are different variables,why do line 16 and line 11 cause data race?
My go version is 1.8. I guess that is some compile optimization, and somebody can tell me about it? Thank you very much.

A: The requirements to have a data race are:

*

*Multiple goroutines accessing the same resource (e.g. a variable) concurrently.

*At least one of those accesses is a write.

*The accesses are uncynchronized.

In your code all 3 requirements are met:

*

*You have the main goroutine accesssing m1, and the one you start in it also accesses m1. The main goroutine accesses it after the other goroutine has been launched, so they are concurrent.

*The main goroutine writes m1 in line #17: m1 = m2.

*The accesses are not synchronized, you use no mutex or channels or anything like that (sleeping is not synchronization).

Therefore it's a data race.
The obvious data race is between lines #11 reading m1, and line #17 writing m1.
But! Since line #17 assigns m2 to m1, then when/if the launched goroutine continues to run, it attempts to read m1 which may now be the value of m2 because we assigned m2 to m1. What does this mean? This introduces another data race writing m2 and reading m1.
That is after line #17 if the program does not end immediately (it may, but not necessarily), then the launched goroutine attempts to read from m1 which is now m2 which was last written in line #16, so this explains the "conflict" between lines #11 and #16.
The full go run -race output is as follows:
==================
WARNING: DATA RACE
Write at 0x00c42000e010 by main goroutine:
  main.main()
      /home/icza/gows/src/play/play2.go:17 +0x22f

Previous read at 0x00c42000e010 by goroutine 5:
  [failed to restore the stack]

Goroutine 5 (running) created at:
  main.main()
      /home/icza/gows/src/play/play2.go:9 +0x190
==================
==================
WARNING: DATA RACE
Read at 0x00c42007e000 by goroutine 5:
  runtime.mapaccess1_faststr()
      /usr/local/go/src/runtime/hashmap_fast.go:208 +0x0
  main.main.func1()
      /home/icza/gows/src/play/play2.go:11 +0x7a

Previous write at 0x00c42007e000 by main goroutine:
  runtime.mapassign_faststr()
      /usr/local/go/src/runtime/hashmap_fast.go:598 +0x0
  main.main()
      /home/icza/gows/src/play/play2.go:16 +0x1fc

Goroutine 5 (running) created at:
  main.main()
      /home/icza/gows/src/play/play2.go:9 +0x190
==================
==================
WARNING: DATA RACE
Read at 0x00c420080088 by goroutine 5:
  main.main.func1()
      /home/icza/gows/src/play/play2.go:11 +0x90

Previous write at 0x00c420080088 by main goroutine:
  main.main()
      /home/icza/gows/src/play/play2.go:16 +0x212

Goroutine 5 (running) created at:
  main.main()
      /home/icza/gows/src/play/play2.go:9 +0x190
==================
Found 3 data race(s)
exit status 66

A: Data race
A data race occurs when two goroutines access the same variable concurrently and at least one of the accesses is a write.
Instructions Reorder
compilers and processors may reorder the reads and writes executed within a single goroutine as far as the reordering does not change the behaviour within the routine, it doesn' ensure behaviour of other goroutines to be unaffected
m2["hello"] = 3
m1 = m2

Can be reordered to
m1 = m2
m2["hello"] = 3

That won't alter the behaviour of the main routine and thus race checking will consider that also for evaluating race condition. Now we have m2["hello"] = 3 causing the race condition and it prints out the same with its original line number

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the meaning of this name attribute and #varName in the router outlet tag? I found a code which is insrted in the app.component.html file.
In the  should be displayed the other components regarding on the routes configured in the app-routing.module.ts.
But i dont understant what is the meaning of
o="outlet"
and
name="popup"

      <router-outlet #o="outlet"></router-outlet>

      <router-outlet name="popup"></router-outlet>

A: The angular router supports having multiple outlets. this allows you to display different content based on user interaction.
I'd suggest reading the official angular documentation on Displaying multiple routes in named outlets


text:
Q: Ordering columns in a dataframe in R I have created a data frame using the following code:
manager <- c(1,2,3,4,5)
date <- c("10/24/08","10/28/08","10/1/08","10/12/08","5/1/09")
country <- c("US","US","UK","UK","UK")
gender <- c("M","F","F","M","F")
age <- c(32,45,25,39,99)
q1 <- c(5,3,3,3,2)
q2 <- c(4,5,5,3,2)
q3 <- c(5,2,5,3,2)
q4 <- c(5,5,5,NA,2)
q5 <- c(5,5,2,NA,1)
leadership <- data.frame(manager,date,country,gender,age,
                     q1,q2,q3,q4,q5, stringsAsFactors = FALSE)

I have then queried using the following: View(leadership[c(1:3),c("q1","q2","q3","q4","q5")])
My question is as follows: Is there any way to set up an ordered structure to the columns, such that I will be able to query using the following code?
View(leadership[c(1:3),c("q1":"q5")])
Thanks in advance.

A: Alternatively, in base R append a list with grep() on column names:
leadership[append(1:3, grep("^q.*$", names(leadership)))]
#   manager     date country q1 q2 q3 q4 q5
# 1       1 10/24/08      US  5  4  5  5  5
# 2       2 10/28/08      US  3  5  2  5  5
# 3       3  10/1/08      UK  3  5  5  5  2
# 4       4 10/12/08      UK  3  3  3 NA NA
# 5       5   5/1/09      UK  2  2  2  2  1

And if just a subset of q's pass in a regex search:
leadership[append(1:3, grep("^q[1-3].*$", names(leadership)))]
#   manager     date country q1 q2 q3
# 1       1 10/24/08      US  5  4  5
# 2       2 10/28/08      US  3  5  2
# 3       3  10/1/08      UK  3  5  5
# 4       4 10/12/08      UK  3  3  3
# 5       5   5/1/09      UK  2  2  2

leadership[append(1:3, grep("^q[4-5].*$", names(leadership)))]
#   manager     date country q4 q5
# 1       1 10/24/08      US  5  5
# 2       2 10/28/08      US  5  5
# 3       3  10/1/08      UK  5  2
# 4       4 10/12/08      UK NA NA
# 5       5   5/1/09      UK  2  1

A: dplyr::select allows for the non-standard syntax you propose.
library(dplyr)
View(select(leadership[1:3, ], q1:q5))

See ?select for more details. You could also do select(leadership, starts_with("q"))


text:
Q: How to combine two tables that have distinct data I have 2 tables

*

*tbl_vacancies_details

*tbl_filled_vacancies
I want show a graph that contains the total count of vacancies and filled counts in each year. How can I write a SQL query for that.
 tbl_vacancies_details

    Id | Year      | Count |
    ------------------------
    1  | Jan-2014  |  10   |
    2  | Jun-2014  |  5    |
    3  | Dec-2015  |  9    |

    tbl_filled_details

    Id | Join_Date | UserId |
    ------------------------
    1  | Mar-2014  |  1     |
    2  | Dec-2014  |  6     |
    2  | Dec-2014  |  15    |
    3  | May-2016  |  3     |

My desired output is
Year | Total | Filled |
-----------------------
2014 | 15    | 3      |
2015 | 3     | 0      |
2016 | 0     | 3      |

A: This should get you started:
SELECT
  year Year
  , (SELECT SUM(cnt) FROM tbl_vacancies_details WHERE YEAR(dt) = years.year) Total
  , (SELECT COUNT(userID) FROM tbl_filled_details WHERE YEAR(join_date) = years.year) Filled
FROM
  (SELECT
    YEAR(dt) year
  FROM tbl_vacancies_details
  UNION
  SELECT
    YEAR(join_date)
  FROM tbl_filled_details) years
;

See it in action: SQL Fiddle
Please comment, if and as this requires adjustment / further detail.

A: SELECT
    (CASE
        WHEN vac.year not null then to_char(vac.Year,'YYYY')
        ELSE to_char(det.Year,'YYYY')) as Year,
        sum(vac.Count) as Total,
        det.Count as Filled
    FROM
        tbl_vacancies_details  vac  FULL
    OUTER JOIN (
            SELECT
                to_char(fil.Join_Date,'YYYY') as Year,
                count(*) as Count
            FROM
                tbl_filled_details as fil
            GROUP BY
                to_char(fil.Join_Date,'YYYY')
        ) det ON det.Year = vac.Year
    GROUP BY
        to_char(vac.Year,'YYYY')

I think this showcases the idea of how to do it but I'm not sure that it is runnalbe query. You will have to find functions for transforming the date based on your format.
It full outter joins tbl_vacancies_details by year with the inner select (which counts the occurances of vac in tbl_filled_details for each year) and then displayes both results for each year
Edit: I asumed that tbl_filled_details has case by case records of vacation and tbl_vacancies_details has already sums of vacations

A: I would recommend a union all query with aggregation:
select yyyy,
       sum(total) as total,
       sum(filled) as filled
from ((select year(year) as yyyy, count as total, 0 as filled
       from tbl_vacancies_details
      ) union all
      (select year(join_date) as yyyy, 0 as total, 1 as filled
       from tbl_filled_details
      )
     ) x
group by yyyy;

Here is a SQL Fiddle.
Note:  I would advise you to not name your columns count and year because these are used for other purposes in SQL.


text: Q: Вопрос по Hibernate Сколько бы не читал документации, всегда говорят, вот Hibernate за вас делает это, делает то, автоматически меняет названия таблицы, когда это нужно, при указании в аннотации @Column (name = "name") делает столбец name, но вот вопрос: Hibernate может делать что-либо только с заранее созданной таблицей? То есть каждую таблицу, которая у нас есть, мы должны описывать entity-классом, причем в точности? Или же Hibernate должен их (таблицы) сам создавать (основываясь на entity)?


text:
Q: It is almost impossible to check SMS or iMessage color from CNContacts in Swift? I am going to researching to find however to add contact's Profile picture with small dots show blue or green appear if person was iMessage or sms to easier and noticeable on UITableView with Apple's Framework.
any idea?
Thanks!


text:
Q: Fitting a log-log data using scipy.optmize.curve_fit I have two variables x and y which I am trying to fit using curve_fit from scipy.optimize.
The equation that fits the data is a simple power law of the form y=a(x^b). The fit seems to be well for the data when I set the x and y axis to log scale, i.e ax.set_xscale('log') and ax.set_yscale('log').
Here is the code:
def fitfunc(x,p1,p2):
    y = p1*(x**p2)
    return y

popt_1,pcov_1 = curve_fit(fitfunc,x,y,p0=(1.0,1.0))
p1_1 = popt_1[0]
p1_2 = popt_1[1]
residuals1 = (ngal_mstar_1) - fitfunc(x,p1_1,p1_2)
xi_sq_1 = sum(residuals1**2) #The chi-square value

curve_y_1 = fitfunc(x,p1_1,p1_2) #This is the fit line seen in the graph

fig = plt.figure(figsize=(14,12))
ax1 = fig.add_subplot(111)
ax1.scatter(x,y,c='r')
ax1.plot(y,curve_y_1,'y.',linewidth=1)
ax1.legend(loc='best',shadow=True,scatterpoints=1)
ax1.set_xscale('log') #Scale is set to log
ax1.set_yscale('log') #SCale is set to log
plt.show()

When I use true log-log values for x and y, the power law fit becomes y=10^(a+b*log(x)),i.e raising the power of the right side to 10 as it is logbase 10. Now both by x and y values are log(x) and log(y).
The fit for the above does not seem to be good. Here is the code I have used.
def fitfunc(x,p1,p2):
    y = 10**(p1+(p2*x))
    return y

popt_1,pcov_1 = curve_fit(fitfunc,np.log10(x),np.log10(y),p0=(1.0,1.0))

p1_1 = popt_1[0]
p1_2 = popt_1[1]
residuals1 = (y) - fitfunc((x),p1_1,p1_2)
xi_sq_1 = sum(residuals1**2)

curve_y_1 = fitfunc(np.log10(x),p1_1,p1_2) #The fit line uses log(x) here itself

fig = plt.figure(figsize=(14,12))
ax1 = fig.add_subplot(111)
ax1.scatter(np.log10(x),np.log10(y),c='r')
ax1.plot(np.log10(y),curve_y_1,'y.',linewidth=1)
plt.show()

THE ONLY DIFFERENCE BETWEEN THE TWO PLOTS IS THE FITTING EQUATIONS, AND FOR THE SECOND PLOT THE VALUES HAVE BEEN LOGGED INDEPENDENTLY. Am I doing something wrong here, because I want a log(x) vs log(y) plot and the corresponding fit parameters (slope and intercept)

A: Your transformation of the power-law model to log-log is wrong, i.e. your second fit actually fits a different model. Take your original model y=a*(x^b) and apply the logarithm on both sides, you will get log(y) = log(a) + b*log(x). Thus, your model in log-scale should simply read y' = a' + b*x', where the primes indicate variables in log-scale. The model is now a linear function, a well known result that all power-laws become linear functions in log-log.
That said, you can still expect some small differences in the two versions of your fit, since curve_fit will optimise the least-squares problem. Therefore, in log scale, the fit will minimise the relative error between the fit and the data, while in linear scale, the fit will minimise the absolute error. Thus, in order to decide which way is actually the better domain for your fit, you will have to estimate the error in your data. The data you show certainly does not have a constant uncertainty in log-scale, so on linear scale your fit might be more faithful. If details about the error in each data-point are known, then you could consider using the sigma parameter. If that one is used properly, there should not be much difference in the two approaches. In that case, I would prefer the log-scale fitting, as the model is simpler and therefore likely to be more numerically stable.


text:
Q: SNS FilterPolicy Limit increase According to AWS documentation on SNS limits, you can only have 100 message filter policies per account per region.
I can ask for an increase to this, but I can't find any information on the web about what the costs or upper limits would be for increasing the filter policy count, similar to the question answered here on topic count limits.
If I'm hoping to increase this limit by A LOT, what should I expect in terms of pricing or if it'll even be allowed?
I plan to ask for the increase, but was disappointed in not finding any available info on the web from others. I also would have posted this question in their forums, but I don't like their interface as much :)

A: I heard back from AWS support and got a limit increase, but not as high as I'd like to fit my use case.
It seems as if you should use filter policies very judicially.


text:
Q: Тип параметра функции Вопрос по языку python.
Метод класса принимает какой-то объект по параметру.
def intersection(self, vp):

Можно ли в коде присвоить тип параметру vp?
A: Если речь идет о статической типизации, то нет, нельзя. Максимум, что можно — это контракты, проверяемые во время выполнения, при вызове функции. Самое простое — используя assert. Например, как-то так:
def intersection(self, vp):
    assert type(vp) is tuple and \
           all(type(x) in (int, long) for x in vp), \
        "vp must be a tuple of integers"
    ...

Если хочется синтаксического сахара, в Python 3 есть аннотации, которые можно использовать.
@typecheck
def intersection(self, vp: tuple_of(int)):
    ...

И дальше проверять типы декоратором, например, http://code.activestate.com/recipes/572161/. В Python 2.x аннотаций нет, максимум что можно сделать, это декоратор в духе:
@requires("vp", tuple)
def intersection(self, vp):
    ...

Или прописать контракт в docstring'е, в духе:
def intersection(self, vp):
    """
    Does something.

    inv:
        type(vp) is tuple
    """
    ...

Если имелось в виду что-то другое — уточните, пожалуйста, вопрос, пояснив что значит — «присвоить тип.»


text:
Q: (getDate() - 1) function is getting the value zero if the current date is 1 My Requirement:
I'm having to fields Start Date and End Date, If the End Date is left empty while saving the record, the End Date Field value is populated with plus 1 year based on the entered from date.
My Issue:
If the Start Date is "9/1/2016" and the End Date is Left Empty means it should automatically populate the End Date value as "8/31/2016" but it returning the End Date value as "9/0/2016" and also i'm getting the following ERROR MESSAGE
Error: JS_EXCEPTION
INVALID_FLD_VALUE You have entered an Invalid Field Value Invalid Date for the following field: custrecord_end_date
CODE:
SCRIPT : CLIENT SCRIPT, EVENT :SaveRecord
function saveRecord(scriptContext) {
  var newRecord= scriptContext.currentRecord;
 var fromDate = new Date(newRecord.getValue('custrecord_created_date'));
 var endDate = newRecord.getValue('custrecord_end_date');
   if (endDate == null || endDate == '') {
    //getting plus 1 year based on the From Date
    tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);

   //setting the value to the End Date Field
     newRecord.setValue('custrecord_end_date', tempEndDate);

}
}
  // Add Plus Year from the Start Date when the End Date is Empty
        function addingPlusYearOfTheCurrentDate(fromDate ) {
            var date = new Date();
            var Month = (fromDate.getMonth() + 1);
            var Dates = (fromDate.getDate() - 1);
            var Year = (fromDate.getFullYear() + 1);
            var last_Day = new Date(Month + '/' + Dates + '/' + Year);

            log.debug('last_Day:', last_Day);
            return last_Day;
        }

A: Not sure why you expected to be able to subtract 1 from 1 and get anything other than 0, but you can solve this problem by using the Date object's setFullYear() and setDate().

function addingPlusYearOfTheCurrentDate(fromDate) {
  var date = new Date(fromDate);

  date.setFullYear(date.getFullYear() + 1);
  date.setDate(date.getDate() - 1);

  return date;
}

console.log(addingPlusYearOfTheCurrentDate(new Date(2015, 10, 1)));

A: Parsing strings with the Date constructor (and Date.parse, they are equivalent for parsing) is strongly recommended against since parsing is almost entirely implementation dependent and inconsistent. Manually parse strings with a custom function or use a library.
Adding a year to a Date is fairly simple, but it seems you want the date that is one day prior to the same date next year. So add one year then subtract one day.

// Parse m/d/y format string to a Date and validate the result
function parseMDY(s) {
  var b = s.split(/\D/);
  var d = new Date(b[2], --b[0], b[1]);
  return d && d.getMonth() == b[0]? d : new Date(NaN);
}

// Add 1 year to a Date
function addYear(d) {
  if (Object.prototype.toString.call(d) != '[object Date]') return;
  d.setFullYear(d.getFullYear() + 1);
  d.setDate(d.getDate() -1);
  return d;
}

var d = parseMDY('9/1/2016');
console.log(d.toLocaleString())
addYear(d);
console.log(d.toLocaleString())

Note that for 29 February, adding one year gives 1 May, then subtracting one day will give 28 February.

A: You should use the method nlapiStringToDate() for string to date conversions, as NetSuite gives date field value as string, which you must convert to date, and before you set back date, you must use nlapiSetFieldValue(YOUR_FIELD_ID, nlapiStringToDate(dateObject))
Please see below on suggested usage on reading and setting date fields.
function saveRecord(scriptContext) {
  var newRecord = scriptContext.currentRecord;
  var fromDate = nlapiStringToDate(newRecord.getValue('custrecord_created_date'));
  var endDate = nlapiStringToDate(newRecord.getValue('custrecord_end_date'));
  if (endDate == null || endDate == '') {
    //getting plus 1 year based on the From Date
    tempEndDate = addingPlusYearOfTheCurrentDate(fromDate);

   //setting the value to the End Date Field
     newRecord.setValue('custrecord_end_date', nlapDateToString(tempEndDate));
}

A: Is this a 1.0 or 2.0 script?
NetSuite's 1.0 API offers a couple date manipulation methods that might be helpful to you here: nlapiAddMonths and nlapiAddDays, as well as the Date-String conversion methods.
Here's an example of what you could do in 1.0
// 1.0 API does not pass scriptContext to saveRecord
function saveRecord() {

    // Use nlapiStringToDate instead of raw Date constructor
    var fromDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_created_date'));

    // Instead of the full extra conditional, just use || as fallback
    var endDate = nlapiStringToDate(nlapiGetFieldValue('custrecord_end_date')) ||
            calculateEndDate(fromDate);

    // setting the value to the End Date Field
    nlapiSetFieldValue('custrecord_end_date', nlapiDateToString(endDate));
}

/** @param fromDate {Date} */
function addYear(fromDate) {
    return nlapiAddMonths(fromDate, 12);
}

/** @param fromDate {Date} */
function dayBefore(fromDate) {
    return nlapiAddDays(fromDate, -1);
}

/** @param startDate {Date} */
function calculateEndDate(startDate) {

    // add 1 year first, then subtract one day
    return dayBefore(addYear(startDate));
}

If you're using 2.0 just add a comment, and I will try to update the example if I can. If you've got any questions about how this works, feel free to let me know as well.


text: Q: chrome downloaded blocked files location I downloaded a file using chrome it downloaded it correctly then chrome blocked it. I don't see it in my downloads folder. But while downloading I could see the partial file in the downloads folder. My question is what is the location of chrome files which are blocked or quarantined? i.e. where they are kept. While downloading is taking place they seem to be in the downloads folder but after chrome passes its judgement it moves it somewhere else.


text:
Q: @EnableBinding(Source.class) throws Failed to bind properties under 'server.error.include-stacktrace' to org.springframework.boot.autoconfigure.web Spring Cloud Stream and kafka.
This error shows up after I add the following dependencies. ( If I comment out the @EnableBinding(Source.class) everything works. )
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-kafka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
        </dependency>

When I add the Enable Binding property,
@SpringBootApplication
@EnableBinding(Source.class)
public class CustomersServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(CustomersServiceApplication.class, args);
    }
}

And these are my properties
spring:
  application:
    name : customerservice
  cloud:
    stream:
      bindings:
        output:
            destination:  orgChangeTopic
            content-type: application/json
      kafka:
        binder:
          zkNodes: localhost
          brokers: localhost

logging:
  level:
    com.netflix: WARN
    org.springframework.web: WARN
    com.thoughtmechanix: DEBUG

eureka:
  instance:
    preferIpAddress: true
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
        defaultZone: http://localhost:8761/eureka/

server:
  port: 7000

This is my full code, however when I run the application now, I am getting an error.
2019-04-08 15:40:33.325  INFO 22917 --- [  restartedMain] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-04-08 15:40:33.336 ERROR 22917 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to bind properties under 'server.error.include-stacktrace' to org.springframework.boot.autoconfigure.web.ErrorProperties$IncludeStacktrace:

    Property: server.error.include-stacktrace
    Value: ALWAYS
    Origin: "server.error.include-stacktrace" from property source "devtools"
    Reason: 0

Action:

Update your application's configuration

After Adding the property to my properties file. I still get the same error
server:
  port: 7000
  error:
    include-stacktrace : ALWAYS

A: It looks like spring version conflict issue. Two suggestions here:

*

*Create a clean spring cloud stream with Kafka project, to make sure it works well.

*Use mvn dependency tree to analysis conflict spring version.


text:
Q: How to extract a function variable value and initialize it to another variable in a different function? These are my two function and i want to transform the information from function to the other without need to declare a variable to store the information because always when i start my app the initial variable is the one that show up
    func action(gestureRecognizer: UIGestureRecognizer) {

    var touchPoint = gestureRecognizer.locationInView(self.mapView)
    var location:CLLocationCoordinate2D = mapView.convertPoint(touchPoint, toCoordinateFromView: self.mapView)
    var latDelta:CLLocationDegrees = 0.01
    var lonDelta:CLLocationDegrees = 0.01
    var span:MKCoordinateSpan = MKCoordinateSpan(latitudeDelta:latDelta, longitudeDelta: lonDelta)
    var region:MKCoordinateRegion = MKCoordinateRegion(center: location, span: span)
    mapView.setRegion(region, animated: true)

    var annotation = MKPointAnnotation()
    annotation.coordinate = location
    annotation.title = ""
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    var userLocation:CLLocation = locations[0] as! CLLocation

    CLGeocoder().reverseGeocodeLocation(userLocation, completionHandler: { (placeMarks, error) -> Void in

     if error != nil
     {
         println("error: \(error)")
     }
      else {
         let place = CLPlacemark(placemark: placeMarks?[0] as! CLPlacemark)
            }
     })

}


text:
Q: Vectors - Find the vector $\vec{c}$ which is orthogonal to $\vec{a}$ and $\vec{b}$ and whose first component is 1
Find the vector $\vec{c}$ which is orthogonal to $\vec{a}$ and $\vec{b}$ and whose first component is 1
$\vec{a}$ = (0 / 4 / -2), start point: $P$ (2 / -3 / 5), end point: $A$ (2 / 1 / 3)
$\vec{b}$ = (-5 / 5 / -1), start point: $P$ (2 / -3 / 5), end point: $B$ (-3 / 2 / 4)

I can only assume that $\vec{c}$ is supposed to be an unit vector. What I don't understand, is, how one vector is supposed to be orthogonal to both vectors $\vec{a}$ and $\vec{b}$ at once?
Maybe the Point $P$ provides the place for the new vector to be orthogonal to both vectors, but how to find $\vec{c}$ respectively determine its properties (direction, x-, y-, and z-values)?
Edit - As suggested by rschwieb here's the solution I worked out:
The first component of $\vec{c}$ is $x = 1$, the other ones are unknown, thus:

$\vec{c}$ = (1, y, z)

Because the vector $\vec{c}$ is orthogonal to the other vectors $\vec{a}$ and $\vec{b}$, the scalar products are: $\vec{c} * \vec{a} = 0$ and $\vec{c} * \vec{b} = 0$. This results in the following system of equations:

$\vec{a} * \vec{c} => (0, 4, -2) * (1, y, z) = (0*1) + (4*y) + (-2*z) = 0$
$\vec{b} * \vec{c} => (-5, 5, -1) * (1, y, z) = (-5*1) + (5*y) + (-1*z) = 0$

Which is then simplified to:

$4y - 2z = 0$
$-5 + 5y - z = 0$

When calculating this system of equations, the solutions then are

y = $\dfrac{5}{3}$ and z = $\dfrac{10}{3}$

Thus, the end result is:

$\vec{c} = (1, \dfrac{5}{3}, \dfrac{10}{3})$

A: Of course a vector can be perpendicular to two vectors at once: think of the x-y-z coordinate axes!
If you simply let $\vec{c} =(1,a,b)$ be your vector, and find the resulting system of equations that arises if you assume $\vec{c}$ has dot product 0 the other two vectors, you will find that  $\vec{c}=(1,5/3,10/3)$.
I would like to encourage you to show this work in a solution of your own.
Edit: Somehow made a mistake in my haste. $\vec{c}=(1,5/3,10/3)$. Corrected above.

A: If you take the cross product of two non-parallel vectors, you automatically get a vector that is perpendicular to the original two. Now all you have to do is divide all three components of the result by the value of the first component. The result should be the same as rschwieb's solution.
You'd skip the equation system part, but instead have to calculate a cross product, so I'm not sure which solution is easier.


text:
Q: How to calculate the sum of the Integers I insert in EditText everytime I insert an Integer? I have a RecyclerView with a single TextView in it. And i have an add Button and one EditText outside it that only accept Integers and add them to the RecyclerView when i press the add button. My question is  how to make it calculate the sum of all the Integers i insert to the EditText.
Example: lets say i entered 300 to the EditText in the first row will show 300 then if i insert 200 to the EditText i want show 500 in the second row (300 + 200) and so on.
here is my code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.brecyclerview.MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edit_ten"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Score"
        android:inputType="numberSigned|number" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/btn_add"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_add"
            android:text="Add"
            tools:ignore="OnClick" />

        <Button
            android:id="@+id/btn_undo"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_undo"
            android:text="Undo"
            tools:ignore="OnClick" />

        <Button
            android:id="@+id/btn_new"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="btn_new"
            android:text="New Game" />

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleViewContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        tools:itemCount="8" />

</LinearLayout>

list_item.xml

  <RelativeLayout
      android:id="@+id/singleRow"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:padding="8dp">

      <ImageView
          android:id="@+id/userImg"
          android:src="@mipmap/ic_launcher"
          android:layout_width="60dp"
          android:layout_height="60dp" />

      <TextView
          android:id="@+id/pNametxt"
          android:text="User Name"
          android:textSize="20sp"
          android:layout_marginTop="6dp"
          android:maxLines="1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_toRightOf="@+id/userImg"
          android:layout_toEndOf="@+id/userImg"
          android:layout_marginLeft="8dp"
          android:layout_marginStart="8dp" />

  </RelativeLayout>

  <View
      android:layout_below="@+id/singleRow"
      android:layout_width="match_parent"
      android:layout_height="1dp"
      android:background="#f2f2f2" />

MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    Button button;
    Button button1;
    Button button2;
    EditText editText;
    TextView personName;
    RecyclerView recyclerView;
    RecyclerView.Adapter mAdapter;
    RecyclerView.LayoutManager layoutManager;

    List<PersonUtils> personUtilsList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.btn_add);
        button1 = (Button)findViewById(R.id.btn_undo);
        button2 = (Button)findViewById(R.id.btn_new);
        editText = (EditText)findViewById(R.id.edit_ten);
        personName = (TextView)findViewById(R.id.pNametxt);

        recyclerView = (RecyclerView) findViewById(R.id.recycleViewContainer);
        recyclerView.setHasFixedSize(true);

        layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);

        personUtilsList = new ArrayList<>();

        //Adding Data into ArrayList

        mAdapter = new CustomRecyclerAdapter(this, personUtilsList);

        recyclerView.setAdapter(mAdapter);

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == button2) {
                    MainActivity.this.finish();

                    startActivity(new Intent(MainActivity.this, MainActivity.class));
                }}});

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                int pNametxt;
                int total = 0;
                for (int i = 0; i<personUtilsList.size(); i++)
                {
                    total += personUtilsList.get(i).getPersonName();
                }
                total = Integer.parseInt(editText.getText().toString());

                layoutManager = new LinearLayoutManager(getApplicationContext());
                recyclerView.setLayoutManager(layoutManager);
                personUtilsList.add(new PersonUtils(total));
                mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
                recyclerView.setAdapter(mAdapter);
                editText.setText("");

            }});

    }}

CustomRecyclerAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class CustomRecyclerAdapter extends RecyclerView.Adapter<CustomRecyclerAdapter.ViewHolder> {

    private Context context;
    private List<PersonUtils> personUtils;

    public CustomRecyclerAdapter(Context context, List personUtils) {
        this.context = context;
        this.personUtils = personUtils;
    }

    public static void remove(long i) {

    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(v);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.itemView.setTag(personUtils.get(position));

        PersonUtils pu = personUtils.get(position);

       holder.pName.setText(String.valueOf(pu.getPersonName()));

    }

    @Override
    public int getItemCount() {

        return personUtils.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{

        public TextView pName;
        Button deleteButton;

        public ViewHolder(View itemView) {
            super(itemView);

            pName = (TextView) itemView.findViewById(R.id.pNametxt);
            deleteButton = (Button) itemView.findViewById(R.id.btn_undo);

                }

    }

}

PersonUtils.java
public class PersonUtils {

    private Integer personName;

    public Integer getPersonName() {
        return personName;
    }

    public void setPersonName(Integer personName) {
        this.personName = personName;
    }

    public PersonUtils(Integer personName) {
        this.personName = personName;
    }

}

thank u in advance.

A: When user click add button, you can get last value from your array list and sum with value at edit text. Add total sum to your list.
You don't have to do it again.
layoutManager = new LinearLayoutManager(getApplicationContext());
            recyclerView.setLayoutManager(layoutManager);
            personUtilsList.add(new PersonUtils(total));
            mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
            recyclerView.setAdapter(mAdapter);

Just add your item in personUtilsList and call recyclerView.notifyDataSetChanged() method.

A: Actually, you done it in your code, but with a simple mistake.
MainActivity.java in button listener
int total = 0;
for (int i = 0; i<personUtilsList.size(); i++)
{
    total += personUtilsList.get(i).getPersonName();
}
total = Integer.parseInt(editText.getText().toString());

The problem of it, that you have set a new value for total variable but it should be += instead of = and your code will work as you wish InChaa'Allah.
But i have some notices about your coding way.
First, these lines are bad to write it like this.
layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
personUtilsList.add(new PersonUtils(total));
mAdapter = new CustomRecyclerAdapter(MainActivity.this, personUtilsList);
recyclerView.setAdapter(mAdapter);

It will do all the Activity life cycle again, and will be a lot of CPU waste.
So you do it like this.
((CustomRecyclerAdapter) mAdapter).addPersonUtils(new PersonUtils(total));
mAdapter.notifyDataSetChanged();//will make the RecyclerView adapter to reload its data.

And in CustomRecyclerAdapter.java class i have added a new method just to add a new item to the personUtils ArrayList.
public void addPersonUtils(PersonUtils personUtil){
    personUtils.add(personUtil);
}

The code will be better this way.


text:
Q: How to create a GUI with multiple lines of glyphs/text in parallel where the glyphs have x and y coordinates I'm currently creating an application to edit parallel lists of events which happen on a timeframe. In the model/backend there is a list of lists where the sublist has all the items in order.
Each event should be represented by a string/glyph (from a ttf font) and each of the textlines should be edited like a normal line of text with a few exeptions how they are displayed. Look at this picture:

Basically each lines represents a line of text. Each event is a single char/glyph. So its a text editor?! Not quite

*

*There are no linebreaks

*Multiple lines in parallel

*Each glyph has an individual space after it (X-direction)

*Each glyph can be shifted "up" and "down" individually (Y-Direction) (Maybe the most important point)

*If you delete a glyph all items right of it go a step "left" to close the gap (just like in a normal texteditor).

*If you insert a glyph all items right of it go a step "right" to create a gap to insert.

Most of these points are covered by QGraphicsLinearLayout, but maybe its the wrong widget/layout for this approach. Do you have any advice?

A: I would suggest trying to setup a QGraphicsScene with your events as QGraphicText objects (or possibly a class derived from QGraphicText).  Let each be positioned independently, but let them know about the "next" event on their line, like a linked list.  Then, when one is inserted or deleted, you can quickly do that operation and (unfortunately, more slowly) update the positions of the other events in the line.  This update might not be too much code, if it's just setting the position to be X pixels to the right of the previous item, but it will have to update every event in the line after the modification.
You could maybe do some thing where the event to the right is a child of the current event, and push off the position updates to Qt.  I don't know if that would be any more efficient, and I don't know how deep child trees can really get.
Updating the Y position of the event (requirement 4) should be easy: just change its Y position.


text:
Q: Alternative to Complex.h in Visual Studio I know very little about VS, and was surprised when my linux code did not compile on windows. The problem seams from the lack of <complex.h> in VS. My question is this: do people re-implement  in their Windows applications, or is there a public domain version.

A: <complex.h> is a new feature of ISO/IEC 9899:1999 and Visual Studio (at least up to 2008) only supports ISO/IEC 9899:1990 with some extensions, so complex.h isn't supported.

A: If you have the option of using C++ instead of C, you can use the complex header. Visual C++ supports C89, but not C99, where complex.h is defined.
If C++ is not an option, you can either use another compiler (there are Windows ports of GCC available, for example), or try to find a third-party implementation.

A: since C++ is not an option, and neither is GCC, can't you just... Download the header, and include it into your project yourself: #include"complex.h"? You could download a minimal version of MinGW and just copy the header file over.


text:
Q: Custom field type rendering in XSLT How can I render a custom field type with XSLT.
I want to render in the same manner like I do with this CAML
<RenderPattern Name="DisplayPattern">
    <Switch>
    <Expr>
        <Column/>
    </Expr>
    <Case Value="" />
    <Default>
        <Column SubColumnNumber="0" HTMLEncode="TRUE"/>
        <![CDATA[, nr. ]]>
        <Column SubColumnNumber="1" HTMLEncode="TRUE"/>
        <![CDATA[
Bloc ]]>
        <Column SubColumnNumber="2" HTMLEncode="TRUE"/>
        <![CDATA[, Etaj ]]>
        <Column SubColumnNumber="3" HTMLEncode="TRUE"/>
        <![CDATA[, Sc. ]]>
        <Column SubColumnNumber="4" HTMLEncode="TRUE"/>
        <![CDATA[, Ap. ]]>
        <Column SubColumnNumber="5" HTMLEncode="TRUE"/>
        <![CDATA[
]]>
        <Column SubColumnNumber="6" HTMLEncode="TRUE"/>
        <![CDATA[, Jud/Sec ]]>
        <Column SubColumnNumber="7" HTMLEncode="TRUE"/>
        <![CDATA[ ]]>
        <Column SubColumnNumber="8" HTMLEncode="TRUE"/>
    </Default>
  </Switch>
</RenderPattern>

I've tried with an XSL file like this
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema"
            xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
            version="1.0"
            exclude-result-prefixes="xsl msxsl ddwrt"
            xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
            xmlns:asp="http://schemas.microsoft.com/ASPNET/20"
            xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer"
            xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
            xmlns:msxsl="urn:schemas-microsoft-com:xslt"
            xmlns:SharePoint="Microsoft.SharePoint.WebControls"
            xmlns:ddwrt2="urn:frontpage:internal" ddwrt:oob="true">
<xsl:output method="html" indent="no"/>
<xsl:template match="FieldRef[@FieldType='AdresaField']" mode="Note_body">
<xsl:param name="thisNode" select="." />
<xsl:variable name="curElement" select="current()" />
<xsl:variable name="fldVal">
  <xsl:value-of select="$thisNode/@*[name()=$curElement/@Name]"/>
</xsl:variable>
<xsl:value-of select="substring($fldVal, 1, 3)"/> - Just to show it's working. Here I don't know how to do
</xsl:template>
</xsl:stylesheet>

Thank's

A: is the following link useful for you? http://www.intheknow.it/customxsltfieldrendering.ashx


text:
Q: JS match string from right to left Let's say I have the following object:
const obj = {
  'myApi': ['keyOne', 'keyTwo'],
  'myApi.keyOne': ['three', 'four'],
  'myApi.keyTwo': [...],
  'myApi.keyOne.three': [...]
  'myApi.keyOne.four': [...]
}

Now, based on the following string:
const str = "if(myApi.keyOne.three"

I want to match the correct object key, but from right to left. So, in the above example, I want to get obj["myApi.keyOne.three"].
indexOf or str.test methods will not work because they will catch myApi and myApi.keyOne also.
Note that it could be any string, the str is just an example. For example:
while(myApi.keyOne.three) {} // should match obj["myApi.keyOne.three"]
if(myApi.keyOne) {} // should match obj["myApi.keyOne"]

etc.
How can I do this?

A: To get the key, use a regular expression to match myApi, followed by any number of repeated groups of (a period followed by word characters). Then, you can just access the appropriate key on the object:

const obj = {
  'myApi': ['keyOne', 'keyTwo'],
  'myApi.keyOne': ['three', 'four'],
  'myApi.keyOne.three': ['foobar']
};

function getVal(str) {
  const key = str.match(/myApi(?:\.\w+)*/)[0];
  console.log(obj[key]);
  return obj[key];
}
getVal("if(myApi.keyOne.three");
getVal("while(myApi.keyOne.three) {}");
getVal("if(myApi.keyOne) {}");

A: Search for the key entry in the pattern:
var result = "";
Object.keys(obj).forEach(function(key) {
    if (str.indexOf(key) !== -1 && key.length > result.length) result = key;
});

console.log(obj[result]);

A: To make things more dynamic (even if there's no guarantee about myApi):

function findStuff(str, obj) {
  const keys = Object.keys(obj);
  keys.sort((a, b) => b.length - a.length);
  // https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript
  const re = new RegExp(keys.map(key => key.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')).join('|'));
  const match = str.match(re);
  return match && match[0];
}

const obj = {
  'myApi': ['keyOne', 'keyTwo'],
  'myApi.keyOne': ['three', 'four'],
  'myApi.keyTwo': [""],
  'myApi.keyOne.three': ["THREE"],
  'myApi.keyOne.four': [""]
}

console.log(findStuff('while(myApi.keyOne.three) {}', obj));

We take all the keys from the object, then sort them by descending length (so the longest will be matched first). Then regexp-escape them and stick them together in a regexp alternation.

A: You can use a regular expression like
myApi(\.\w+)*
Details:

* myApi - matches the "myApi" string

* (\.\w+)* - matches 0 or more repetitions of those alphanumeric strings which follows a period (.) character

const obj = {
  'myApi': ['keyOne', 'keyTwo'],
  'myApi.keyOne': ['three', 'four'],
  'myApi.keyTwo': ['someVlaue1'],
  'myApi.keyOne.three': ['someVlaue2'],
  'myApi.keyOne.four': ['someVlaue3']
}

var str1 = 'while(myApi.keyOne.three) {}';
var str2 = 'if(myApi.keyOne) {}';

var regex = /myApi(\.\w+)*/g;

var val1 = obj[ str1.match(regex)[0] ];
var val2 = obj[ str2.match(regex)[0] ];

console.log(val1);
console.log(val2);


text:
Q: The following C program regarding pointers is not working #include<stdio.h>
int main(void)
{
    int *pc;
    *pc=100;
    printf("\n Address of Pointer : %d",pc);
    printf("\n Contents of Pointer : %d",*pc);
}

When I run the code in eclipse, it is saying "Pointers.exe has stopped working". What is the error?

A: Assigning a value to *pc is particularly dangerous. If pc contains the valid memory address , then the assignment
*pc = 100;

will attempt to modify the data stored at that address.
If the location modified by this assignment belongs to the program, it may behave erratically; if it belongs to operating system, the program will most likely crash.
Your compiler should raise a warning that pc is uninitialized.

A: Change it to:
    int a;
    int *pc;

    pc = &a;
    *pc = 100;

Your pc pointer was not initialized in your program.
Moreover the way your are printing a pointer value is incorrect, use this:
printf("\n Address of Pointer : %p", (void *) pc);

A: You forgot to point pc to somewhere useful. When you write
int *pc;

The compiler creates a pointer for you. The pointer points somewhere in memory, and you have no way of knowing where. Chances are, it points to a bad place in memory. When you overwrite it with *pc=... you overwrite a place in memory that shouldn't be overwritten.
So you need to have pc point somewhere.
int a, *pc=&a;

will do the trick. Now the compiler prepares an int for you then and you point pc to it. That way, when you write through the pointer, nothing bad will happen - you're writing on an area of memory that you know is safe.
Another way to initialize pc is like so:
int *pc = (int*)malloc(sizeof(int)); // Allocate an integer on the heap

Now *pc=100; will also work. Just don't forget to free(pc) when you're done.

A: You have:

int *pc;
*pc=100;

When you define the pointer to integer pc above, this pointer is not initialized, so it points to some memory that you have not allocated and you have not the right to access.
So your executable is crashing.
Just use a valid pointer, e.g. you can allocate some heap memory using malloc(sizeof(int)) (and later release it using free()), or just use stack-based memory for local automatic variables, e.g.:
/* An integer stack-allocated variable */
int n = 64;

/* Pointer to that integer */
int * pn = &n;

/* Change its value */
*pn = 100;

Moreover, to print an address, considering using the %p specifier for printf().
e.g.:
#include <stdio.h>

int main(void)
{
    int n = 64;
    int *pn = &n;

    printf("n (before): %d\n", n);

    *pn = 100;
    printf("n (after): %d\n", n);

    printf("Address of n: %p", (void *)pn);

    return 0;
}

Output:

n (before): 64
n (after): 100
Address of n: 003AF7CC

A: Pointers need to POINT! A pointer is a variable that contains the adress of another variable.
int *pc;

This pointer contains some garbage value. Who knows what was in that memory before. The adress that it's pointing to could be an adress of memory that is occupied by another program. You need to assign a valid adress to a pointer if you want to change the value in that adress.
If you want to calculate sum of all the members of an array you would have to initialize the variable sum to 0 because it could contain other values.
The same is with pointers. They have to contain a valid adress of a variable if you want to modify the value.
Your program would work if you comment line *pc = 100;. You can display the adress of an uninitialized pointer but the program will crash if you try to change the value in that adress.


text:
Q: JavaFX TableView last column not appearing I need to make each of the cells in a TableView into JFXTextArea. The first 4 columns are perfect and let me enter text into them. But the 5th column just isn't clickable.When I click on it the entire row gets selected. How do I get the 5th column to behave like the first 4?
FXMLController.java
 @FXML
     private TableView<Person> table1;
     TableColumn indexCol = new TableColumn("S. No.");
     TableColumn desCol = new TableColumn("Description");
     TableColumn quantityCol = new TableColumn("Quantity");
     TableColumn unitCol = new TableColumn("Unit/(SGD)");
     TableColumn totalCol = new TableColumn("Total (SGD)");

void fillTable(){
     indexCol.setSortable(false);
     desCol.setSortable(false);
     quantityCol.setSortable(false);
     unitCol.setSortable(false);
     totalCol.setSortable(false);
     indexCol.setPrefWidth(50);
     table1.getColumns().addAll(indexCol, desCol, quantityCol, unitCol ,totalCol);
    ObservableList<Person> data;
    data = FXCollections.observableArrayList(
    new Person("Jack", "", "","", ""),
    new Person("Tom", "", "","", "")
    );
    indexCol.setCellValueFactory(
    new PropertyValueFactory<Person,String>("firstName")
    );
    desCol.setCellValueFactory(
    new PropertyValueFactory<Person,String>("lastName")
    );
     quantityCol.setCellValueFactory(
             new PropertyValueFactory<Person,String>("email")
    );
    unitCol.setCellValueFactory(
             new PropertyValueFactory<Person,String>("remark")
    );
    totalCol.setCellValueFactory(new PropertyValueFactory<Person,String>("total"));
    table1.setItems(data);
}

Person.java
public class Person {
    private JFXTextArea firstName;
    private  JFXTextArea lastName;
    private  JFXTextArea email;
    private JFXTextArea remark;
    private  JFXTextArea total;

    Person(String fName, String lName, String email, String value, String total1) {
        this.firstName= new JFXTextArea();
        this.firstName.setText(fName);
        this.firstName.setEditable(false);
        this.remark = new JFXTextArea();
        this.lastName = new JFXTextArea();
        this.email = new JFXTextArea();
        this.total = new JFXTextArea();

    }

    public JFXTextArea getFirstName() {
        return firstName;
    }
    public void setFirstName(JFXTextArea fName) {
        this.firstName = fName;
    }

    public JFXTextArea getLastName() {
        return lastName;
    }
    public void setLastName(JFXTextArea fName) {
        this.lastName =  fName;
    }

    public JFXTextArea getEmail() {
        return email;
    }
    public void setEmail(JFXTextArea fName) {
        this.email = fName;
    }

 public JFXTextArea getRemark() {
        return remark;
    }

    public void setRemark(JFXTextArea remark) {
        this.remark = remark;
    }

    public void settotal(JFXTextArea fName) {
            this.total = fName;
        }
     public JFXTextArea gettotal() {
            return total;
        }

}


text:
Q: NMEA 2000, configure repetition of messages According to the NMEA 2000 standard it is possible to configure the repetition time of messages which are specified by the manufacturer of the receiver. This is done by the Group Function message (PGN 126208) is sent. Because this message is larger than eight bytes, a transport protocol is needed.My question is, which protocol is used. Is it the TP (SAE J1939), ETP (ISOBUS), Fast Packet (NMEA2000)?
Thanks for the help

A: The PGN is composed of information from the 29-bit identifier format.  The contents are:

*

*EDP (Extended Data Page): 1-bit

*DP (Data Page): 1-bit

*PDU-F (PDU-Format): 8-bits

*PDU-S (PDU-Specific): 8-bits

The PGN you provide is 126208 which becomes 0x1ED00.  If you decode the information you see that EDP is 0 and DP is 1.  This is a NMEA2000 message.  Use the Fast-Packet transport protocol.
There's a good primer provided by Vector CANtech here:
http://vector.com/portal/medien/cmc/application_notes/AN-ION-1-3100_Introduction_to_J1939.pdf
(The DP & EDP bits are discussed on page 4 of that PDF)


text:
Q: How to use fcnchk in Matlab I'm having trouble figuring out how to use fcnchk correctly for this implementation:
function [w,t,flg] = RKF(FunFcnIn, Intv, alpha, tol, stepsize)
% On input:
%   FunFcnIn is the name of function to be integrated
%   A call to FunFcnIn with argument (t, y) returns f(t,y).

What type of input does FunFcnIn need to be in order to evaluate it as the comment suggests?


text:
Q: Issues with pass by reference in java I was trying to solve this problem from leetcode - https://leetcode.com/problems/combination-sum/
My test case is
Input = [1]
Result = 1

However, it is returning empty result. I think the code is doing fine. I mean the function getCombinations does add the value 1 to the result. But ultimately combinationSum return empty result. I think it has to do with something related to pass by reference or something. Any ideas what could have gone wrong?
public class Solution {
    public List<List<Integer>> combinationSum(int[] a, int target) {
        Arrays.sort(a);
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        ArrayList<Integer> current = new ArrayList<Integer>();
        getCombinations(0, a, result, target,current);
        return result;
    }

    public void getCombinations(int start, int[] a, List<List<Integer>> result, int target, ArrayList<Integer> current) {
        if(target == 0) {
            result.add(current);
            return;
        }
        if(target < 0) {
            return;
        }
        for(int i=start;i<a.length; i++) {
            current.add(a[i]);
            getCombinations(i+1, a, result,target-a[i],current);
            current.remove(current.size()-1);
        }
    }
}

A: You need to create a copy of current when adding to result like:
result.add(new ArrayList<>(current));

otherwise, when the items are removed from current, then they will be removed from the result too.


text:
Q: Make a http server accessible in a remote network through VPN I have an all Linux environment.
I'm connected to a remote network through a PPP VPN tunnel. My machine at home appears to be on the same network as the remote machines through the PPP interface.
This machine hosts an HTTP server, and the remote machines can view the web page in the browser by simply entering http://10.1.2.10:80.
I would like to move the HTTP server to another machine at home. But I don't want to configure a PPP connection for it as well. I want the current machine to be the VPN gateway towards the remote network for all my local machines.
The goal is for the remote machines to be able to access the HTTP server on a local machine that is not the gateway as easily as it is right now.
I imagine I would have to configure some port forwarding on the gateway. Do you have a comprehensive guide or recommendations for that?
This could be achieved with an HTTP proxy, but it feels like an overkill solution in my case.
Maybe there are other solutions.
Any VPN software that does the job will do.

A: You could use the Windows
Netsh interface portproxy commands
and specifically the verb
add v4tov4.
An example command would be to redirect all port 80 traffic to
IP address 192.168.0.10 by running as Administrator
the command:
netsh interface portproxy add v4tov4 listenaddress=127.0.0.1 listenport=80 connectaddress=192.168.0.10 connectport=80

The VPN might add some complexity to the local network solution,
but that's something you will need to solve on your end.

A: You may also want to consider setting up a VPN based on the modern Wireguard protocol, that supersedes the older more complex approach using OpenVPN.
A popular commercial VPN based on Wireguard that is easy to set up, can punch through most firewalls, and is free for personal use is Tailscale
Search Google for Nebula, Headscale, Netmaker, Netbird, and Yggdrasil for more open alternatives that may still meet your needs.


text:
Q: Including an external JSON file to work with Bootstrap I have this code and I am looking to include an external JSON file on my foreach() loop in order to display.
The JSON looks like this:
"items":[{"title":"ONE","content":"Something-1"},
{"title":"TWO","content":"Something-2"},
{"title":"THREE","content":"Something-3"}]

I have this code:
var data = 'doc.json';
$.getJSON(data)

var success = function(data) {
  data.items.forEach(function(item, index) {

    $('.latestinfo').append(
      '
' +
      '
' +
      '
' +
      '' +
      item.title +
      '' +
      '
' +
      '
' +
      '
' +
      '
' + // improves readability with the +, concatenates strings
      item.content +
      '
' +
      '
' +
      '
'
    );
  });
}

success(data);

A: You have to change your JSON file like below
{
  "items": [
    {
      "title": "ONE",
      "content": "Something-1"
    },
    {
      "title": "TWO",
      "content": "Something-2"
    },
    {
      "title": "THREE",
      "content": "Something-3"
    }
  ]
}

So now you can access items array using this method.

$.get('https://api.myjson.com/bins/v5ko2', function(result, status) {

    var data = result.items;

    // console.log(data);

    $.each(data, function(i, item) {

        console.log(item.title);

        // Now follow you append code here
        // $('.latestinfo').append("");

    });
});

A: You should send a callback function in $.getJSON(jsonpath,callbackFn) method, so that when the JSON gets fetched you can access the JSON in the callback function's data parameter.
var data = 'doc.json';

$.getJSON(data, function(data) {
  data.items.forEach(function(item, index) {

    $('.latestinfo').append(
      '
' +
      '
' +
      '
' +
      '' +
      item.title +
      '' +
      '
' +
      '
' +
      '
' +
      '
' + // improves readability with the +, concatenates strings
      item.content +
      '
' +
      '
' +
      '
'
    );
  });
})


text:
Q: Dropdownlist SelectedIndexChanged event do not trigger inside jQuery ui-Dialog I have a Dropdownlist with SelectedIndexChanged event inside jQuery ui-Dialog, but when I select an item in the DropdownList, SelectedIndexChanged event is not triggering though I already set AutopostBack to true, what could be the caused of this problem? any idea?
Here is my sample code:
 $(document).ready(function () {

            init();

            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

            function EndRequestHandler(sender, args) {
                init();

            }
        });

javascript function:
function init() {

            $(".dialog-form").dialog({
                autoOpen: false,
                modal: true,
                draggable: false,
                width: 1000,
                height: 600,
                close: function () {

                    $('body').css('overflow', 'auto');
                    $(".dialog-form").dialog("close");
                }
            }).parent().appendTo("form1");

            $(".add_ppmp").click(function () {
                $(".dialog-form").dialog("open");
                $('body').css('overflow', 'hidden');
            });
}

aspx code:

                    <asp:DropDownList ID="DropDownList1" runat="server" OnInit="LoadItems"  AutoPostBack="true" OnSelectedIndexChanged="cmbItem_SelectedIndexChanged"></asp:DropDownList>

A:     function init() {

            $(".dialog-form").dialog({
                autoOpen: false,
                modal: true,
                draggable: false,
                width: 1000,
                height: 600,
                close: function () {

                    $('body').css('overflow', 'auto');
                    $(".dialog-form").dialog("close");
                }
            }).parent().appendTo($("form:first"));

            $(".add_ppmp").click(function () {
                $(".dialog-form").dialog("open");
                $('body').css('overflow', 'hidden');
            });
}

Append the jquery ui dialog to form like above.

A: I'll explain this more generally to help googlers of the future.
If you view the source of the page, you may straight away slap your forehead and say "of course!"
When you create a dialog with jQuery UI the element you create the dialog out of comes out of the <form> and into the root of the  element. That's just how jQuery UI's dialog works.
The code behind the .aspx page is dependent on the form, anything outside the form cannot trigger the postback and therefore no code behind is run on any events that depend on elements outside the form.
The fix for this is thankfully quite simple :). After you create the dialog, simply append it to the <form>.
You have rightly tried to do that in your code, however the selector you've used $("form1") is looking for a <form1> type element - which doesn't exist.
You can fix it with this code: .parent().appendTo("form"); although to ensure you get the first form element only you can use .parent().appendTo("form:first");.
If form1 is the id of the form element you want to append to, then you would of course use $("#form1").


text:
Q: Using listings with multiple languages, define language as LaTeX gives error I'm documenting a system which produces PDF files from database entries using Python, and I'm using the listing package to insert the code via \lstinputlisting. Everything has worked fine 'till I got to the latex code. I can use \lstinputlisting[language=TeX]{myfile.tex} and it works fine, but if I use \lstinputlisting[language=[LaTeX]TeX]{myfile.tex} it will output Package Listings Error: File 'T(.tex)' not found. \lstinputlisting[language=[LaTeX]T. How can I fix it?
A MWE (or sort of, since it relies on the source code being on an external file and the languages defs are not so minimal) would be:
% !TeX encoding = UTF-8
\documentclass[letterpaper,11pt,oneside]{book}
\usepackage[utf8]{inputenc}
\usepackage[spanish]{babel}
\usepackage[spanish]{layout}
\usepackage{color}
\usepackage[usenames]{xcolor}
\usepackage{listings}

\definecolor{editorGray}{rgb}{0.95, 0.95, 0.95}
\definecolor{editorOcher}{rgb}{1, 0.5, 0} % #FF7F00 -> rgb(239, 169, 0)
\definecolor{editorGreen}{rgb}{0, 0.5, 0} % #007C00 -> rgb(0, 124, 0)

\lstdefinelanguage{JavaScript}{
    morekeywords={break, case, catch, continue, debugger, default, delete,         do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with},
    morecomment=[s]{/*}{*/},
    morecomment=[l]//,
    morestring=[b]",
    morestring=[b]'
}
\lstdefinelanguage{CSS}{
    keywords={accelerator,azimuth,background,background-attachment,
        background-color,background-image,background-position,
        background-position-x,background-position-y,background-repeat,
        behavior,border,border-bottom,border-bottom-color,
        border-bottom-style,border-bottom-width,border-collapse,
        border-color,border-left,border-left-color,border-left-style,
        border-left-width,border-right,border-right-color,
        border-right-style,border-right-width,border-spacing,
        border-style,border-top,border-top-color,border-top-style,
        border-top-width,border-width,bottom,caption-side,clear,
        clip,color,content,counter-increment,counter-reset,cue,
        cue-after,cue-before,cursor,direction,display,elevation,
        empty-cells,filter,float,font,font-family,font-size,
        font-size-adjust,font-stretch,font-style,font-variant,
        font-weight,height,ime-mode,include-source,
        layer-background-color,layer-background-image,layout-flow,
        layout-grid,layout-grid-char,layout-grid-char-spacing,
        layout-grid-line,layout-grid-mode,layout-grid-type,left,
        letter-spacing,line-break,line-height,list-style,
        list-style-image,list-style-position,list-style-type,margin,
        margin-bottom,margin-left,margin-right,margin-top,
        marker-offset,marks,max-height,max-width,min-height,
        min-width,-moz-binding,-moz-border-radius,
        -moz-border-radius-topleft,-moz-border-radius-topright,
        -moz-border-radius-bottomright,-moz-border-radius-bottomleft,
        -moz-border-top-colors,-moz-border-right-colors,
        -moz-border-bottom-colors,-moz-border-left-colors,-moz-opacity,
        -moz-outline,-moz-outline-color,-moz-outline-style,
        -moz-outline-width,-moz-user-focus,-moz-user-input,
        -moz-user-modify,-moz-user-select,orphans,outline,
        outline-color,outline-style,outline-width,overflow,
        overflow-X,overflow-Y,padding,padding-bottom,padding-left,
        padding-right,padding-top,page,page-break-after,
        page-break-before,page-break-inside,pause,pause-after,
        pause-before,pitch,pitch-range,play-during,position,quotes,
        -replace,richness,right,ruby-align,ruby-overhang,
        ruby-position,-set-link-source,size,speak,speak-header,
        speak-numeral,speak-punctuation,speech-rate,stress,
        scrollbar-arrow-color,scrollbar-base-color,
        scrollbar-dark-shadow-color,scrollbar-face-color,
        scrollbar-highlight-color,scrollbar-shadow-color,
        scrollbar-3d-light-color,scrollbar-track-color,table-layout,
        text-align,text-align-last,text-decoration,text-indent,
        text-justify,text-overflow,text-shadow,text-transform,
        text-autospace,text-kashida-space,text-underline-position,top,
        unicode-bidi,-use-link-source,vertical-align,visibility,
        voice-family,volume,white-space,widows,width,word-break,
        word-spacing,word-wrap,writing-mode,z-index,zoom},
    sensitive=true,
    morecomment=[l]{//},
    morecomment=[s]{/*}{*/},
    morestring=[b]',
    morestring=[b]",
    alsoletter={:},
    alsodigit={-}
}
\lstdefinelanguage{HTML5}{
    language=html,
    sensitive=true,
    alsoletter={<>=-},
    otherkeywords={
        % HTML tags
        <, </, >,
        </a, <a, </a>,
        </abbr, <abbr, </abbr>,
        </address, <address, </address>,
        </area, <area, </area>,
        </area, <area, </area>,
        </article, <article, </article>,
        </aside, <aside, </aside>,
        </audio, <audio, </audio>,
        </audio, <audio, </audio>,
        </b, <b, </b>,
        </base, <base, </base>,
        </bdi, <bdi, </bdi>,
        </bdo, <bdo, </bdo>,
        </blockquote, <blockquote, </blockquote>,
        </body, <body, </body>,
        </br, <br, </br>,
        </button, <button, </button>,
        </canvas, <canvas, </canvas>,
        </caption, <caption, </caption>,
        </cite, <cite, </cite>,
        </code, <code, </code>,
        </col, <col, </col>,
        </colgroup, <colgroup, </colgroup>,
        </data, <data, </data>,
        </datalist, <datalist, </datalist>,
        </dd, <dd, </dd>,
        </del, <del, </del>,
        </details, <details, </details>,
        </dfn, <dfn, </dfn>,
        </div, <div, </div>,
        </dl, <dl, </dl>,
        </dt, <dt, </dt>,
        </em, <em, </em>,
        </embed, <embed, </embed>,
        </fieldset, <fieldset, </fieldset>,
        </figcaption, <figcaption, </figcaption>,
        </figure, <figure, </figure>,
        </footer, <footer, </footer>,
        </form, <form, </form>,
        </h1, <h1, </h1>,
        </h2, <h2, </h2>,
        </h3, <h3, </h3>,
        </h4, <h4, </h4>,
        </h5, <h5, </h5>,
        </h6, <h6, </h6>,
        </head, <head, </head>,
        </header, <header, </header>,
        </hr, <hr, </hr>,
        </html, <html, </html>,
        </i, <i, </i>,
        </iframe, <iframe, </iframe>,
        </img, <img, </img>,
        </input, <input, </input>,
        </ins, <ins, </ins>,
        </kbd, <kbd, </kbd>,
        </keygen, <keygen, </keygen>,
        </label, <label, </label>,
        </legend, <legend, </legend>,
        </li, <li, </li>,
        </link, <link, </link>,
        </main, <main, </main>,
        </map, <map, </map>,
        </mark, <mark, </mark>,
        </math, <math, </math>,
        </menu, <menu, </menu>,
        </menuitem, <menuitem, </menuitem>,
        </meta, <meta, </meta>,
        </meter, <meter, </meter>,
        </nav, <nav, </nav>,
        </noscript, <noscript, </noscript>,
        </object, <object, </object>,
        </ol, <ol, </ol>,
        </optgroup, <optgroup, </optgroup>,
        </option, <option, </option>,
        </output, <output, </output>,
        </p, <p, </p>,
        </param, <param, </param>,
        </pre, <pre, </pre>,
        </progress, <progress, </progress>,
        </q, <q, </q>,
        </rp, <rp, </rp>,
        </rt, <rt, </rt>,
        </ruby, <ruby, </ruby>,
        </s, <s, </s>,
        </samp, <samp, </samp>,
        </script, <script, </script>,
        </section, <section, </section>,
        </select, <select, </select>,
        </small, <small, </small>,
        </source, <source, </source>,
        </span, <span, </span>,
        </strong, <strong, </strong>,
        </style, <style, </style>,
        </summary, <summary, </summary>,
        </sup, <sup, </sup>,
        </svg, <svg, </svg>,
        </table, <table, </table>,
        </tbody, <tbody, </tbody>,
        </td, <td, </td>,
        </template, <template, </template>,
        </textarea, <textarea, </textarea>,
        </tfoot, <tfoot, </tfoot>,
        </th, <th, </th>,
        </thead, <thead, </thead>,
        </time, <time, </time>,
        </title, <title, </title>,
        </tr, <tr, </tr>,
        </track, <track, </track>,
        </u, <u, </u>,
        </ul, <ul, </ul>,
        </var, <var, </var>,
        </video, <video, </video>,
        </wbr, <wbr, </wbr>,
        />, <!
    },
    ndkeywords={
        % General
        =,
        % HTML attributes
        accept=, accept-charset=, accesskey=, action=, align=, alt=, async=, autocomplete=, autofocus=, autoplay=, autosave=, bgcolor=, border=, buffered=, challenge=, charset=, checked=, cite=, class=, code=, codebase=, color=, cols=, colspan=, content=, contenteditable=, contextmenu=, controls=, coords=, data=, datetime=, default=, defer=, dir=, dirname=, disabled=, download=, draggable=, dropzone=, enctype=, for=, form=, formaction=, headers=, height=, hidden=, high=, href=, hreflang=, http-equiv=, icon=, id=, ismap=, itemprop=, keytype=, kind=, label=, lang=, language=, list=, loop=, low=, manifest=, max=, maxlength=, media=, method=, min=, multiple=, name=, novalidate=, open=, optimum=, pattern=, ping=, placeholder=, poster=, preload=, pubdate=, radiogroup=, readonly=, rel=, required=, reversed=, rows=, rowspan=, sandbox=, scope=, scoped=, seamless=, selected=, shape=, size=, sizes=, span=, spellcheck=, src=, srcdoc=, srclang=, start=, step=, style=, summary=, tabindex=, target=, title=, type=, usemap=, value=, width=, wrap=,
        % CSS properties
        accelerator:,azimuth:,background:,background-attachment:,
        background-color:,background-image:,background-position:,
        background-position-x:,background-position-y:,background-repeat:,
        behavior:,border:,border-bottom:,border-bottom-color:,
        border-bottom-style:,border-bottom-width:,border-collapse:,
        border-color:,border-left:,border-left-color:,border-left-style:,
        border-left-width:,border-right:,border-right-color:,
        border-right-style:,border-right-width:,border-spacing:,
        border-style:,border-top:,border-top-color:,border-top-style:,
        border-top-width:,border-width:,bottom:,caption-side:,clear:,
        clip:,color:,content:,counter-increment:,counter-reset:,cue:,
        cue-after:,cue-before:,cursor:,direction:,display:,elevation:,
        empty-cells:,filter:,float:,font:,font-family:,font-size:,
        font-size-adjust:,font-stretch:,font-style:,font-variant:,
        font-weight:,height:,ime-mode:,include-source:,
        layer-background-color:,layer-background-image:,layout-flow:,
        layout-grid:,layout-grid-char:,layout-grid-char-spacing:,
        layout-grid-line:,layout-grid-mode:,layout-grid-type:,left:,
        letter-spacing:,line-break:,line-height:,list-style:,
        list-style-image:,list-style-position:,list-style-type:,margin:,
        margin-bottom:,margin-left:,margin-right:,margin-top:,
        marker-offset:,marks:,max-height:,max-width:,min-height:,
        min-width:,transition-duration:,transition-property:,
        transition-timing-function:,transform:,
        -moz-transform:,-moz-binding:,-moz-border-radius:,
        -moz-border-radius-topleft:,-moz-border-radius-topright:,
        -moz-border-radius-bottomright:,-moz-border-radius-bottomleft:,
        -moz-border-top-colors:,-moz-border-right-colors:,
        -moz-border-bottom-colors:,-moz-border-left-colors:,-moz-opacity:,
        -moz-outline:,-moz-outline-color:,-moz-outline-style:,
        -moz-outline-width:,-moz-user-focus:,-moz-user-input:,
        -moz-user-modify:,-moz-user-select:,orphans:,outline:,
        outline-color:,outline-style:,outline-width:,overflow:,
        overflow-X:,overflow-Y:,padding:,padding-bottom:,padding-left:,
        padding-right:,padding-top:,page:,page-break-after:,
        page-break-before:,page-break-inside:,pause:,pause-after:,
        pause-before:,pitch:,pitch-range:,play-during:,position:,quotes:,
        -replace:,richness:,right:,ruby-align:,ruby-overhang:,
        ruby-position:,-set-link-source:,size:,speak:,speak-header:,
        speak-numeral:,speak-punctuation:,speech-rate:,stress:,
        scrollbar-arrow-color:,scrollbar-base-color:,
        scrollbar-dark-shadow-color:,scrollbar-face-color:,
        scrollbar-highlight-color:,scrollbar-shadow-color:,
        scrollbar-3d-light-color:,scrollbar-track-color:,table-layout:,
        text-align:,text-align-last:,text-decoration:,text-indent:,
        text-justify:,text-overflow:,text-shadow:,text-transform:,
        text-autospace:,text-kashida-space:,text-underline-position:,top:,
        unicode-bidi:,-use-link-source:,vertical-align:,visibility:,
        voice-family:,volume:,white-space:,widows:,width:,word-break:,
        word-spacing:,word-wrap:,writing-mode:,z-index:,zoom:
    },
    morecomment=[s]{<!--}{-->},
    tag=[s]
}
\lstset{%
    % Basic design
    backgroundcolor=\color{editorGray},
    basicstyle={\scriptsize\ttfamily},
    frame=l,
    % Line numbers
    %xleftmargin={0.75cm},
    numbers=left,
    stepnumber=1,
    firstnumber=1,
    numberfirstline=true,
    % Code design
    keywordstyle=\color{blue}\bfseries,
    %commentstyle=\color{darkgray}\ttfamily,
    commentstyle=\color{editorGreen}\ttfamily,
    ndkeywordstyle=\color{editorGreen}\bfseries,
    stringstyle=\color{editorOcher},
    % Code
    language=HTML5,
    alsolanguage=JavaScript,
    alsodigit={.:;},
    tabsize=2,
    showtabs=false,
    showspaces=false,
    showstringspaces=false,
    extendedchars=true,
    breaklines=true,
    literate={Á}{{\'A}}1 {á}{{\'a}}1 {É}{{\'E}}1 {é}{{\'e}}1 {Í}{{\'I}}1 {í}{{\'i}}1 {Ó}{{\'O}}1 {ó}{{\'o}}1 {Ú}{{\'U}}1 {ú}{{\'u}}1 {Ñ}{{\~N}}1
            {ñ}{{\~n}}1 {¿}{{?`}}1 {¡}{{!`}}1 {°}{{\degree}}1 {•}{{\textbullet}}1 {"}{{``}}1 {"}{{''}}1,
    title=\lstname
}

\begin{document}
\lstinputlisting[language=[LaTeX]TeX]{myfile.tex}
\end{document}

A: I solved it defining a dummy language:
\lstdefinelanguage{template}{
    language=[LaTeX]{TeX},
    sensitive=true
}

What i'd like now is to have a different style for it... guess I'll have to post that on another question.

A: This solution works:
\lstinputlisting[ language={[LaTeX]TeX} ] {myfile.tex}

Observe the language setting using curly braces {}


text:
Q: How to make a parser for a web crawler maintainable I wrote a Ruby web-crawler that retrieves data from a third-party website. I am using Nokogiri to extract information based on a specific CSS div and specific fields (accessing children and elements of the nodes I extract).
From time to time, the structure of the third-party website changes which breaks the crawler (element[1].children[2] might need to be changed to element[2].children[0]).
So far, I have a utility that prints the structure of the node I extract which allows me to quickly fix the parser when the structures change. I also have an automated process that controls that it can extract "some" values.
I would like to know if there is a more elegant way to deal with this issue. How would one write a crawler that is easy to maintain?

A: You should try to use the data and metadata of the web page to find the element you care about as much as possible instead of using element index numbers like you are doing.
The "class" and "id" attributes are a good way to do it.  Nokogiri has XPath features that should make it easy to select elements based on those.  If that is not possible, you could try looking at the content of the page around the element, e.g. if you are looking for a weight and you know it is in a table, you could search for strings ending with "kg".  It's hard to give super-specific tips without seeing the document you are parsing.
I recommend that your crawler should check the data is retrieving and raise an exception (or show a warning) if the data looks wrong.

A: Use CSS.
For example the price of a product will almost always be:
page.at('#price, .price').text

The site can change layout (theme) and this will still work.


text:
Q: Lebesgue Measures Hi guys I got a doubt about how to interpret the following:

Given measurable space $(\Omega, \Im ) \hspace{.1cm} \text{and} \hspace{.1cm}(\mathbb{P}_n)_{n\geq0 }$ succession of probability measures defined on $(\Omega, \Im) $ and $\forall \hspace{.1cm} A \in\Im:$ $\mathbb{P}(A) = \sum_{n=0}^{\infty } a_{n}\mathbb{P}_n(A)$

Now if $\hspace{.01cm}$ $\varphi$ is an integrable function with respect to $\mathbb{P}$ $\hspace{.01cm}$, then $\hspace{.01cm}$ $\varphi$ is an integrable function with respect to $\mathbb{P}_n$
I can barely understand why this happens, but i get confused why the reciprocal it's not true:
If $\hspace{.01cm}$ $\varphi$ is an integrable function with respect to $\mathbb{P}_n$, $\hspace{.01cm}$ then$\hspace{.01cm}$ $\varphi$ is an integrable function with respect to $\mathbb{P}$
Why this is false?

A: To see the failure of the converse, consider $a_n=2^{-(n+1)}$ and $\mathbb{P}_n$ concentrated on the number $3^n$ with $\varphi(x)=x$.


text:
Q: International shipping calculation with Paypal? We're offering Paypal checkout as a way to purchase items on our website, and offer our goods internationally.  Our problem is that when a user selects Paypal there's no easy way to set a shipping cost based on their location...
For instance if a user is from the USA, his/her shipping cost will be $3.85
If a user is from the UK, his/her shipping cost will be $5
Aside from having users pre-select their country (which seems pretty flimsy because they could just select domestic, then change their address to something international) is there a way for Paypal to adjust shipping based on user's shipping address??

A: Does https://www.paypal.com/cgi-bin/webscr?cmd=xpt/shipping/EasyCalculateShipAndTax-outside help at all? It describes a way to (within PayPal's interface) pre-set shipping costs for different destination countries.

A: It looks like this article and thread may have fallen into the abyss but I thought I might chime in and give my two sense.
The challenges I have struggled with around international sales are really two parts.
First, and I won't dive too deeply as its more related to the merchant service and credit card processing side of the business, but merchant services and payment gateways have yet to deploy a system that roots out fraud. The unfortunate fact is that assuming a customer abroad uses a fraudulent credit card it will almost certainly slide through the gateway and merchant services as a good sale, then deposited into the retailer bank account, only to be identified as suspicious weeks later. Naturally the banks reach in and extract the fraudulent funds and leave the retailer holding the bag.
The other side of it the logistics, and more precisely the competitive or noncompetitive pricing leading to sales.
Amazon.com has been a steamroller throughout the marketplace and many would argue the vast benefits it has brought with it byway of competitive forces. Amazon has been a God send to many particularly small businesses who without the Amazon marketing advantage would be little more than a doodle on the back of a napkin at the looking drinking hole. They are great at reaching a domestic consumer and their impact in the larger international space is growing fast.
But for those of us who try to sell through our own website, foregoing the massive commissions paid to the behemoth, it can be a little daunting to tackle the international shipping.
First, the rates. Getting rates that compete is tough. Have you seen the retail rates from Fedex, DHL, or TNT? They are insanely expensive and unrealistic for a retailer. I negotiated rates with UPS, TNT, and DHL, but the results were not good. Not enough volume to drive real discounts. This is when competing with Amazon makes you feel really really small.
I'm measuring the percentage of lost business against incremental increases to shipping rates and its extreme.
Frankly, as a seller who has evolved through the past decade of Amazon ups and downs I've learned through heartache and loosing lots of money, whether through BiG Bank Merchant Services who take no prisioners or the hefty costs for international shipping. Where I have moved my inventories is away from Amazon and FBA and into fulfillment centers capable of handling all my logistics issues.
For instance, reverse logistics. For those of you who may be new to the term, it refers to the process of returning merchandise from end consumer to merchant. Managing this with international customers can be complex. Additionally, fulfillment centers offer volume rates I'm not able to get on my own with the aforementioned carriers; UPS, FEDEX, DHL, TNT. Rather, the fulfillment operations I work with tend to be flexible and understand the cost correlation associated with international sales.
The fulfillment companies I have used are:
Good - Amazon FBA
Better - Shipwire
Best - Newgistics
I won't ooze over any of them, but I'll say that as my requirements have evolved FBA was incapable of keeping pace. With the other solutions I have full EDI integration by and between me and all my distribution partners. Partners that make life a lot more manageable.
As for international shipping rates that beat retail published rates, check out these international shipping calculators:
USPS
DHL
MyUS
American eBox
    ``
These will at the very least send you in a direction that makes sense.
I hope this personal recount provides help to those who are transitioning through differing stages of growth.


text:
Q: use of w:tag in Office openxml/javascript add-in I have the following:

  Word.run(function (context) {
    docSelection = context.document.getSelection();

var text = '<w:sdt><w:sdtPr><w:alias w:val="SomeAlias" /><w:tag w:val="SomeTag" /><w:lock w:val="sdtLocked" /></w:sdtPr>'
 + '<w:sdtContent><w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:pPr><w:pStyle w:val="NormalWeb" /></w:pPr>'
 + '<w:r><w:t>MY TEXT</w:t></w:r></w:p></w:sdtContent></w:sdt>';

    docSelection.insertOoxml(text, "Replace");
      return context.sync().then(function () {
        console.log('Text insertion complete');
      });
    })
  .catch(function (error) {
      console.log("Error: " + error);
      if (error instanceof OfficeExtension.Error) {
          console.log("Debug info: " + JSON.stringify(error.debugInfo));
          displayError(JSON.stringify(error));
          return false;
      }
  });

Running this, I get the error:
"Debug info: {"code":"GeneralException","message":"GeneralException","errorLocation":"Range.insertOoxml","statement":"var insertOoxml = selection.insertOoxml(...);","surroundingStatements":["var root = context.root;","var selection = root.getSelection();","// Instantiate {selection}","// >>>>>","var insertOoxml = selection.insertOoxml(...);","// <<<<<","// Instantiate {insertOoxml}"],"fullStatements":["var root = context.root;","var selection = root.getSelection();","// Instantiate {selection}","var insertOoxml = selection.insertOoxml("<w:sdt><w:sdtPr><w:alias w:val=\"SomeAlias\" /><w:tag w:val=\"SomeTag\" /><w:lock w:val=\"sdtLocked\" /></w:sdtPr><w:sdtContent><w:p xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:pPr><w:pStyle w:val=\"NormalWeb\" /></w:pPr><w:r><w:t>MY TEXT</w:t></w:r></w:p></w:sdtContent></w:sdt>", "Replace");","// Instantiate {insertOoxml}"]}"
which I quite simply don't understand.
Inserting with docSelection.insertOoxml("<w:p xmlns:w='http://schemas.microsoft.com/office/word/2003/wordml'><w:r><w:t>TEST</w:t></w:r></w:p>", "Replace");
works fine so the rest of my code is OK.
Any ideas what I'm doing wrong?

A: XML:
<pkg:package xmlns:pkg='http://schemas.microsoft.com/office/2006/xmlPackage'>
            <pkg:part pkg:name='/_rels/.rels' pkg:contentType='application/vnd.openxmlformats-package.relationships+xml' pkg:padding='512'>
                <pkg:xmlData>
                    <Relationships xmlns='http://schemas.openxmlformats.org/package/2006/relationships'>
                        <Relationship Id='rId1' Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument' Target='word/document.xml'/>
                    </Relationships>
                </pkg:xmlData>
            </pkg:part>
            <pkg:part pkg:name='/word/document.xml' pkg:contentType='application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'>
                <pkg:xmlData>
                    <w:document xmlns:w='http://schemas.openxmlformats.org/wordprocessingml/2006/main'>
                        <w:body>
                            <w:sdt>
                                <w:sdtPr>
                                    <w:lock w:val="contentLocked"/>
                                </w:sdtPr>
                                <w:sdtContent>
                                    <w:p>
                                        <w:pPr>
                                            <w:alias w:val="Table of Contents"/>
                                            <w:tag w:val="TOCLitera"/>
                                            <w:spacing w:after="480"/>
                                            <w:jc w:val="center"/>
                                            <w:pStyle w:val='TOCHeading'/>
                                        </w:pPr>
                                        <w:r>
                                            <w:rPr>
                                                <w:keepNext/>
                                                <w:keepLines/>
                                                <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi"/>
                                                <w:sz w:val="32"/>
                                                <w:szCs w:val="32"/>
                                                <w:b/>
                                                <w:caps/>
                                            </w:rPr>
                                            <w:t>Table of Contents</w:t>
                                        </w:r>
                                    </w:p>
                                    <w:r>
                    <w:rPr>
                        <w:b/>
                        <w:bCs/>
                        <w:noProof/>
                    </w:rPr>
                    <w:t>No table of contents entries found.</w:t>
                </w:r>
                                </w:sdtContent>
                            </w:sdt>
                        </w:body>
                    </w:document>
                </pkg:xmlData>
            </pkg:part>
        </pkg:package>

Below I gave link example to create TOC:
http://tutorials.winplaybox.in/api/how-to-create-table-of-contents-in-o365-add-in/


text:
Q: Up-Down control doesn't show its position in its buddy window I created an up-down control by the following code.
HWND hEdit, hUpDown;

hEdit = CreateWindowExW(WS_EX_CLIENTEDGE,
                        L"EDIT",
                        Content.c_str(),
                        ES_LEFT | WS_VISIBLE | WS_CHILD,
                        600,
                        260,
                        100,
                        25,
                        hWndParent,
                        NULL,
                        hInstance,
                        NULL);

INITCOMMONCONTROLSEX iccx;
iccx.dwSize = sizeof(INITCOMMONCONTROLSEX);
iccx.dwICC  = ICC_UPDOWN_CLASS;
InitCommonControlsEx(&iccx);

hUpDown = CreateWindowExW(  0,
                            UPDOWN_CLASSW,
                            L"",
                            UDS_ARROWKEYS | UDS_ALIGNRIGHT | WS_VISIBLE | WS_CHILD,
                            0,
                            0,
                            0,
                            0,
                            hWndParent,
                            NULL,
                            hInstance,
                            NULL);

SendMessageW(hUpDown, UDM_SETBUDDY,   (WPARAM) hEdit, (LPARAM) NULL);
SendMessageW(hUpDown, UDM_SETRANGE32, (WPARAM) 0,     (LPARAM) 100);
Sleep(5000);
SendMessageW(hUpDown, UDM_SETPOS32,   (WPARAM) NULL,  (LPARAM) 20);
Sleep(5000);
SendMessageW(hUpDown, UDM_SETPOS32,   (WPARAM) NULL,  (LPARAM) 60);

I checked the return values of the SendMessageW() functions. They terminate successfully by returning the previous position value as documented.
The created up-down control looks normal:

The problem is, sending the UDM_SETPOS32 message, clicking the up and down arrows and pressing the up and down keys on the keyboard have no effect. I can't change the contents of the edit control (the buddy window of the up-down control) without directly typing something into it. It just stays empty.
I am able to type anything in it manually by using keyboard:

How do I change the position/value of this up-down control by pressing keyboard arrow keys, by clicking the arrows in the GUI and by sending UDM_SETPOS32 in the code? What am I missing in my code?

A: Use the style UDS_SETBUDDYINT to the up-down control while creating it.
From MSDN documentation:

UDS_SETBUDDYINT
  Causes the up-down control to set the text of the buddy window (using the WM_SETTEXT message) when the position changes. The text consists of the position formatted as a decimal or hexadecimal string.

Change the creation code of the up-down control like this by adding the UDS_SETBUDDYINT style:
hUpDown = CreateWindowExW(  0,
                            UPDOWN_CLASSW,
                            L"",
                            UDS_SETBUDDYINT | UDS_ARROWKEYS | UDS_ALIGNRIGHT | WS_VISIBLE | WS_CHILD,
                            0,
                            0,
                            0,
                            0,
                            hWndParent,
                            NULL,
                            hInstance,
                            NULL);


text:
Q: WooCommerce : How to convert wp_price value to a numeric value? I'm developing a table with two columns, "State" and "Sales". To get the number in the sales column, I use the wc_price function, which works just fine to output a currency string:
CA         $1,652.13
CO         $515.80
...etc.
I have at least 50 rows, one for each state.
The very last row will output the total of all the dollar amounts from column 2.
I discovered that the actual result from wc_price isn't just a sting, it's a block of html:
<bdi>
    $
    435.50
</bdi>

I tried to get to the actual number within the html, 435.50 using strip_tags:
$numeric = strip_tags(wc_price($total)); // result is a simple string, with the $ sign
echo str_replace("$","",$numeric) . "
"; // doesn't strip away the $ sign.
$tally = $tally + $numeric; // produces an error, non-numeric value.

The error is on the $tally = line. This doesn't work in any way. Sure, the html tags are stripped, and I'm left with a string: $435.50. In other words, I can't get rid of that danged '$' for some reason. I simply cannot parse, convert, or anything to that currency string. (int), intval($numeric), (float)$numeric, floatval($numeric), etc., none of these work. number_format doesn't work, either.
Warning: A non-numeric value encountered in C:\xampp\htdocs\mysite\wp-content\plugins\my-custom-plugin\my-custom-plugin.php on line 104

A: Add a floatval() around your str_replace and assign the variable.
    $numeric = strip_tags($html);
    $numeric = floatval(str_replace("$", "", $numeric));

See working example. It works with 5.6, 7.4 and 8.1.

A: I'm not sure of the result, but I think it's possible to have the price without the currecy reading from the documentation of wp_price:
$numeric = wp_price($total, array('currency'=>''));

However you can have some action that change the comportament of the wc_price function.