text:
Q: is it possible to get function name in which given closure is running? function MyFunction() {
  closure = function() {
    alert('my parent function name is: '/* now what here ? */);
  }
  closure();
}
MyFunction();

Result should be my parent function name is: MyFunction
(To moderators: I do not know why stackoverflow is preventing me from sending this question claiming it doesn't meet quality standards. Do I must type some superfluous text to be allowed to send this.)

A: That is/was possible, but it is restricted. First restriction, not all Javascript engines support the following pattern and second (more dramatic), ES5 strict mode does not support it either.
Some Javascript engines allow you to access the .__parent__ property which is a reference to the parent scope. That should look like
alert('my parent is ' + this.__parent__.name );

where you would have to call new closure(), or give the function a name and use that name instead of this.
However, most implementations removed that access for security concerns. As you may noticed, you're able to breach the 'allmighty' closure security by beeing able to access the parent context.

Another way to accomplish it, is to access arguments.callee.caller, which also is not accessible in ES5 strict mode. Looks like:
function MyFunction() {
  closure = function f() {
    alert('my parent function name is: ' +  arguments.callee.caller.name);
  }
 closure();
}
MyFunction();

A: function MyFunction() {
  closure = function() {
    alert('my parent function name is: ' + arguments.callee.caller.name);
  }
  closure();
}
MyFunction();

A: function MyFunction() {
    var functionName = arguments.callee.name,
    closure = function() {
        alert('my parent function name is: ' + functionName);
    }
    closure();
}
MyFunction();


text:
Q: Unexpected behavior of c++ program on executing two equivalent statements I was trying to solve this problem,
while doing so,
it looks like
for (int i=row1; i<=row2; i++) {
    if (col1 != 0) sum -= mat[i][col1-1];
    sum += mat[i][col2];
}

and
for (int i=row1; i<=row2; i++) {
    sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);
}

are equivalent, but executing the later results in following error
Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34

Am I missing something?, Thank You In Advance.
complete program:
class NumMatrix {
public:
    vector<vector<int>> mat;
    NumMatrix(vector<vector<int>>& matrix) {
        mat = matrix;
        for (int i=0; i<matrix.size(); i++) {
            for (int j=1; j<matrix[0].size(); j++)
                mat[i][j] += mat[i][j-1];
        }
    }

    int sumRegion(int row1, int col1, int row2, int col2) {
        int sum = 0;
        for (int i=row1; i<=row2; i++) {
            if (col1 != 0) sum -= mat[i][col1-1];
            sum += mat[i][col2];

            // sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0); // this gives error :
            // Line 1038: Char 34: runtime error: addition of unsigned offset to 0x618000000080 overflowed to 0x61800000007c (stl_vector.h)
            // SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_vector.h:1043:34
        }

        return sum;
    }
};

/**
 * Your NumMatrix object will be instantiated and called as such:
 * NumMatrix* obj = new NumMatrix(matrix);
 * int param_1 = obj->sumRegion(row1,col1,row2,col2);
 */

A: This statement
sum += (mat[i][col2] - (col1 != 0) ? mat[i][col1-1] : 0);

is equivalent ti
sum += (mat[i][col2] - (col1 != 0) ) ? mat[i][col1-1] : 0;

So for example if this expression (mat[i][col2] - (col1 != 0) ) is not equal to 0 then you will have in fact
sum += mat[i][col1-1];

even when col1 is equal to 0.
It seems you mean
sum += mat[i][col2] - ( (col1 != 0) ? mat[i][col1-1] : 0);

Pay attention to that this function
int sumRegion(int row1, int col1, int row2, int col2) {

is unsafe. There is no check whether row1, row2, col1 and col2 are in valid ranges.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ParseFromString failure to decode message I'm trying to interface with a RESTful API that accepts application/x-protobuf objects in post.
.proto example object:
message register
{
    required string name = 1;
    required int32 id = 2;
}

using requests I'm able to POST this message to the server and receive a 200.
e.g.
register = protobuf_pb2.register()
register.name = "foo"
register.id = 1

response = requests.request("POST", url, data=register.SerializeToString(), headers=headers)

when I look at this payload in SerializeToString() format it shows similar to

b'\n\t\n\x03foo\x10\x01'

As a sanity check, I can then create a new message object and .ParseFromString() on that back into the correct message format.
A second uri on the server allows you to send a GET request to retrieve that same data. So I used the following:
register = protobuf_pb2.register()
response = requests.request("GET", url, headers=headers).content
register.ParseFromString(response)

The response returns

b'foo:1\n'

And ParseFromString returns the exception

DecodeError('Error parsing message',)

Am I missing a step somewhere?
Should the .content payload be encoded somehow before being parsed?
Many thanks.

A: The object you are getting back from the server is binary data, UTF-8 encoded, so Python interprets it as a bytes object (in Python 3, bytes and str are different types).
m = b'foo:1\n'
type(m)
Out[1]: bytes

m.decode('utf-8')
Out[2]: 'foo:1\n'

ParseFromString however expects a string, so it throws a DecodeError; just use the decode() with the appropriate encoding.
In the response headers you should be able to find the encoding used: pretty much everyone uses UTF-8, but in "real" Production code, you should check that too: in the Content-Type (or you can even request a specific one with Accept-Charset but you may get a 406, if the server cannot fulfil it).


text:
Q: Imprimir automáticamente cada vez que se cree un archivo en una carpeta - Python Soy nuevo ocupando el lenguaje Python y tengo un problema.
El código continuación muestra el nombre y el contenido del ultimo archivo creado en una carpeta en especifico:
import glob

import os

 newest=max(glob.iglob('/Users/BetaBrawler/Downloads/HernanVillela/*'), key=os.path.getctime)

 print newest

 file = open(newest,'r')

 texto = [x.strip() for x in file.readlines()]

 print texto

Output
/Users/BetaBrawler/Downloads/HernanVillela\Ultimo archivo creado.txt
['Contenido del ultimo archivo creado']

El problema es que quiero que el código se mantenga ejecutando constantemente con el fin de que cada vez que cree un archivo en la carpeta se muestre su nombre y su contenido de forma automática sin tener que volverlo a ejecutar
¿Tengo que agregar un while y un break?

A: Tu pregunta, si no la entendí mal es: quiero controlar constantemente una carpeta y si hay nuevos archivos imprimirlos. Esto tiene varias dificultades para resolver.
Por empezar, la idea es resolver todo con código básico, pero te comento que hay módulos de python especialmente creados para esto, por ejemplo watchdog.
El primer problema es obtener la fecha de creación de un archivo, lamentablemente el uso de os.path.getctime no es multiplataforma, por lo que vamos a incorporar el código de este enlace a la solución para que el script nos sirva en Linux/Windows.
Como ya te comentaron, necesitas un ciclo infinito while True, que igual se puede interrumpir con un ctrl-c. En ese ciclo invocaremos a una rutina get_newestfiles que se encargará de devolver una lista de los archivos cuya fecha de creación sea superior a una determinada que le pasaremos por parámetro, debe ser una lista por que no sabes si entre cada verificación no se ha creado más de un archivo (y entiendo que los quieres imprimir todos). La idea es que luego de invocar esta rutina, tenemos que guardarnos en una variable, la fecha máxima de creación de los archivos devueltos, y la siguiente verificación la haremos de los archivos posteriores a esa fecha.
Aclaraciones:

*

*No es necesario convertir las fechas a otro formato, al estar en UTC (los segundos desde el 1/1/1970) nos sirven para hacer las comparaciones. Si tenemos que mostrarlas habrá que convertirlas.

*Como bien comenta este enlace, hay una imposibilidad de obtener la fecha de creación de un archivo en Linux, lo que hace la rutina creation_date en el caso de Linux, es devolver la fecha de modificación.

*No agregué la impresión del archivo, eso en teoría, no es tan simple como parece ya que eventualmente podría estar bloqueado por el proceso que lo genera, en cuyo caso hay que hacer otro ciclo intentando abrir de modo exclusivo el archivo y cuando esto sea posible recién ahí mandarlo a imprimir.

Código:
# -*- coding: utf-8 -*-
import os
import platform
from time import sleep
from operator import itemgetter

def creation_date(path_to_file):
    """
    Try to get the date that a file was created, falling back to when it was
    last modified if that isn't possible.
    See http://stackoverflow.com/a/39501288/1709587 for explanation.
    """
    if platform.system() == 'Windows':
        return os.path.getctime(path_to_file)
    else:
        stat = os.stat(path_to_file)
        try:
            return stat.st_birthtime
        except AttributeError:
            # We're probably on Linux. No easy way to get creation dates here,
            # so we'll settle for when its content was last modified.
            return stat.st_mtime

def get_newestfiles(path, last_check_date=0):
  # Armo una lista de todos los archivos del path indicado
  # Guardo el nombre del archivo y la fecha de creación en UTC
  files = []
  for file in os.listdir(path):
    files.append((file,creation_date(os.path.join(path, file))))

  # Retornamos una lista de archivos que han sido creados luego del último control
  return([f for f in files if f[1] > last_check_date])

path = "/etc"
last_check_date = 0
newest_file = []
time_interval = 5

while True:

  newest_file = get_newestfiles(path, last_check_date)
  if newest_file:
      last_check_date = max(newest_file,key=itemgetter(1))[1] # Me quedo con la máxima fecha de los archivos de la lista

  # Recorro los nuevos archivos e imprimo el nombre del mismo
  for f in newest_file:
    print f[0]

  # espero unos segundos para volver a verificar
  sleep( time_interval )


text:
Q: Set color of highchart column according to average or limit value I want to set color of highchart column according to average or limit value. I wrote this script; but the problem is that when I move the mouse over the red column it returned to blue !! someone can tell me what to add on my code so that it remains in red ? Thanks
<script>
$(function () {
            var chart = new Highcharts.Chart({
        chart: {
            renderTo: 'donuts1',
            type: 'column',
            zoomType: 'xy'
        },
        title: {
            text: 'Les données d\'expression du transcrit : <?php echo $id; ?>'
        },
        subtitle: {
                text: document.ontouchstart === undefined ?
                        'Click and drag in the plot area to zoom in' : 'Pinch the chart to zoom in'
        },
        xAxis: {
            categories: ["<?php echo join($tableauLogin, '","') ?>"] ,
            labels: {
                rotation: -45,
                style: {
                    fontSize: '11px',
                    fontFamily: 'Verdana, sans-serif'
                }
            },
        },
        yAxis: {
            title: {
                text: 'Log2(Expression)'
            },
            minorTickInterval: 1,
            min: <?php echo $min-1;?>,
            max: <?php echo $max+1;?>,
            plotLines: [{
            color: '#FF0000',
            width: 2,
            value: <?php echo $mean ;?> ,// Need to set this probably as a var.
            dashStyle: 'ShortDash',
            label: {
                    text: '<?php echo $leg ;?> : <?php echo round($mean,2) ;?>',
                    align: 'right',
                    verticalAlign: 'top',
                    y: -100,
                    x: -10,
                    style: {
                        color: '#FF0000'
                    }}
        }]
        },
        legend: {
            layout: 'vertical',
            align: 'left',
            verticalAlign: 'top',
            x: 50,
            floating: true,
            borderWidth: 1,
            backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
            shadow: true
            },
        series: [{
            name: '<?php echo $name ?>',
            data: [<?php echo join($tableauNote, ',') ?>]
        }]
    },function(chart){

            var max = <?php echo $mean ;?>;

            $.each(chart.series[0].data,function(i,data){

                if(data.y > max)
                    data.graphic.attr({
                        fill:'#FE2E2E'
                    });

            });

        });
});
$('#preview').html(chart.getCSV());
</script>

A: I finally found the solution by my self
I rempalcer this line:
data.graphic.attr({ fill:'#FE2E2E'

by this one
data.graphic.css({ color:'#FE2E2E'


text:
Q: Locating syntax error in Drools I have a drool file where rule 2 is always coming out to true.
rule "R2"
salience 1000

when

((residence status = "US Citizen") || ((residence status = "Lawfully-entered Alien") and (residence duration >= 5))) and (fpl <= 133)
then

Add to Programs List "3"
end

the value of
residence status is US Citizen
residence status is null
residence duration is 0
fpl is 278.77

Why it is going into it always though for specified value the condition is false .
Kindly find the all files.
package com.eligibility.service;

import com.platform.enrollment.domain.BasicInfo;
import com.platform.enrollment.domain.FamilyMember;
global java.util.List prog_id_list;
global java.lang.Double fpl;

[condition][] and=and
[condition][] or=or

[condition][]residence status \= "{value}"=FamilyMember(basicInfo.citizenshipStatus == "{value}")
[condition][]residence duration >\= {value}=FamilyMember(basicInfo.permanentResidenceDuration >= {value})
[condition][]job status \= "{value}"=FamilyMember(basicInfo.jobStatus == "{value}")
[condition][]large business status \= "{value}"=FamilyMember(basicInfo.largeBusinessStatus == "{value}")
[condition][]false=eval(false)
[condition][]true=eval(true)
[condition][]age \= {value}=FamilyMember(basicInfo.getAge=={value})
[condition][]age < {value}=FamilyMember(basicInfo.getAge<{value})
[condition][]age > {value}=FamilyMember(basicInfo.getAge>{value})
[condition][]age <\= {value}=FamilyMember(basicInfo.getAge<={value})
[condition][]age >\= {value}=FamilyMember(basicInfo.getAge>={value})

[condition][]fpl \= {value}=eval(fpl=={value})
[condition][]fpl < {value}=eval(fpl<{value})
[condition][]fpl > {value}=eval(fpl>{value})
[condition][]fpl <\= {value}=eval(fpl<={value})
[condition][]fpl >\= {value}=eval(fpl>={value})

[condition][]gender \= "{value}"=FamilyMember(basicInfo.gender == "{value}")

[condition][]pregnant \= true=Applicant(eval(pregnant))
[condition][]pregnant \= false=Applicant(eval(!pregnant))

[condition][]Family member age greater than or equal to 60 \= true=eval(any_member_greater_than_equal_to_60)
[condition][]Family member age greater than or equal to 60 \= false=eval(!any_member_greater_than_equal_to_60)

[condition][]job status \= "{value}"=Applicant(eval(job_status.contains("{value}")))

[condition][]large business status \= "{value}"=Applicant(eval(large_business_status.contains("{value}")))
[condition][]employer benefits \= "{value}"=Applicant(eval(large_business_status.contains("{value}")))

[condition][]spouse \= true=eval(spouse)
[condition][]spouse \= false=eval(!spouse)

[condition][]total assets \= {value}=eval(total_assets=={value})
[condition][]total assets < {value}=eval(total_assets<{value})
[condition][]total assets > {value}=eval(total_assets>{value})
[condition][]total assets <\= {value}=eval(total_assets<={value})
[condition][]total assets >\= {value}=eval(total_assets>={value})

[condition][] Question with code "{code}" has answer "{answer}"=Question(code=="{code}"&& eval(answer.contains("{answer}")))

[consequence][]Add to Programs List {id}=prog_id_list.add({id});

rule "R0"
salience 1000

when

(age <= 0) and ((residence status = "US Citizen") || (residence status = "Lawfully-entered Alien")) and (fpl <= 200)
then

Add to Programs List "1"
end

rule "R1"
salience 1000

when

((residence status = "US Citizen") || (residence status = "Lawfully-entered Alien")) and (fpl >= 400)
then

Add to Programs List "2"
end

rule "R2"
salience 1000

when

((residence status = "US Citizen") || ((residence status = "Lawfully-entered Alien") and (residence duration >= 5))) and (fpl <= 133)
then

Add to Programs List "3"
end

rule "R3"
salience 1000

when

((residence status = "US Citizen") || (residence status = "Lawfully-entered Alien")) and (fpl > 133) and (fpl < 400)
then

Add to Programs List "4"
end

Can anybody help me why it is enetring is list3 though data as provided above is not making it valid

A: It could also be helpful to look at the generated java class for your rule and see what the issue might be.
Use:
-Ddrools.dump.dir=
to set path for the generated code.
It could also be helpful to set a rules listener and look at the fact insertions updates and rules firing sequence.
Also you could try to break the problematic rule into two rules without DSL as follows for debug purpose:
when
FamilyMember(basicInfo.citizenshipStatus == "US Citizen")
Fact(eval(fpl <= 133))

when
FamilyMember(basicInfo.citizenshipStatus == "Lawfully-entered Alien")
FamilyMember(basicInfo.permanentResidenceDuration >= 5)
Fact(eval(fpl <= 133))

Hope this helps.


text:
Q: Как передать Set готовый Set? Вот у List допустим есть такой метод
List <String> arrayList = new ArrayList<>(Arrays.asList("", "", ""));

В этом случае Arrays.asList("", "", "") передает сразу список...
Вот вопрос в том, есть ли у Set, что то аналогичное?

A: Пожалуйста:
final Set<String> set = new HashSet<>(Arrays.asList("","",""));


text:
Q: Python tuple data byte to string easy way? I'm using socket, struct for receive and unpack the received bytes message via tcp/ip protocol, I'm getting tuple which contains numeric data as well as bytes in the defined order as per contract.
The example data as below...
Example:
receive buffer data from tcp ip
buffer = sock.recv(61)

Unpack the bytes into predefined struct format
tup_data = struct.unpack("<lll8s17sh22s", buffer)

tup_data
(61,12000,4000,b'msg\x00\x00\x00\x00\x00',b'anther
msg\x00\x00\x00\x00\x00\x00\x00',4,b'yet another
msg\x00\x00\x00\x00\x00\x00\x00')

since the data is highly streaming and execution time is matter... I don't want to load the cpu by using any looping and isinstance() method.
Since the location of bytes are defined, so I'm currently using as
processed_data = (*tup_data[:3],
                   tup_data[3].strip(b"\x00").decode(),
                   tup_data[4].strip(b"\x00").decode(),
                   tup_data[5],
                   tup_data[6].strip(b"\x00").decode())

processed_data
(61,12000,4000,"msg","anther msg",4,"yet another msg")

Is there any magic way to convert bytes into required string at one shot as the location of bytes are known...??

A: Since you're using struct.unpack for unpacking your buffer and due to the format-characters chart you can't get string format as your output. Therefore you should either strip the extra \x00 at the source or just use a generator comprehension as following to reformat the items that are instances of bytes.
In [12]: tuple(i.strip(b'\x00').decode() if isinstance(i, bytes) else i for i in t)
Out[12]: (61, 12000, 4000, 'msg', 'anther msg', 4, 'yet another msg')


text:
Q: How to free up space of dvd drive I'm trying to install kali Linux on VMWare. But I click on iso file of kali Linux. Now when I open a file explorer I see that there is new DVD drive is shown with name "DVD Drive(F) Install Kali Linux" with space "0byte free of 379MB".
Now my question is that, does this new created DVD drive takes 379 MB of memory from my hard disk ? If yes then how should I delete this and recover this memory to my hard disk back. If not then where does this 379 MB of memory came from ?
Please tell the answer by keeping in mind I'm installing OS for the first time.

A: To clarify things 379MB is the size of your Kali Linux (netinstall) ISO file, you don't have to free memory or delete anything, you just need to unmount (or eject) the virtual DVD on Windows side. This "memory", as you said, came from that...
If you double-click on any *.iso file on Windows, this will "mount" that virtual DVD (not virtual as virtual machine I mean), but this is not absolutely needed to get your job done.
To install a new VM (Kali) on VMWare you should create a new virtual machine inside that environment and attach the ISO file, then create a virtual HD and boot your newly created VM from ISO to complete the installation process. Netinstall ISOs needs an active internet connection to download packages during install stage, no differences between physical and virtual machines for that. So make sure you provided that too. Bye.


text:
Q: Does DataTable implement IListSource? The documentation (and intellisense) states very clearly that DataTable implements IListSource. But then why doesn't DataTable have a getList() method, which is (the main) part of the IListView interface?

A: DataTable uses Explicit Interface Implementation to implement IListSource.
You can still use the method via:
 IListSource listSource = (IListSource)dataTable;
 IList list = listSource.GetList();


text:
Q: MVC get variable from url (routing) in view? In my routing I have
routes.MapRoute(
    name: "ctrl",
    url: "ctrl/{target_name}",
    defaults: new { controller = "ctrl", action = "TheAction" }
);

How do I access target_name? I tried ViewBag.target_name, I Googled and found many pages say RouteData.Values but I get a compile error
CS0120: An object reference is required for the non-static field, method, or property 'System.Web.Routing.RouteData.Values.get'

So I end up doing
public ActionResult TheAction(string target_name) { ViewBag.target_name = target_name; return View(); }

which appears to be very wrong (because it seems stupid)
How do I access target_name in my view?

A: If you want to get at the RouteData in your view you need to get it through the ViewContext.
ViewContext.RouteData.Values["target_name"]


text:
Q: Power BI calculate workdays in month I have a lot to learn of Power BI and I am currently stuck with a column I need to add in my Calendar table.
I have to calculate a workday column that should flag each day of the month with it's workday number (from 1 to the maximum number of working days for that month).
I was able to find a solution online with RANKX (I have a column, NonWorkday that flags with 1 for all days that are either weekends or holidays) but it's not complete:
Workday =
VAR CurrentMonth = Calendar[MonthYear]
VAR MonthTable = FILTER( ALL( Calendar ), Calendar[NonWorkDay] = 0 && Calendar[MonthYear] = CurrentMonth )
RETURN
IF( Calendar[NonWorkDay] = 1, BLANK(), RANKX(MonthTable, CALCULATE(AVERAGE(Calendar[DayofMonth])), ,ASC))

What I'm missing is that, for weekends and holidays I don't want blank, I want it to have the same workday number as the previous workday and if the month starts with a non-working day, that will be 0. An example image below:

It would be great if anyone can help me with a solution or point me in the right direction, either DAX or M query.
Thank you!
LE: Adding MVE code, as per @Marco_CH request:
    let
        Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("bdJBDoMwDATAv+RciXgTSPIW1P9/oxTbar34wGUQCWvveRbZZEMFyqvI9dTyfp0FGbYMe4b7D+v94otHRNw4IrYbZzxTcWUoNVWJp3ZVRN1VW9RDtUcdqnu8zfRIlZJN1Rl1qS6aly2hEuscQelEJwnamXPLmQKKTg68OR0daHeiswNlFB0eKKToREAbNG41Z05pA9zwbBYiwtqKZ7N6xG5txf8PdGtrgiN+vltb8SzQiji8rUg6IfGq6W3NtKVKsZa3FUmr5CAW7yuSVgmls57Iiv/h9ak589a6NxZZqyijM4X0snHK4Y2Nh0xvbMqc8prg+wM=", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Date = _t, NonWorkDay = _t, WantedWorkday = _t]),
        #"Changed Type" = Table.TransformColumnTypes(Source,{{"Date", type date}, {"NonWorkDay", Int64.Type}, {"WantedWorkday", Int64.Type}})
    in
        #"Changed Type"

LE2: My final calculation based on the answered provided by @msta42a:
WD =
var day ='Calendar'[Date]
VAR CurrentMonth = Calendar[MonthYear]
return
CALCULATE( COUNTROWS('Calendar'), FILTER('Calendar', Calendar[MonthYear] = CurrentMonth && 'Calendar'[Date] <= day && 'Calendar'[NonWorkDay] <> 1)) +0

Results:

A: You can calculate this like "running count/total" here my example (in your code you should add a clause for month/year)
Workday =
var day ='Calend'[Date]
return
CALCULATE( COUNTROWS('Calend'), FILTER('Calend',  'Calend'[Date] <= day && 'Calend'[Weekend]="wd" && Calend[Nonworking] <> 0)) +0


text:
Q: Program is not exiting loop even thought it appears it knows to I am making a guessing game where the user inputs the top number and the computer selects a number between 1 and the number that the user input. After the correct number is guessed, it is supposed to leave the do-while it is in and move on to the toString, but does not.
Here is an example:
Guessing Game - How many numbers? 10
Enter a number between 1 and 10: 1
Try again.

Enter a number between 1 and 10: 2
Try again.

Enter a number between 1 and 10: 3
Try again.

Enter a number between 1 and 10: 4
Enter a number between 1 and 10:

You can see that it doesn't say "Try again," but yet asked for another guess.
Here is my program
import java.util.Scanner;
import static java.lang.System.*;

public class GuessingGame
{
    public int upperBound;
    int guesscount = 0;

    public GuessingGame(int stop)
    {
        upperBound = stop;
    }

    public int playGame()
    {
        boolean guesscorrectly = false;
        Scanner kb = new Scanner(System.in);
        int correctNum = (int) ((Math.random()*upperBound) +1);
        do{
            System.out.print("Enter a number between 1 and " + upperBound + ": ");
            int guess = kb.nextInt();
            if(guess==correctNum){
                guesscount++;
                guesscorrectly = true;
            }
            else{
                guesscount++;
                System.out.println("Try again.\n");
            }
        }while(guesscorrectly!=true);
        return correctNum;
    }

    public String toString()
    {
        return "You correctly guessed " + playGame() + "! It took you " + guesscount + " guesses.";
    }
}

And then here is the main
import java.util.Scanner;
import static java.lang.System.*;

public class GuessRunner
{
    public static void main(String args[])
    {
        Scanner kb = new Scanner(System.in);
        System.out.print("Guessing Game - How many numbers? ");
        int upperBound = kb.nextInt();
        GuessingGame test = new GuessingGame(upperBound);
        test.playGame();
        System.out.println(test);
    }
}

A: Your calling playGame() in your toString() method. You shouldn't do that or it will start the game over...

A: Note that whenever you do playGame() in your code, it will call the playGame() method. This means that the method will be executed inside of toString(). You have three ways to fix this.

*

*Remove the line that calls test.playGame() in main(). Then move the System.out.println() statement from toString() to main(), changing playGame() to test.playGame().

*Capture the return value of playGame() by assigning it to a variable. Then you can printing that variable's value in main() rather than overriding toString().

*Instead of returning a value from playGame(), you can create a member field which stores the value. Then toString() uses the value of the member field instead of calling playGame().


text:
Q: Collapsing several "required field missing" errors down to one line in the "stripes:errors" box I realize this is kind of "Stripes 101", but I guess I skipped that class.
I'd like to use the code that drops the "error" class into the field
tag class strings as the primary way to indicate missing required
fields. I'd then like to show a single error message along with any
other errors (like fields supplied with improper values).
Thus, the error info on the page might look like:

Sorry for the trouble, but:

 1. Please supply values for all indicated required fields.
 2. Please supply a numeric value for Zip Code.

etc.
I suppose I could go through the validation errors, look for ones for
fields where the value is empty, and make the assumption that those
were the required field errors.  However, if I take those errors out
of the set, then I suspect that the page will no longer be able to
mark the erroneously-missing fields with the "error" class.
This seems like something likely to be pretty easy, but I can't find
any specific examples. Maybe I can do it all in the .jsp code; I'll start looking into that.

A: The DefaultActionBeanPropertyBinder adds an instance of ScopedLocalizableError with the default scope value of "validation.required" when a required field is missing.
So you coult probably write a tag similar to the stripes errors tag, but which collapes all the instances of ScopedLocalizableError having a default scope of "validation.required" to a single error message.


text:
Q: Change the div's in another html page still learning some javascript here, got done other things but now the final and most important part of it.
I have two html pages - one of which uses javascript to dynamically add text-fields (and to remove them of course) (genmain.html) and the other one where the text field input should go(table.html).
So i have already created a function to retrieve the array of values.
function getElementArray(divName){
   var names = document.getElementsByName("namefield");
}

The variable names is an array and it has all the values from fields.
The problem is I would like to set these values from array to the values of another div on the page. After some searching i understood that it could be done with 'id'-s but i'm not that sure and don't completely understand how.
Let's say i have a lot of div's on another page (table.html) but some of them have id="MAIN". I would like to change the value inside of the div
For example

THIS PART I WANT TO CHANGE

Javascript is not part of my school system and i've done CodeAcademy tutorials and that's the most i've got about this, I hope you guys can help with my issue.

A:
The variable names is an array and it has all the values from fields.

function getElementArray(divName){
   var names = document.getElementsByName("namefield");
}

Nope, you've only got reference to the elements here. You've not got the value yet.
You can get the values by iterating through the names Nodelist array and use names[i].value

The problem is I would like to set these values from array to the
  values of another div on the page

If it's going to be in same page, then use innerHTML or textContent property of the DOM to assign the value.
document.getElementById("MAIN").textContent= names[1].value;

Just for demo purpose am using names[1] here so it will load the second input value.

Let's say i have a lot of div's on another page (table.html) but some
  of them have id="MAIN". I would like to change the value inside of the
  div

Once you move to another page, the javascript state will be lost. So you wont have access to names inside that page.
Either you must store the values into localStorage and retrieve in next page.
Else add the values to query string of your URL and retrive it there.

Edit: Update based on comments

Let us assume you have var names = document.getElementsByName("namefield"); so to store the values inside localStorage.
var myValues = [],
    names = document.getElementsByName("namefield");
    for(var i = 0; i < names.length; i++) {
        myValues.push(names[i].value);
    }
    localStorage.myValues = JSON.stringify(myValues);

Now if your next page, Iinside window.onload event:
   window.onload = function() {
       var myValues = localStorage.getItem("myValues") ? JSON.parse(localStorage.getItem("myValues")) : [],
           divElements = document.querySelectorAll("#MAIN");
       for(var i =0; i < myValues.length; i++) {
           divElements[i].textContent = myValues[i];
       }
   }

A: If you want to set or change the contents of an element, you can use the innerHTML property.
So in your case, document.getElementById("MAIN").innerHTML = "Whatever you want";
For the record, names in your example technically isn't an array, but a NodeList. See https://developer.mozilla.org/en/docs/Web/API/NodeList#Why_is_NodeList_not_an_Array.3F.


text:
Q: Using second derivative to find a bound for the first derivative
Let $f$ be a twice differentiable function on $\left[0,1\right]$ satisfying $f\left(0\right)=f\left(1\right)=0$. Additionally $\left|f''\left(x\right)\right|\leq1$ in $\left(0,1\right)$. Prove that $$\left|f'\left(x\right)\right|\le\frac{1}{2},\quad\forall x\in\left[0,1\right]$$

The hint we were given is to expand into a first order Taylor polynomial at the minimum of $f'$. So I tried doing that:
As $f'$ is differentiable, it is continuous, and attains a minimum at $\left[0,1\right]$. Thus we can denote $x_{0}$ as the minimum, and expending into a Taylor polynomial of the first order around it gives us, for some $c$ between $x$ and $x_0$.
$$T_{x_{0}}\left(x\right)=f\left(x_{0}\right)+f'\left(x_{0}\right)\left(x-x_{0}\right)+\frac{f''\left(c\right)}{2}\left(x-x_{0}\right)^{2}$$
Now at $x=0$ we have
$$T_{x_{0}}\left(0\right)=f\left(x_{0}\right)-x_{0}f'\left(x_{0}\right)+x_{0}^{2}\frac{f''\left(c\right)}{2}=0$$
And at $x=1$ we have $$T_{x_{0}}\left(0\right)=f\left(x_{0}\right)+\left(1-x_{0}\right)f'\left(x_{0}\right)+\left(1-x_{0}\right)^{2}\frac{f''\left(c\right)}{2}=0$$
and I'm pretty much stuck here..
So I tried a different approach using Mean Value Theorem directly, by Rolle's I know the derivative is $0$ somewhere (as $f(0)=f(1)$), suppose at $x_0$, so by mean value theorem $\frac{f'(x)}{x-x_0} =f''(c)\leq1$ for some $c$ and $f'(x)<x-x_0$.
But using this approach as well I'm not sure how to proceed, as this gives me the desired propety only in $1/2$ environment around $x_0$...
Any help?

A: You were on the right track, but, as I suggested, the hint should have been to expand about the point $x_0$ where $|f'(x_0)|$ is a maximum.
Fix any $x_0\in [0,1]$ and, using Taylor's Theorem, write
$$f(x)=f(x_0) + f'(x_0)(x-x_0) + \frac12 f''(c)(x-x_0)^2\quad\text{for some $c$ between $x_0$ and $x$.}$$
Plugging in $x=0$ and $x=1$ respectively, we arrive at
$$f'(x_0) = \frac12\big(f''(c_1)x_0^2 - f''(c_2)(1-x_0)^2\big) \quad\text{for some $c_1$ and $c_2$}.$$
Therefore $|f'(x_0)|\le \dfrac12\big(x_0^2 + (1-x_0)^2\big) \le \dfrac12$, since $x_0\in [0,1]$ is arbitrary.

A: This is an equivalent statement:
Let $g:[0,1] \to \mathbb R$ be a continuous function on $[0,1]$. Assume that $g$ is differentiable on $(0,1)$,
$$
\int_0^1 g(x) dx = 0 \qquad \text{and} \qquad  \forall x \in (0,1) \quad \bigl| g'(x) \bigr| \leq 1. \tag{1}\label{1}
$$
Then $|g(x)| \leq 1/2$ for all $x \in [0,1]$.
Proof. By the Mean value theorem, for all $x,y \in [0,1]$ such that $x \neq y$ there exists $c \in (0,1)$ such that
$$
\frac{g(y) - g(x)}{y-x} = g'(c).
$$
By the second assumption in $\eqref{1}$, for all $x,y \in [0,1]$ such that $x \neq y\ $ we have
$$
\left| \frac{g(y) - g(x)}{y-x} \right| \leq 1.
$$
Consequently, for all $x,y \in [0,1]$ we have
$$
-|y-x| \leq g(y) - g(x) \leq |y-x|.
$$
Integrating the last inequality with respect to $x$ over $[0,1]$ and using the first assumption in $\eqref{1}$, we get
$$
-\int_0^1 |y-x| dx \leq g(y) \leq \int_0^1 |y-x| dx.
$$
Thus, for all $y \in [0,1]$ we have
$$
\bigl| g(y) \bigr| \leq \int_0^1\!\! |y-x| dx =\frac{1}{2}\bigl( y^2 + (1-y)^2 \bigr) = \Bigl(y-\frac{1}{2}\Bigr)^2 + \frac{1}{4} \leq \frac{1}{2}.
$$


text:
Q: Rotated ImageViews overlaps each other I want to add an rotated ImageViews to an VBox. My probelm is that the ImageViews overlaps each other and i have no idea how to solve this. Can anyone help me? That would be cool! Thanks!
My Code for the Rotation:
private ImageView normalizeOrientation(int orientation, ImageView iv){
        switch (orientation){
            case 2:
                iv.setRotationAxis(Rotate.Y_AXIS);
                iv.setRotate(180);
                break;
            case 3:
                iv.setRotate(180);
                break;
            case 4:
                iv.setRotate(180);
                iv.setRotationAxis(Rotate.Y_AXIS);
                iv.setRotate(180);
            case 5:
                iv.setRotate(90);
                iv.setRotationAxis(Rotate.Y_AXIS);
                iv.setRotate(180);
                break;
            case 6:
                iv.setRotate(90);
                break;
            case 7:
                iv.setRotate(270);
                iv.setRotationAxis(Rotate.Y_AXIS);
                iv.setRotate(180);
                break;
            case 8:
                iv.setRotate(270);
                break;
            default:
                break;
        }
        return iv;
    }

After adding rotated images to a VBox this happens:
Overlapping Images in a VBox


text:
Q: Simple Linear Regression: $Y = \beta_0 + \beta_1 X$ BUT $y_i = \beta_0 + \beta_1 x_i + \epsilon$ I am studying simple linear regression for the very first time, and I'm having a little trouble understanding something. If someone can clarify this for me and perhaps lead the explanation to a little introduction/motivation behind simple linear models that would be really helpful.
What I've understood is that we have a random variable $Y$ we think is linearly related to a random variable $X$.
But then I've seen the "model" that we use is $Y = \beta_0 + \beta_1 X + \epsilon $. If our assumption was that $X$ and $Y$ are linear, then why did we add an error term? Aren't they exactly linearly related, under our assumption?
I would understand that $y_i = \beta_0 + \beta_1 x_i + \epsilon_i $ was used, perhaps indicating that "While $X$ and $Y$ are perfectly linearly correlated, when we are observing values we have measurement errors and other factors affect this from being a perfect observation.
I thought that maybe our assumption is not that $Y$ and $X$ are exactly linear transforms of each other, but rather just "correlated". If this is a more accurate explanation of our assumption, then the epsilon would make more sense.

A: The more correct "model" is that $\mathbb{E}(Y|X) = \beta_0 + \beta_1 X$. Since $Y$ is a random variable, there's no way to know for sure what $Y$ will be. That's why there's a need for the (conditional) expectation.

A:
If our assumption was that X and Y are linear, then why did we add an error term? Aren't they exactly linearly related, under our assumption?

Linear here implies linear plus noise.


text:
Q: jQuery-UI dialog $.ajax POST fails due to jQuery "Could not convert JavaScript argument" I'm using the jQuery-UI dialog and I'm trying to send the data in my dialog form via AJAX upon clicking the dialog's send button. Both the $('').submit(), $('').load(url) methods "work" for me in that the dialog form submits/the url is loaded. However, as i try to add some post data to the load method, like some form input, I get the error message in the firebug console stating that the jQuery library "Could not convert JavaScript argument".
Here's my code that doesn't work yet:
$(function(){
  $( "#form" ).dialog({
    buttons: {
      "Send": function() {
        var url = "/messages/add";
        var message=$('#message').val();

        $('#main_content').load(url, { message:message } );
        $( this ).dialog( "close" );
      }
    }
  });

  $( "#open_dialog_button" ).click(function() {
    $( "#form" ).dialog( "open" );
  });
});

The problem seems to me to be with the "message" since the "url" will load into the "main_content" Div if I don't include the {message:message} parameter.
Any advice someone might have to help submit this post data I would greatly appreciate,

A: I solved the problem, i had misidentified one of my other key:value pairs I didn't mention (besides {message:message}), now it works!


text:
Q: BehaviorSubject functionality for item subclass I have a Subject that I use as an event bus. This bus emits multiple items, all of a common type:
static class EventBus {
    private final Subject<Event> subject = BehaviorSubject.create();

    /**
     * @param event Event to publish to the subject
     */
    void publish(@NonNull Event event) {
        this.subject.onNext(event);
    }

    /**
     * Listen to events of a specific class
     *
     * @param eventClass class of event to listen for
     * @param <T>        generic type
     * @return Observable
     */
    <T extends Event> Observable<T> listenForEvents(@NonNull Class<T> eventClass) {
        return this.subject
                .serialize()
                .filter(eventClass::isInstance)
                .cast(eventClass);
    }
}

abstract static class Event {
    int id;

    public Event(int id) {
        this.id = id;
    }
}

final class EventA extends Event {
    EventA(int id) {
        super(id);
    }
}

final class EventB extends Event {
    EventB(int id) {
        super(id);
    }
}

Things that want to listen for specific events can call listenForEvents and pass in the class they want to listen for.
However I want a BehaviorSubject behavior for each class type. An example will illustrate this:
void main() {
    EventBus eventBus = new EventBus();

    // publish some A's
    eventBus.publish(new EventA(1));
    eventBus.publish(new EventA(2));
    eventBus.publish(new EventA(3));

    // publish a B
    eventBus.publish(new EventB(4));

    eventBus.listenForEvents(EventA.class)
            .subscribe(eventA -> {
                // 1. I want to receive EventA(3) but I won't receive
                // anything because last value in the BehaviorSubject is an EventB
                Log.d("TAG", String.valueOf(eventA.id));
            });

    eventBus.publish(new EventA(5));
    // 2. It's only if I put another EventA into the subject
    // after I subscribe that I'll seen anything emitted.
}

I have several possible solutions but none of them seem like good ones =)
1.) multiple BehaviorSubjects, one for each event type; these can be lazy created
2.) track "most recent event of type X" outside observable stream
3.) Convert BehaviorSubject with ReplaySubject and use .debounce(10, TimeUnit.MILLISECONDS) and assume that replayed items will be emitted quickly and new items will not be published quickly
private final Subject<Event> subject = ReplaySubject.create();

<T extends Event> Observable<T> listenForEvents(@NonNull Class<T> eventClass) {
    return this.subject
            .serialize()
            .filter(eventClass::isInstance)
            .cast(eventClass)
            .debounce(10, TimeUnit.MILLISECONDS);
}

Is there a clean way to do this with existing rx operators?


text:
Q: How to create an App with a lot of media without getting memory problems? i should create app for tablets, which will be shows magazines, every magazine will be have about 60-70 pages, every page has cover as image ( weight about 400kB - 1mb, height over 1200px and width = screen size ), and every page has small cover ( about 20kB ), some pages have mp3, mov and other files, which I must show on this page. When i start first time app, i must download about 200mb, now but in future will be more files, magazines, and pages ;(
When I open magazine, i must load about 70 pages and when i slide screen, pages will be move right - left. When I click on screen, I must show gallery view with small images cover.
Im wondering, that it will be waste of time to create this app, any ideas how i could show images and other files whithout overload memory ? Have You any experience in app like this ?

A: Think about it: will any user of your app ever see more than one page at once?
To put it even further, when was the last time you did actually read 70 pages simultaneously?
The key to implementing such an app is clever loading and unloading data as it is needed. There are quite some strategies to achieve this, one very simple would be to keep only a few pages (the last, the current and maybe the next two) in memory at a time. This makes switching pages seamless and keeps your memory footprint low. It can be quite hard to figure out the right balance between memory use and responsiveness, but well, thats what it takes. Good luck.

A: Your application can contain any number of information within itself, but to display correctly you shouldn't immediately load all media files. Currently displayed in only the informations you need. Many standard controls initially work as well (table with reused cells, for example). Small pictures can be cached in memory, when switching between pages removes all  old information and upload a new one.
Just start it and success won't keep waiting.


text:
Q: Can I execute a shell script when restarting (starting) apache webserver I have an application with some cacheing backend and I want to clear the cacheing whenever the  webserver is been restarted.
Is there a apache configuration directive or any other way to execute a shell script upon webserver (re)start?
Thanks,
Phil
Adding some more information, as asked by some answers already:

*

*Base system is ofc linux based, in this exact situation: CentOs

*Modifying the startup script is unfortunately no option as pointed out by one of the comments already, due to it beeing not configuration file within the respective RPM packages and therefor beeing replaced by updates. Also I think modifying the startup script would be a bad thing in general

*I see, that actually linking both "restarting the webserver" and "clearing my app cache" is not exactly what should be tied together. I will consider other alternatives

*My situation is as follows: I can define how the virtual host config looks like, but I can not define how the rest of the servers configuration looks like.

*The application is actually PHP based (and runs on the symfony framework). Symfony pre-compiles alot of stuff into dynamic php files from what it finds in the static configuration files. We deploy our apps via RPM and after deployment, an webserver restart is actually initiated already, so I thought it might make sense to tie the cache-cleanup to it. But I think after getting all your feedback, it looks like it is better to put the cache cleanup process into the installation process itself.

A: You can modify Startup script for the Apache Web Server in /etc/init.d/httpd and write your own syntax inside it.
chattr +i /etc/init.d/httpd

A: You haven't provided a lot of detail here, so it's hard to give a concrete answer, but I would suggest that your best option is to write a script which handles restarting apache, and clearing your cache.  It would look something like this:
#!/bin/sh

# restart apache
/etc/init.d/httpd graceful

# whatever needs to be done to clear cache
rm -rf /my/cache/dir

Ramy suggests modifying the system startup script for Apache -- this is a bad idea! If and when you update Apache on your server, there is a good chance that your change will be lost.
Dirk suggests that what you are trying to do is probably misguided, and I think he's right.  You haven't told us what platform you are running, but I can think of few situations where restarting your webserver and clearing a cache actually need to happen together.

A: If you have (root) access to the server you could do this by shell scripts but I would consider if it is the best way of cache management to rely on apache restarts.


text:
Q: Enable button without exposing model properties I am using the MVVM pattern with MVVMHelpers.
I already made the login form, but I was trying to enable the button only if the user has typed his username and password.
public ICommand LoginCommand { get; set; }

    private string _Username;
    public string Username {
        get { return _Username; }
        set {
            if (_Username != value) {
                _Username = value;
                RaisePropertyChanged();
                Activate();
            }
        }
    }

    private string _Password;
    public string Password {
        get { return _Password; }
        set {
            if (_Password != value) {
                _Password = value;
                RaisePropertyChanged();
                Activate();
            }
        }
    }

    private bool _IsEnabled;
    public bool IsEnabled {
        get { return _IsEnabled; }
        set {
            if (_IsEnabled != value) {
                _IsEnabled = value;
                RaisePropertyChanged();
            }
        }
    }

    public bool Activate() {
        if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password)) {
            IsEnabled = true;
            return true;
        }

        return false;

    }

    public LoginVM() {
        LoginCommand = new Command(() => {
            MessageBox.Show("LogeIn");
        });
    }
}

As you can see, I achieved this, by exposing the properties of the class to my VM.
I was wondering if there is a way to do this without exposing it?
https://github.com/eduardoagr?tab=repositories

A: You could achieve this in XAML only, by using a multi-binding on the IsEnabled property on the Sign In Button to the user name and the password TextBoxes along with a custom value converter that converts the bound strings to a bool that indicates whether they are empty or not.
However, in this case that is not possible, since you should avoid using Command and IsEnabled at the same time, as it can lead to strange behavior. Commands offer a mechanism to determine, if an action is possible or not and will in turn set the IsEnabled state.

A command can indicate whether an action is possible by implementing the CanExecute method. A button can subscribe to the CanExecuteChanged event and be disabled if CanExecute returns false or be enabled if CanExecute returns true.

As you can see, setting both a Command and IsEnabled will interfere with each other. Although it might work, if you specify IsEnabled before Command in XAML, this is a brittle solution, so choose one, in this case favor Command with its built in mechanism.
The good news is that instead of doing this in XAML, you can achieve the same in your view model and save yourself some code by passing a CanExecute delegate to your LoginCommand as follows.
public class LoginVM : ViewModelBase {

    public Command LoginCommand { get; }

    private string _Username;
    public string Username {
        get { return _Username; }
        set {
            if (_Username != value) {
                _Username = value;
                RaisePropertyChanged();
                LoginCommand.RaiseCanExecuteChanged();
            }
        }
    }

    private string _Password;
    public string Password {
        get { return _Password; }
        set {
            if (_Password != value) {
                _Password = value;
                RaisePropertyChanged();
                LoginCommand.RaiseCanExecuteChanged();
            }
        }
    }

    public LoginVM() {
        LoginCommand = new Command(
           () => MessageBox.Show("Log IN"),
           () => !string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password));
    }
}

The second parameter for your command is a method that determines, whether the command can execute and if it returns true, the control that binds the command will automatically be enabled or disabled when returning false. Using this approach, you do not need the IsEnabled property at all and you can remove it from XAML.
The only other thing to note here is that you have to tell the LoginCommand, when it needs to reevaluate the CanExecute delegate by calling its RaiseCanExecuteChanged method (defined in  the Command class). In order to access it, change the type of the property from ICommand to Command or define a separate backing field for it. In this case, it needs to be reevaluated each time either Username or Password changes, so put it in their setters.
At the moment, the TextBoxes for the user name and password update the view model properties only when losing focus (e.g. clicking outside of it or another control). If you want the Sign In button to react on each keystroke, change the UpdateSourceTrigger to PropertyChanged.
<inputLayout:SfTextInputLayout x:Name="sfTextInputLayout"
                               Hint="Username"
                               Margin="20,20,20,0">
    <TextBox Foreground="BlanchedAlmond"
             Text="{Binding Username, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</inputLayout:SfTextInputLayout>
<controls:CustomPasswordBox Password="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />


text:
Q: Load javascript animation ONLY when entire site (images) loaded I'm building this hotsite that relies heavily on 'heavy' images and animations.
It has some "Curtains" covering all the site, then i want to open these curtains (animate, already coded it), but only when all my site (specially images) is loaded.
Would also like to create a simple loader (no progress at all, just say "loading");
UPDATE:
$.ready(function() {
            $("#loading").fadeOut();
            $(".leftcurtain").stop().animate({ width: '374px', left: '-60px' }, 6200);
            $(".rightcurtain").stop().animate({ width: '374px', right: '-60px' }, 6200);

            $(".leftback").stop().animate({ width: '60px' }, 6500);
            $(".rightback").stop().animate({ width: '60px' }, 6500);

    });

A: Using
window.onload = function() {
    // initialize site
};

Will work. It fires once everything embedded into the site (HTML, CSS, images...) has finished loading.
You will then need to hide your website content while it loads. If you place everything within a DIV, you can toggle the visibility of it with "visibility: hidden". You should not use "display: none", as with some browsers (if I can remember correctly, Opera), they won't load content that has no display value.
You should then be able to place a DIV containing your "Loading" content at the top of the page, then simply either toggle off the display of it, or remove it from the DOM once the page is loaded.

As a side note, you should not use the jQuery.ready() function, as pointed out by RobG, as this only waits for the DOM to load, and not the images.

A: try combining jQuery`s  ready and load
$(document).ready(function()
{
    var images = $('img');
    var loadedImgs = [];
    images.each(function()
    {
        $(this).load(function() //image load callback
        {
            loadedImgs.push('');
        });
        // we are interested only if the images is loaded,
        // so we need to place something in the loadedImgs array;
    });
    var interval = setInterval(function()
    {
        if(loadedImg.length == loadedImgs.length)
        {
            clearInterval(interval);
           //your code here ... images were loaded !!!
        }
    },10);
});

A: Put your handlers inside window.load. This is triggered only after the page is fully loaded, including graphics.
$(window).load()

A: Use Prototype's Event.observe like
Event.observe(window, 'load', function()
    {
        //add javascript script tags to the document here
    }

Function in Event.observe will be called only after all the images in the DOM are loaded.

A: Just use:
window.onload = function(){
    // javascript code will be executed only after the whole dom is loaded
}

With Jquery:
$.ready(function(){
    // some code
});


text:
Q: How to make "test" classes available in the "it" (integration test) configuration? I would like to share a helper trait between my "test" and "it" configurations in SBT, but I have not figured out how.
Here is a minimal example:
project/Build.scala
import sbt._
import Keys._

object MyBuild extends Build {

  val scalaTest = "org.scalatest" %% "scalatest" % "2.0" % "test,it"

  lazy val myProject =
    Project(id = "my-project", base = file("."))
      .configs(IntegrationTest)
      .settings(Defaults.itSettings: _*)
      .settings(
        scalaVersion := "2.10.3",
        libraryDependencies ++= Seq(
          scalaTest
        )
      )
}

src/test/scala/Helpers.scala
trait Helper {
  def help() { println("helping.") }
}

src/test/scala/TestSuite.scala
import org.scalatest._

class TestSuite extends FlatSpec with Matchers with Helper {
  "My code" should "work" in {
    help()
    true should be(true)
  }
}

src/it/scala/ItSuite.scala
import org.scalatest._

class ItSuite extends FlatSpec with Matchers with Helper {
  "My code" should "work" in {
    help()
    true should be(true)
  }
}

then, in sbt, "test" works:
sbt> test
helping.
[info] TestSuite:
[info] My code
[info] - should work
[info] Run completed in 223 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[success] Total time: 0 s, completed Dec 17, 2013 1:54:56 AM

but "it:test" doesn't compile:
sbt> it:test
[info] Compiling 1 Scala source to ./target/scala-2.10/it-classes...
[error] ./src/it/scala/ItSuite.scala:3: not found: type Helper
[error] class ItSuite extends FlatSpec with Matchers with Helper {
[error]                                                   ^
[error] ./src/it/scala/ItSuite.scala:5: not found: value help
[error]     help()
[error]     ^
[error] two errors found
[error] (it:compile) Compilation failed
[error] Total time: 1 s, completed Dec 17, 2013 1:55:00 AM

A: If you want to share code from Test configuration, it's probably better to create a custom test configuration from Test. See Custom test configuration.
Your project/Build.scala becomes:
import sbt._
import Keys._

object MyBuild extends Build {
  lazy val FunTest = config("fun") extend(Test)

  val scalaTest = "org.scalatest" %% "scalatest" % "2.0" % "test"

  lazy val myProject =
    Project(id = "my-project", base = file("."))
      .configs(FunTest)
      .settings(inConfig(FunTest)(Defaults.testSettings) : _*)
      .settings(
        scalaVersion := "2.10.3",
        libraryDependencies ++= Seq(
          scalaTest
        )
      )
}

Also rename src/it/ to src/fun/. Now fun:test works:
> fun:test
helping.
[info] ItSuite:
[info] My code
[info] - should work
[info] Run completed in 245 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[success] Total time: 1 s, completed Dec 17, 2013 8:43:17 AM

A: You can redefine the IntegrationTest Configuration in your project to extend the Test configuration instead of the Runtime Configuration (the default). This will make everything in your test configuration available to your IntegrationTest configuration.
import sbt._
import Keys._

object MyBuild extends Build {

  val scalaTest = "org.scalatest" %% "scalatest" % "2.0" % "test,it"

  lazy val IntegrationTest = config("it") extend(Test)

  lazy val myProject =
    Project(id = "my-project", base = file("."))
      .configs(IntegrationTest)
      .settings(Defaults.itSettings: _*)
      .settings(
        scalaVersion := "2.10.3",
        libraryDependencies ++= Seq(
          scalaTest
        )
      )
}


text:
Q: Simplify launching an EC2 instance with a given configuration Is there any way to create a link or "saved profile" for launching an EC2 instance with a given configuration?
I'm aware of the mechanism where you can create a link to launch a given AMI, i.e.  http://console.aws.amazon.com/ec2/home?region=us-east-1#launchAmi=ami-XXXXXX.  However, there are still a lot of configuration steps left (instance type, security group, etc).
Is there anyway to automate this process, in such a way that it can be launched by an arbitrary Amazon account?

A: You should look into AWS CloudFormation.
The idea is that you create a JSON "template" document that describes the resources (EC2 instance, EBS volumnes, security groups, RDS services, etc) for a given "stack". The JSON document can be more-or-less independent of a specific account. You can also specify configuration prompts (which region to launch in, etc) to collect additional information from whomever is actually launching the stack.
From the AWS CloudFormation page:

Create additional stacks (if needed) by simply using existing
  templates you've created, choosing from one of our sample templates,
  or creating a new one from scratch. Since templates are text files
  that can be created and managed outside of CloudFormation, you can
  share them easily through email, source control repositories, or
  services such as Amazon S3.


text:
Q: How does intent parameter insertion work based on entity type? I am playing around with Dialogflow ES and learning by creating a simple chatbot that takes food orders. I am doing the bot in Hungarian (which is not officially supported by Dialogflow, but based on the various tutorials I read so far, it should not be an issue). I have created a custom entity type that contains foods:

I have picked the Fuzzy matching, because Hungarian is a language that has e.g. accusative case-endings.

*

*Pizza in Hungarian: pizza (so the same as in English)

*"I want a pizza" in Hungarian: "Szeretnék egy pizzát!" (notice the t letter at the end, which is the accusative case-ending).

*"This is a pizza" in Hungarian: "Ez egy pizza." (notice that there is no t letter here, because it's not an accusative case)

See here for more details: http://www.hungarianreference.com/Nouns/-t-accusative.aspx
I have the following intents:

I set the custom entity for each of them.
And now here comes the strange part (at least the part that I don't understand): for some reason, in some case, the original form of the paramter is inserted in the response (which is "Tessék! Itt egy $entity-foods" -- "Here you go. Here is a $entity-foods."), and in other cases, the written form (that the chatbot user writes) is inserted. So e.g. even if the end user makes a typo, that wrongly written form is used instead of the original. See the below examples:

*

*The "pizza" is mispelled as "piza". It's recognized and the original entity type form (pizza) is included in the response, even though I did not specify the $entity-foods.original in the parameters.

*The accusitive version is used in the utterance ("pizzát"). It's also recognized, but not the entity type version (pizza) is included in the response, but the accusitive form ("pizzát")

Question: why is this like this? I would have at expected that the response will be consistent, e.g. the same form (either what is written by the user or what the custom entity has).

A: Both your use cases with your current setup are working as intended according to the documentation with regards to spell correction in Fuzzy Matching:

When end-user input could be considered a misspelling of an entity
synonym, the associated entity may be matched. For example, if you
define a synonym as "lumber", and the end-user input is "number", the
associated entity may be matched.

For your 1st use case:
Input-> kérek egy piza
Agent response -> Tessék! Itt egy pizza

'piza' was matched and auto corrected to 'pizza' which means spell correction worked.
For your 2nd use case:
Input -> kérek egy pizzát
Agent response -> Tessék! Itt egy pizzát

Fuzzy matching feature spell correction did not work and it returned the original user input (pizzát).


text:
Q: In the Imager Portfolio series why doesn't Rhenn paint by Imaging? Renn starts out as a painter apprentice. It's during these years that he starts to realize his abilities. In fact one sign is that he is trying to get the right shade of green for eyes in a portrait, that is called Imager's Green because only Imagers can make it, and suddenly the portrait has the right color. Later on he paints portraits of the Masters and even draws quick sketches of suspects when he is a patroller. The portraits take weeks or months to finish. So why doesn't he just Image the portraits?
He is shown to be a very strong and talented Imager, in later books it's shown how strong, but he never once seems to grasp that he could just Image a painting. Following the rules of the book it wouldn't even be taxing if he laid out all of the supplies the same as if he was painting it himself.

A: Good question.
As you mentioned, he uses it for small, specific adjustments to his paintings.
Don't forget that imaging does create from nothing, it takes from the surrounding environment and uses those substances. Changing the tint of a small amount of paint requires trivial matter and effort - trying to image an entire painting at once would be difficult:

*

*Details - it would be extremely difficult to hold every detail of a complicated painting in your mind at once - it would probably turn out blurry and undetailed. When imagers first try to image coins, the coins often come out "dodgy"

*Effort - different substances and size of imaging take more effort - sometimes exponentially. One imager states that he was sick in bed for a week and nearly died after imaging a single gold coin.

*Materials - the materials for the painting would still need to come from somewhere in the surrounding environment. He would still need to setup the components before he could image the painting.

Also, the idea of him being a portraitist is possibly perceived as a partial cover for his real position within the college.
But most importantly, I think he just enjoys doing it.

A: At one point (in the first book, I think) Dichartyn asked Renn if it would be wrong to image a copy of another's painted work and he replies that it wouldn't be possible since there is too much detail in a painting.  Dichartyn is trying to get Renn to see that there is value in what is rare - because it is rare.  Even so, Renn missed that point and zeroed in on the technical impossibility of imaging a good painting with all its many elements.

A: He could perhaps image a portrait, even if it took several sessions doing small portions--but why bother? He's not doing portraits for the money (he's no longer a guild member, so cannot charge for any portrait), but because he enjoys the work--it's a skill he spent nearly 10 years learning--and it does seem to help him develop his ability to observe and analyze closely for imaging.


text:
Q: How can I run a user script before any inline scripts run on a webpage? I want to make a greasemonkey type script for firefox that runs before the scripts on the page.  Greasemonkey scripts run after scripts on the page, so that won't work.  The reason I need this is because I want to edit one of the scripts on the page.  Specifically, I want to delete a script that forces the page to load inside a frame since having the page inside a frame breaks F5 (Pressing F5 makes the page jump back to the front page instead of reloading the current page).  Also, I don't want to load the page through a proxy with AJAX and switching to chrome/opera is not an option either.  I was thinking maybe the Jetpack add-on would work but it seems to only have the same event that greasemonkey uses, DOMContentLoaded.  Any ideas?

A: [edit 2013] Use the page-mod module of the Add-on SDK with contentScriptWhen = start.

older:
Right, only newer Firefox builds (currently 3.7 nighlies, may later be added to 3.6.x) have support for running custom scripts before content-specified scripts. I wrote a prototype Jetpack-SDK module to take advantage of the new notification.
Is it a <script src> or an inline script? In the former case it can be blocked with a content policy (something adblock-like).


text:
Q: Git checkout just a subdirectory Please note: I am not looking for git sparse checkout, nor is this question a duplicate of Is there any way to clone a git repository's sub-directory only?
In git, is it possible to clone or checkout just a subdirectory, into the current directory? In svn, you would do this by extending the URL. For example, instead of checking out http://server/repo you would checkout http://server/repo/subdir
The difference between sparse checkout and checking out only a subdir, is that a sparse checkout still creates a local directory subdir. I don't want a subdirectory called subdir. I want the contents of subdir to be checked out into the top level of my working copy.
An example use case would be:

*

*I clone https://github.com/jquerytools/www.git

*I don't like their css so I do a sparse checkout or use ignores to exclude their css from my checkout.

*I want to use the source/css subdirectory from https://github.com/mozfr/www.git and it must appear in the local css directory


text:
Q: How can I redirect traffic staging site without combining the domain prefix and suffix? I've got a question about apache configs or it may be the .httaccess file. I have staging site : staging.witnesstolove.org with https enabled. when I try to go to the site, I'm redirected to stagingwitnesstolove.org and I'm not sure why?
My apache config seems pretty basic:
<VirtualHost *:80>
     ServerAdmin accounts@1905newmedia.com
     DocumentRoot /home/ubuntu/staging/witnesstolove/current/site/web/
     ServerName staging.witnesstolove.org

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /home/ubuntu/staging/witnesstolove/current/site/web/>
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
     </Directory>

RewriteEngine on
RewriteCond %{SERVER_NAME} =staging.witnesstolove.org
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

I see in devtools that i'm getting a 301 redirect and it says it's being redirected by wordpress.
If I look at the .htaccess file for the site, it's like this:
# BEGIN WordPress
# The directives (lines) between "BEGIN WordPress" and "END WordPress" are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Based on the response headers I'm getting back, it sounds like wordpress is redirecting the traffic to the other domain?
Here's the HTTPS config for the site in Apache:
<IfModule mod_ssl.c>
<VirtualHost *:443>
     ServerAdmin accounts@1905newmedia.com
     DocumentRoot /home/ubuntu/staging/witnesstolove/current/site/web/
     ServerName staging.witnesstolove.org

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /home/ubuntu/staging/witnesstolove/current/site/web/>
        Options +FollowSymlinks
        AllowOverride All
        Require all granted
     </Directory>

RewriteEngine on
# Some rewrite rules in this file were disabled on your HTTPS site,
# because they have the potential to create redirection loops.

# RewriteCond %{SERVER_NAME} =staging.witnesstolove.org
# RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]

SSLCertificateFile /etc/letsencrypt/live/staging.witnesstolove.org/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/staging.witnesstolove.org/privkey.pem
Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>


text:
Q: A riddle about motion and distances So I was facing a Riddle from Dudeney's Canterbury Puzzles book (number $99$), which states :

A country baker sent off his boy with a message to the butcher in the next village, and at the same time the butcher sent his boy to the baker. One ran faster than the other, and they were seen to pass at a spot $720$ yards from the baker's shop. Each stopped $10$ minutes at his destination and then started on the return journey, when it was found that they passed each other at a spot $400$ yards from the butcher's. How far apart are the two tradesmen's shops? Of course each boy went at a uniform pace throughout.

I was trying to write down the equations of motion, but I realised that I cannot.
Calling $A$ and $B$ the distance between baker and butcher, I named a point $P$ where they meet the first time.
Because the first (let's choose it) runs faster, it will surely, over a time $t$, walk more yards than the other. And also it will arrive first at the destination.
Yet the other may still be walking to reach his destination. But whilst he is still walking, the other is resting and those $10$ minutes decrease. At the end of the first person's rest, the other may or mayn't still walking, or he may be resting or why not he may already have to arrive.
How do I set up the equations for a problem like this?
For the records, I report the "apparently weird" solution (weird because the method is weird, and there is no explanation).
Solution

All that is necessary is to add the two distances at which they meet to twice their difference. Thus $720 + 400 + 640 = 1760$ yards, or one mile, which is the distance required. Or, put another way, three times the first distance less the second distance will always give the answer, only the first distance should be more than two-thirds of the second.

A: Call $d$ the total distance, $d_1$ the "first" distance and $d_2$ the "second" distance. Now, call $v_1$ the speed of one of the boys and $v_2$ the speed of the other one (the first boy is running the distance $d_1$ until they meet for the first time). We have:
$$\frac{d_1}{v_1}=\frac{d-d_1}{v_2}$$
(the time until they meet the first time), and
$$\frac{d+d_2}{v_1}+10\text{min}=\frac{d+(d-d_2)}{v_2}+10\text{min}$$
(the time until they meet the second time).
Cancelling $10\text{min}$ and shuffling the factors gives us:
$$\frac{d_1}{d-d_1}=\frac{v_1}{v_2}=\frac{d+d_2}{2d-d_2}$$
thus:
$$d_1(2d-d_2)=(d-d_1)(d+d_2)$$
$$2dd_1-d_1d_2=d^2-dd_1+dd_2-d_1d_2$$
$$0=d^2-3dd_1+dd_2$$
and, assuming $d\ne 0$:
$$d=3d_1-d_2$$


text:
Q: Why isn't my Main element to the right of my nav bar when on a computer full screen? I am working on a code pen and am having an issue where initially my main element would be exactly to the right of my nav bar (on the left side with height = 100%), but not it is overlapped by the nav bar, even though I added a margin-left earlier wide enough to allow the main to be seen. Here is the CSS code:

   html,
    body {
      min-width: 290px;
      color: hsla(214, 100%, 39%, 1);
      font-family: "Germania One", Helvetica, sans-serif;
      font-size: 17px;
      line-height: 1.25;
      background-color: hsla(239, 60%, 40%, 0.49);
    }

    h1 {
      color: black;
    }

    code {
      background-color: hsla(179, 8%, 40%, 0.49);
      border-radius: 3px;
      color: white;
      display: block;
      text-align: left;
      white-space: pre;
      position: relative;
      word-break: normal;
      word-wrap: normal;
      line-height: 1.5;
      padding: 10px;
      margin: 15px;
    }
    #navbar {
      z-index: 1;
      position: fixed;
      background-color: hsla(246, 81%, 24%, 1);
      min-width: 290px;
      top: 0px;
      left: 0px;
      width: 300px;
      height: 100%;
      border-right: solid;
      border-color: hsla(264, 80%, 39%, 1);
    }

    header {
      color: white;
      font-size: 30px;
      margin: 10px;
      text-align: center;
      font-size: 1.8em;
      font-weight: thin;
    }

    #navbar a {
      color: white;
      text-decoration: none;
      cursor: pointer;
    }

    #navbar ul {
      list-style: none;
      height: 88%;
      overflow-y: auto;
      overflow-x: hidden;
    }

    #navbar li {
      border: 1px solid;
      border-bottom-width: 0px;
      padding: 8px;
      padding-left: 45px;
      position: relative;
      left: -50px;
      width: 100%;
    }

    #main-doc {
      position: absolute;
      margin-left: 310px;
      padding: 20px;
      margin-bottom: 110px;
    }

    #main-doc header {
      text-align: left;
      margin: 0px;
    }

    section article {
      margin: 15px;
      font-size: 0.96em;
    }

    section li {
      margin: 10px 0px 0px 10px;
    }

    #Boulder-img {
      width: 80%;
    }

    #Sherpas-img {
      width: 90%;
    }

    @media only screen and (max-width: 815px) {
      /* For mobile phones: */
      #navbar ul {
        border: 1px solid;
        height: 207px;
      }
      code {
        overflow-x: scroll;
      }
      #navbar {
        position: absolute;
        top: 0;
        padding: 0;
        margin: 0;
        width: 100%;
        max-height: 275px;
        border: none;
        z-index: 1;
        border-bottom: 2px solid;
      }
      #main-doc {
        position: relative;
        margin-left: 0px;
        margin-top: 270px;
      }
      #main-doc section {
        color: black;
        /*     padding-top: 240px; */
      }
    }
    @media only screen and (max-width: 400px) {
      #navbar {
        font-size: .75em;
      }
      #navbar ul {
        height: 222px;
      }
      }
      #main-doc {
        margin-left: -10px;
      }
      code {
        margin-left: -20px;
        width: 100%;
        padding: 15px;
        padding-left: 10px;
        padding-right: 45px;
        min-width: 233px;
      }
    }

    FCC Technical Documentation

Explanation

Early Life

First Move

Some Technical Documentation

Present Day

      Explanation

        Introduction paragraph

        &ltcode&gt
        insert example code here
        &lt/code&gt

It looks like I will have to do 5 of these code elements in the project. In order to display the symbol "&lt", I have to type

          &+l+t

 using those characters above without the plus signs. "&gt" is made by using the following in the same way:

          &+g+t

 I don't know how to display those characters together without it automatically displaying as those carrot symbols. I will ask on StackOverFlow (coding website/forum).

          I could do a documentation page describing what I already know and will use to make this page but I can't be bothered :p.

          So I posted my question on StackOverFlow, perhaps I will update in this section (sorry if it is long) if I get an answer. I've gotten the idea to use the code elements to do small features within the page to explain how I made certain parts of it. I also
          read through the prompt completely (glanced over it), and it seems that that was the only road bump. Thanks and enjoy.

:)

      Early Life

        Early life paragraph

first photo header

header for story

        story paragraph

To code in the photos above, I used the img element. The coding goes as follows:

      &ltimg src="linkofimagegoeshere" alt="descriptionincasephotofails" id="goodtohaveidtoalterappearancewithCSS"&gt

      First Move

        first move paragraph

        I later moved to a small town in blank for high school

      Some Technical Documentation

        So it turns out that you can display the code of how to code in a carrot symbol inside of a coding element without having what you type turn into a carrot itself. Sorry if that made no sense, this is hard to describe unless it is seen visually. Here is
        the code that you can enter in order to show &+l+t and &+g+t without them turning into carrots (basically ampersand has it's own sort of reference code).

        &ltcode&gt turns into &ltcode&gt

 In order to prevent &+l+t (etc.) to turn into a carrot, the ampersand code is &+amp;+lt or gt. Please don't send me further down this rabbithole. I don't want to learn how to display that one without the plus signs.

If it appears that some of my CSS code matches that of the example, it is that I am following along with the code as to learn what all of it means and how it works. I'll set most of the copied values the same but I like to adjust them to learn more
        about the associated properties. I definitely did all of the HTML by myself and half of the CSS alone. Once I got stumped, however, I looked at the example's code. I was trying to use flex boxes to make the nav bar, but it turns out that just
        using absolute/relative position with margin, padding, top, left, etc. works better.

      Present Day

        final paragraph

On top of that, I am also:

lifting weights

walking and jogging two miles daily

playing guitar

learning to code

making weekly videos documenting my journey

blank

 and

blank

 I'm hoping to get back to my social life as well.

        I've gone a long way already but I have much longer to go.

 Thanks for reading! :)

I am still new to all of this and honestly don't know where the issue would be so I pasted the whole css code, except for my font import.

A: You had an additional } on the (max-width: 400px) breakpoint that was overriding a previous margin-left rule with margin-left: -10px

html,
body {
  min-width: 290px;
  color: hsla(214, 100%, 39%, 1);
  font-family: "Germania One", Helvetica, sans-serif;
  font-size: 17px;
  line-height: 1.25;
  background-color: hsla(239, 60%, 40%, 0.49);
}

h1 {
  color: black;
}

code {
  background-color: hsla(179, 8%, 40%, 0.49);
  border-radius: 3px;
  color: white;
  display: block;
  text-align: left;
  white-space: pre;
  position: relative;
  word-break: normal;
  word-wrap: normal;
  line-height: 1.5;
  padding: 10px;
  margin: 15px;
}

#navbar {
  z-index: 1;
  position: fixed;
  background-color: hsla(246, 81%, 24%, 1);
  min-width: 290px;
  top: 0px;
  left: 0px;
  width: 300px;
  height: 100%;
  border-right: solid;
  border-color: hsla(264, 80%, 39%, 1);
}

header {
  color: white;
  font-size: 30px;
  margin: 10px;
  text-align: center;
  font-size: 1.8em;
  font-weight: thin;
}

#navbar a {
  color: white;
  text-decoration: none;
  cursor: pointer;
}

#navbar ul {
  list-style: none;
  height: 88%;
  overflow-y: auto;
  overflow-x: hidden;
}

#navbar li {
  border: 1px solid;
  border-bottom-width: 0px;
  padding: 8px;
  padding-left: 45px;
  position: relative;
  left: -50px;
  width: 100%;
}

#main-doc {
  position: absolute;
  margin-left: 310px;
  padding: 20px;
  margin-bottom: 110px;
}

#main-doc header {
  text-align: left;
  margin: 0px;
}

section article {
  margin: 15px;
  font-size: 0.96em;
}

section li {
  margin: 10px 0px 0px 10px;
}

#Boulder-img {
  width: 80%;
}

#Sherpas-img {
  width: 90%;
}

@media only screen and (max-width: 815px) {
  /* For mobile phones: */
  #navbar ul {
    border: 1px solid;
    height: 207px;
  }
  code {
    overflow-x: scroll;
  }
  #navbar {
    position: absolute;
    top: 0;
    padding: 0;
    margin: 0;
    width: 100%;
    max-height: 275px;
    border: none;
    z-index: 1;
    border-bottom: 2px solid;
  }
  #main-doc {
    position: relative;
    margin-left: 0px;
    margin-top: 270px;
  }
  #main-doc section {
    color: black;
    /*     padding-top: 240px; */
  }
}

@media only screen and (max-width: 400px) {
  #navbar {
    font-size: .75em;
  }
  #navbar ul {
    height: 222px;
  }
 /* } You had this closing bracket here*/
  #main-doc {
    margin-left: -10px;
  }
  code {
    margin-left: -20px;
    width: 100%;
    padding: 15px;
    padding-left: 10px;
    padding-right: 45px;
    min-width: 233px;
  }
}

    FCC Technical Documentation

Explanation

Early Life

First Move

Some Technical Documentation

Present Day

      Explanation

        Introduction paragraph

        &ltcode&gt
        insert example code here
        &lt/code&gt

It looks like I will have to do 5 of these code elements in the project. In order to display the symbol "&lt", I have to type

          &+l+t

 using those characters above without the plus signs. "&gt" is made by using the following in the same way:

          &+g+t

 I don't know how to display those characters together without it automatically displaying as those carrot symbols. I will ask on StackOverFlow (coding website/forum).

          I could do a documentation page describing what I already know and will use to make this page but I can't be bothered :p.

          So I posted my question on StackOverFlow, perhaps I will update in this section (sorry if it is long) if I get an answer. I've gotten the idea to use the code elements to do small features within the page to explain how I made certain parts of it. I also
          read through the prompt completely (glanced over it), and it seems that that was the only road bump. Thanks and enjoy.

:)

      Early Life

        Early life paragraph

first photo header

header for story

        story paragraph

To code in the photos above, I used the img element. The coding goes as follows:

      &ltimg src="linkofimagegoeshere" alt="descriptionincasephotofails" id="goodtohaveidtoalterappearancewithCSS"&gt

      First Move

        first move paragraph

        I later moved to a small town in blank for high school

      Some Technical Documentation

        So it turns out that you can display the code of how to code in a carrot symbol inside of a coding element without having what you type turn into a carrot itself. Sorry if that made no sense, this is hard to describe unless it is seen visually. Here is
        the code that you can enter in order to show &+l+t and &+g+t without them turning into carrots (basically ampersand has it's own sort of reference code).

        &ltcode&gt turns into &ltcode&gt

 In order to prevent &+l+t (etc.) to turn into a carrot, the ampersand code is &+amp;+lt or gt. Please don't send me further down this rabbithole. I don't want to learn how to display that one without the plus signs.

If it appears that some of my CSS code matches that of the example, it is that I am following along with the code as to learn what all of it means and how it works. I'll set most of the copied values the same but I like to adjust them to learn more
        about the associated properties. I definitely did all of the HTML by myself and half of the CSS alone. Once I got stumped, however, I looked at the example's code. I was trying to use flex boxes to make the nav bar, but it turns out that just
        using absolute/relative position with margin, padding, top, left, etc. works better.

      Present Day

        final paragraph

On top of that, I am also:

lifting weights

walking and jogging two miles daily

playing guitar

learning to code

making weekly videos documenting my journey

blank

 and

blank

 I'm hoping to get back to my social life as well.

        I've gone a long way already but I have much longer to go.

 Thanks for reading! :)


text:
Q: Exclude file from project via msbuild In my .csproj file, I am creating directories containing files, and these directories are being created in the main project directory as intended. For certain reasons, I cannot generate these directories in bin\debug. However, I do not want the files generated in the directories to be included in the project, as I do not want them to be checked in.
How can I exclude the files from my project automatically through msbuild?
For reference, I have tried the following, and though the files get generated as expected, they are still being added to the project unintentionally:
<Target Name="BuildThings" AfterTargets="Build" BeforeTargets="GatherStagingFiles" Inputs="@(Compile)" Outputs="$(GeneratedFilesDirectory)">
    <Exec WorkingDirectory="$(MSBuildProjectDirectory)" Command="$(ToolPath) buildpackage -InputDir:$(MSBuildProjectDirectory)\$(OutDir) -OutputDir:$(MSBuildProjectDirectory)\$(GeneratedFilesDirectory)" />
</Target>

<Target Name="HideFiles" DependsOnTargets="BuildThings">
  <ItemGroup>
    <GeneratedFiles Include="$(MSBuildProjectDirectory)\$(GeneratedFilesDirectory)\file.txt">
      <InProject>false</InProject>
    </GeneratedFiles>
  </ItemGroup>
</Target>


text:
Q: When to use backticks when with Postgres Query In PHP when using PDO to query my PostgreSQL database I have this query
$stmt = $myPDO->prepare(
    "SELECT clientid,status,action,datecompleted FROM clientapi.table1"
);
$stmt->execute();

As you can see, the database uses several reserved words as column names, status & action. Should I be escaping these with backticks? And if yes, should I only escape the reserved words? Lastly this query does already run fine without any issues without escaping them


text:
Q: ¿Cual es el error de este algoritmo? Quisiera ver si me pudieran ayudar a encontrar el error en este algoritmo, el ejercicio dice que calcule el descuento: si m>=300 el descuento es del 25% - si 150<=m y m<300 el descuento es del 2% - si m<150 no hay descuento. El problema  que tengo es que me toma todos los descuentos. Acá les dejo el programa, estoy programando en C++.
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main () {
    int monto,desc1,calc1,desc2,calc2;

    printf("Ingrese el monto: ");
    scanf("%d",&monto);
    if (monto>300)
    calc1=monto*0.25;
    desc1=monto-calc1;
    printf("El descuento es de: %d $",calc1);
    printf("\nEL total a pagar es de: %d $",desc1);
    else if ((monto<=150 && monto<300))
    calc2=monto*0.2;
    desc2=monto-calc2;
    printf("El descuento es de: %d $",calc2);
    printf("\nEl total a pagar es de: %d $",desc2);
    if (monto<150)
    printf("No hay descuento");
    printf("\nEl total a pagar es de: %d $",monto);
}

A: Como te había comentado faltaban las llaves de apertura y cierre de cada bloque, pero además tenías mal la segunda condición if ((monto<=150 && monto<300)) que te acabo de corregir. Unos comentarios.

*

*C y C++ no inicializan los valores de las variables por lo que siempre es una buena práctica inicializarlas luego de declararlas: int monto=0,desc1=0,calc1=0,desc2=0,calc2=0;

*Agregué un "casteo" a int en el cálculo del descuento: int (monto*0.25) para evitar warnings durante la compilación y de paso te comento que estás perdiendo la parte decimal del calculo al usar int pero me imagino es lo que pide el ejercicio.

*Como ya comentó @Trauma la condición final es innecesaria
El código:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main ()
{
    int monto=0,desc1=0,calc1=0,desc2=0,calc2=0;

    printf("Ingrese el monto: ");
    scanf("%d",&monto);

    if (monto>300) {
        calc1=int (monto*0.25);
        desc1=monto-calc1;
        printf("El descuento es de: %d $",calc1);
        printf("\nEL total a pagar es de: %d $",desc1);
    }
    else if ((monto>=150 && monto<300)) {
         calc2=int (monto*0.2);
         desc2=monto-calc2;
         printf("El descuento es de: %d $",calc2);
         printf("\nEl total a pagar es de: %d $",desc2);
    } else {
        printf("No hay descuento");
        printf("\nEl total a pagar es de: %d $",monto);
    }
}

A: Deberia estar asi
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

int main () {
    int monto,desc1,calc1,desc2,calc2;

    printf("Ingrese el monto: ");
    scanf("%d",&monto);
    if (monto>300){
       calc1=monto*0.25;
       desc1=monto-calc1;
       printf("El descuento es de: %d $",calc1);
       printf("\nEL total a pagar es de: %d $",desc1);
    }
    else if ((monto<=150 && monto<300)){
       calc2=monto*0.2;
       desc2=monto-calc2;
       printf("El descuento es de: %d $",calc2);
       printf("\nEl total a pagar es de: %d $",desc2);
    }
    else (monto<150){
       printf("No hay descuento");
       printf("\nEl total a pagar es de: %d $",monto);
    }
}


text:
Q: codesign plugins for mac app Following this article, I'm running codesign for all frameworks. However, I'm still getting a codesign error with plugins.
/.../Applications/MyApp.app: code object is not signed at all
In subcomponent: /.../MyApp.app/Contents/PlugIns/Flash Player.plugin
Command /usr/bin/codesign failed with exit code 1

How should I add codesign command for plugins? Tried various directories/files, but didn't work:
codesign --verbose --force --sign "$IDENTITY" "$PLUGINS_LOCATION/Flash Player.plugin"

A: We had to codesign the plugin separately:
codesign --deep --verbose --force --sign "Developer ID Application" Plugins/Flash\ Player.plugin


text:
Q: How to create a copy of a map in f#?    let students =
    Map.empty.
          Add("ABC", "97").
          Add("Jill", "98");;
    printfn "Map - students: %A" students

This I know will create a map named students. I was thinking a way to create a copy of this map, with same key and value. I checked the documentation for f#, and didn't find any methods that clone/create a copy of map.

A: F# maps are immutable. This means that "changing" a map actually means creating a copy with some slight changes. The copy process uses tricks to make it much faster than a full copy. The new version can actually point back to the old version for most of the data. This is safe to do because the maps are immutable: they can never change.
This means that there is no possible reason to copy a map, except to warm up your CPU
The same applies to List and Set in F#, as they are also immutable. It takes a while to get used to working with immutable data structures but life gets easier once you do.

By the way you can create the map with less code like this:
let students =
    [ "ABC", "97"
      "Jill", "98" ]
    |> Map

A: Here's one way to do it.
let copy =
    students
    |> Seq.map (fun pair -> pair.Key, pair.Value)
    |> Map