text:
Q: URL Query string using multiple drop down list selections (ideally PHP?) I am trying to create a dynamic URL query string on a PHP based shopping cart when a submit button is pressed on a PHP form page where the website user has selected options from multiple drop down menus.
URL Example: www.mydomain.com/index.php?main_page=advanced_search_result&search_in_description=1&keyword=32-C
If you look at the above URL the final section after "&keyword=" should be dynamic, so its basically the URL:  www.mydomain.com/index.php?main_page=advanced_search_result&search_in_description=1&keyword="FIRST DROP DOWN BOX"+"-"+"SECOND DROP DOWN BOX SELECTION"
I just have no idea how to script this & how to set the form button to execute the script...PLEASE HELP!!!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Search</title>
</head>
<body>

<form name="form1" method="post" action="">

  <select name="BustSize" id="BustSize">
<option value="0" selected="selected">Bust Size</option>
<option value="30">30</option>
<option value="32">32</option>
<option value="34">34</option>
<option value="36">36</option>
<option value="38">38</option>
<option value="40">40</option>
  </select>

<select name="CupSize" id="CupSize">
<option value="0" selected="selected">Cup Size</option>
<option value="AA">AA</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="DD">DD</option>
<option value="E">E</option>
<option value="F">F</option>
</select>

<input name="Search" type="button" value="Submit">

</form>

</body>
</html>

A: This can be done with the support of jQuery. I have created a working script at following url: http://sugunan.net/demo/form1.php . You can see the source code there as it is pure HTML and javascript function. But here I copy the code for your reference.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>Search</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>

<script>
$(document).ready(function(){
    $( "#submit_search" ).click(function() {
        var url = "http://sugunan.net/demo/form1.php?main_page=advanced_search_result&search_in_description=1&keyword="
        url = url + $( "#BustSize" ).val();
        url = url + "-" + $( "#CupSize" ).val();
        window.location = url;
    });
});
</script>
</head>
<body>

<form name="form1" method="post" action="">

  <select name="BustSize" id="BustSize">
<option value="0" selected="selected">Bust Size</option>
<option value="30">30</option>
<option value="32">32</option>
<option value="34">34</option>
<option value="36">36</option>
<option value="38">38</option>
<option value="40">40</option>
  </select>

<select name="CupSize" id="CupSize">
<option value="0" selected="selected">Cup Size</option>
<option value="AA">AA</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="DD">DD</option>
<option value="E">E</option>
<option value="F">F</option>
</select>

<input name="Search" id="submit_search" type="button" value="Submit" />

</form>

</body>
</html>

Check the HTML header for the script portion.

A: *

*You can create an hidden input field named "keyword" in your form:

*Attach a handler to the onsubmit event of the form:
<form name="form1" method="post" action="" onsubmit="updateKeyword()">

*The updateKeyword function:
function updateKeyword(){

    var bustSize = document.getElementById("BustSize").value,
    cupSize = document.getElementById("CupSize").value;

    document.forms[0].keyword.value = bustSize+"-"+cupSize;
}

Hope this helps.


text:
Q: Teradata stored procedure i am planning to write stored procedure (teradata) with bunch of update statements in it .i want to capture number of rows updated for each update statement into an audit table .so can some one help me with SQL?

A: You can use the ACTIVITY_COUNT variable within your stored procedure.  For example:
   UPDATE MyTable
   SET col1 = 'val';

   INSERT INTO MyAuditTable (ActivityCount)
   VALUES (:ACTIVITY_COUNT);

Keep in mind this variable is only accessible within your SP.
TD Manual

redpajama_set_name: RedPajamaStackExchange


text:
Q: Thread waiting in C I am implementing a parallel code in C with pthreads. Right now I am trying mixed operation on a specific data structure with mutex locks. Say for example I have a data set of 5,00,000 and I have employed 4 threads to insert into the structure and 4 threads to delete from it parallely (the whole data). I need the 4 threads of deletion to start only after the 4 threads of insertion have completed atleast 30 - 50 % portion of the data to be inserted. Is it possible to delay the threads? Can the condition format of pthreads be used for the same? Any resources leading to the same if provided will be useful.
A sample code:
thds = (pthread_t *)malloc((nthdsIns + nthdsDel - 1) * sizeof(pthread_t));
thdArg = (tArg *)malloc((nthdsIns + nthdsDel - 1) * sizeof(tArg));

for(i = 0; i < nthdsIns; i++){
    thdArg[i].num = numsIns; // array of elements to be inserted
    thdArg[i].start = i * iterIns; //starting index
    if(nthdsIns == 1)
        thdArg[i].end = nValIns-1; //ending index
    else
        thdArg[i].end = (i+1) * iterIns - 1;
}

for(k=0; k < nthdsIns; k++)
    pthread_create(&thds[k], NULL, pThdIns, &thdArg[k]);//spawning threads

temp = k;

/*Need to put some condition here inorder to allow the insertion threads to complete half of the insertion part*/

for(j = i, k = 0; k < nthdsDel; j++, k++){
    thdArg[j].num = numsDel;//array for deletion
    thdArg[j].start = k * iterIns;
    thdArg[j].end = (k+1) * iterIns - 1;
}

for(k = 0, j = temp; k < nthdsDel; k++, j++)
    pthread_create(&thds[j], NULL, pThdDel, &thdArg[j]);//spawning threads

for(i=0; i < (nthdsIns + nthdsDel); i++)
    pthread_join(thds[i], NULL);//joining threads

A: You should use condition variables(condvar), mutices etc to synchronize your threads.
delete()
{
  wait_on_cond();
  take_lock();
  actual_insert();
  release_loc();
}

insert()
{
  take_lock();
  actual_insert()
  release_lock();
  signal_condition();
}

This is basic idea on how can one use conditions. You need to check the actual documentation of library you plan to use.


text:
Q: Random straight line walk with conditions A drunkard is 9 steps away from home, and 1 step behind him is a pit. He will move 1 step forward/backward with probabilities of 0.7/0.3 respectively.What are the probabilities that
(a) he will fall into the pit
(b) reach home
(c) reach 1 step away from home
I had solved a somewhat similar problem, but with no pit and a condition of reaching home in 20 steps or less, by analysing patterns on a 2D lattice, getting the formula
sum of (3/n)*C(2n, n+3)*0.7^(n+3)*0.3^(n-3) for n = 3 to 10 = 0.814401
but i don't know how to tackle this question.
I'm not very savvy mathematically, so the simpler the explanation, the more welcome it will be !

A: Call $P(n)$ the probability of reaching  home if you are $n$ step from the pit. So $P(0)=0$, $P(10)=1$. You are looking for $P(1)$.
For $0&ltn&lt10$
$$P(n)=0.7*P(n+1)+0.3*P(n-1)$$
The general solution to this equation is $P(n)=a + b*(0.3/0.7)^n$ (see this link), and using the know value we can write: $P(0)=a+b*1=0$ and $P(10)=a+b*(0.3/0.7)^{10}=1$,  and find $$P(n)=a+b*(0.3/0.7)^1=\frac{(0.3/0.7)^n-1}{(0.3/0.7)^{10}-1}$$
$$P(1)=\frac{(0.3/0.7)^1-1}{(0.3/0.7)^{10}-1}$$
The probability of reaching home is $\approx0.5715$ ($P(1)$), the probability of falling $1-P(1)$, and the probability of reaching the last step but don't reaching home is $\frac{(0.3/0.7)^1-1}{(0.3/0.7)^{9}-1}-\frac{(0.3/0.7)^1-1}{(0.3/0.7)^{10}-1}$ because P(reaching the last step AND don't go home) = P(reaching the last step) - P(reaching the last step AND go home) = P(reaching the last step) - P(go home).


text:
Q: how to set a tab to show automatically upon loading webpage Jsfiddle: http://jsfiddle.net/87YGW/
At present I have to click tab 1 to show content however I want tab 1 content to display automatically upon opening the page.
HTML:

 Tab 1

tab conten1

 Tab 2

Tab Content 2

 Tab 3

tab content 3

 Tab 4

Tab Content 4

CSS:
.css-tabs {
    position: relative;
    text-align: left; /* This is only if you want the tab items at the center */
    height: auto
}
.css-tabs ul.noint11_menu {
    list-style-type: none;
    display: inline-block; /* Change this to block or inline for non-center alignment */
}
.css-tabs ul.noint11_menu > li {
    display: block;
    float: left;
}
.css-tabs ul.noint11_menu li > a {
    color: #EEEEEE;
    text-shadow: 1px 1px 1px #000;
    font-family: 'MuliLight', Arial, sans-serif;
    font-size: 14px;
    text-decoration: none;
    display: block;

}
.css-tabs ul.noint11_menu li > div {
    display: none;
    position: absolute;
    width: 100%;

}
.css-tabs ul.noint11_menu li > div > p {
    border: transparent;
    padding: 10px;
    margin: 0;
}
.css-tabs ul.noint11_menu li > a:focus {
    border-bottom: 1px solid #fff;
}
.css-tabs ul.noint11_menu li:target > a {
    cursor: default;
    border-bottom: 1px solid #fff;
}
.css-tabs ul.noint11_menu li:target > div {
    display: block;
}

I cannot use Javascript, Jquery or iframe

A: In your CSS add:
#item-1 div {display: block}

A: I cannot demo it in the fiddle (because iframe), but if you link to the first tab directly, eg: http://www.yoururl.com/page#item-1, the first tab's content will be visible on page load.
You can test this by putting all your code inside a new blank html file (CSS and markup in their correct places) and saving it as "test.html".  Then make another html file inside the same folder with this code:

    link

Save and open the second file and click the link to go to your styled page. Note the first tab's content is visible, and tab switching still works as expected.
Without JS to redirect or to change the window location, I don't believe you can get the same result through CSS alone.
This article explains why it works: The :target pseudo selector in CSS matches when the hash in the URL and the id of an element are the same.

edit to add another hacky, but pure CSS "solution":
Make the first tab always visible with #item-1 div {display: block}, and set a background colour on all tabs:
.css-tabs ul.noint11_menu li > div {
    display: none;
    position: absolute;
    width: 100%;
    left: 0;
    color: #ccc;
    text-align: left;
    padding: 0;
    margin-left: 32px;
    background: #fff; /* added this */
}

Now the other tabs will hide the first tab when they are selected.  demo: http://jsfiddle.net/87YGW/3/


text:
Q: Not receiving separate values on the server-side client-server TCP I have a problem with receiving the correct values on the server-side of my client-server program.
header file included in both server and client:
#define CHUNK_SIZE 1024
#define ARR_LEN 3

client:
int uids[ARR_LEN] = {1994, 2423, 1222};
unsigned int uidlen = 0;
char uidbuffer[CHUNK_SIZE] = {0};

for(int i = 0; i < ARLL; i++)
{
    uidlen = strlen(uids[i])+1;
    snprintf(uidbuffer, uidlen, "%s", uids[i]);

    if(send(socket, uidbuffer, strlen(uidbuffer), 0) < 0)
        DIE("Write Error");
    if(recv(socket, uidbuffer, sizeof(uidbuffer), 0) < 0)
        DIE("Acknowledge Error");

    memset(uidbuffer, 0, sizeof(uidbuffer));
}

server:
char uid_buff[CHUNK_SIZE];
for(int i = 0; i < ARR_LEN; i++)
{
    memset(uid_buff, 0, sizeof(uid_buff));
    // receiving the UID and storing it directly
    if(recv(client_sock, uid_buff, sizeof(uid_buff), 0) < 0)
        DIE("Receive Error");

    printf("buffer content: %s\n", uid_buff);
    uid_str = uid_buff;

    uids[i] = (uid_t)strtol(uid_str, (char **)NULL, 10);

    if(send(client_sock, uid_buff, sizeof(uid_buff), 0) < 0)
        DIE("Acknowledge Error");
}

These are only parts of my program. I tried to only include the relevant parts. The output is this:
buffer content: 1994
buffer content: 24231222
buffer content:

While I want it to be:
buffer content: 1994
buffer content: 2423
buffer content: 1222

What could be the problem? I know that it's not so easy and that server–client communication is carried out in a stream of bytes rather than messages, but I want to mimmic that functionality by acknowledging every received "message". Could you please clue me what to do? I'm getting desperate.

A: You will need a protocol.
For example, you define that each message in your application has following format:
xx | message

this means first two bytes (mind the endianness) you receive indicate the length of the message that follows. Now you should first receive first two bytes - check the length - and then receive exactly that number of bytes. After that you know you have successfully received that message. And then you can proceed to other messages (which could/should have similar format: length + message itself).
Example:
Say you want to send three messages:
char s1[]="message1";
char s2[]="message2";
char s3[]="message3";

//You do this(client side):

int x1 = strlen(s1); // length of message1
int intsize = 4; // just size of integer -we'll need in next call

sendall(socket, &x1, &intsize); // send length of first message
sendall(socket, s1, &x1); // Now send the message

//On server:
int x = 0;
int y = 4; //size of integer most probably
receiveall(socket,&x,&y);//get length first; y=4 because that is size of integer
receiveall(socket, buffer, &x); // now we know how many bytes to expect - x - so request that number of bytes only

you can repeat this logic for other messages too.
Finally, you want to use such functions (here) instead of send and receive (because send and receive might not send/receive the number of bytes you tell it to):
int sendall(int s, char *buf, int *len)
{
    int total = 0;        // how many bytes we've sent
    int bytesleft = *len; // how many we have left to send
    int n;

    while(total < *len) {
        n = send(s, buf+total, bytesleft, 0);
        if (n == -1) { break; }
        total += n;
        bytesleft -= n;
    }

    *len = total; // return number actually sent here

    return n==-1?-1:0; // return -1 on failure, 0 on success
}

you will need a similar receiveall function.

A: You do not show the code that establishes the connection.
If you are using UDP sockets, each message is stand alone, you will receive a separate message for each message sent, but not necessarily in the same order.
If you are using TCP or Unix sockets, data may be received in chunks of different sizes than those used for sending.  Only the sequence of bytes is preserved, not the chunk sizes.  You need to specify a protocol: unless you specify a fixed number of bytes per message, you need to send some sort of separator to allow the server to tell where each message ends.


text:
Q: Displaying image in JSF-based web application I have a JSF application and I am trying to display an image that is sitting locally on another machine in the intranet:
<h:graphicImage id="image"
    url="\\myip\C\images\myimg.jpg">
</h:graphicImage>

C is a shared folder.
However it doesn't display it and when I look in the source it adds the localhost:8080 as post fix.
how can I deal with it?
When I write the URL with notepad - not as web application it works just fine!

A: Use plain HTML - <img src="...">

A: url="file:///C:/images/myimg.jpg"


text:
Q: Serving GeoTIFFs of different resolutions as single layer I'm trying to serve a 30 arc second DEM with global coverage combined with high resolution 1/3 arc second DEM for a very small area.

*

*I believed at first I could combine them into a single file, however this seems impossible as the file would end up as around 45GB

Questions

*

*Is there another way of solving this problem using geoserver?

*Alternative formats which support this?

*Can the Image Mosaic plugin in Geoserver deal with this? I've tried, but it doesn't appear to work. The documentation implies only a single resolution can be dealt with, however the Heterogeneous=true option implies multiple resolutions?

Details of the two files
gdalinfo GEBCO_2014_1D_EPSG4326.tif
Driver: GTiff/GeoTIFF
Files: GEBCO_2014_1D_EPSG4326.tif
Size is 43200, 21600
Coordinate System is `'
Origin = (-180.000000000000000,90.000000000000000)
Pixel Size = (0.008333333333333,-0.008333333333333)
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  (-180.0000000,  90.0000000)
Lower Left  (-180.0000000, -90.0000000)
Upper Right ( 180.0000000,  90.0000000)
Lower Right ( 180.0000000, -90.0000000)
Center      (   0.0000000,   0.0000000)
Band 1 Block=43200x1 Type=Int16, ColorInterp=Gray

gdalinfo asc/puerto-rico.tif
Driver: GTiff/GeoTIFF
Files: asc/puerto-rico.tif
Size is 24301, 11881
Coordinate System is:
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0],
    UNIT["degree",0.0174532925199433],
    AUTHORITY["EPSG","4326"]]
Origin = (-67.600046296295005,18.800046283695000)
Pixel Size = (0.000092592590000,-0.000092592590000)
Metadata:
  AREA_OR_POINT=Area
Image Structure Metadata:
  INTERLEAVE=BAND
Corner Coordinates:
Upper Left  ( -67.6000463,  18.8000463) ( 67d36' 0.17"W, 18d48' 0.17"N)
Lower Left  ( -67.6000463,  17.6999537) ( 67d36' 0.17"W, 17d41'59.83"N)
Upper Right ( -65.3499538,  18.8000463) ( 65d20'59.83"W, 18d48' 0.17"N)
Lower Right ( -65.3499538,  17.6999537) ( 65d20'59.83"W, 17d41'59.83"N)
Center      ( -66.4750000,  18.2500000) ( 66d28'30.00"W, 18d15' 0.00"N)
Band 1 Block=24301x1 Type=Int16, ColorInterp=Gray
  NoData Value=-9999


text:
Q: Dispaying All Data Points between two ranges I have a table that has several rows out lining ranges between two zip codes for each state. I am hoping to be able to take the two ranges and display every value between the two ranges on their own separate line. EX below.
Zip Start   Zip End     State
00501       06390       NY
10001       10314       NY
10451       11003       NY

I am hoping to display the data as
00501    NY
00502    NY
00503    NY
00504    NY

Any help would be greatly appreciated.
    DROP TABLE IF EXISTS yourTable;
CREATE TABLE yourTable as
Select '00501' as zipstart,'06390' as zipend,'NY' as state union
select'10001','10314','NY'union
select'10451','11003','NY'

Distributed by (ZipStart,ZipEnd,State);

WITH cte AS (
    SELECT *
    FROM
       (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)

, cteTally AS (
    SELECT
       ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Num
    FROM
       cte c1
       CROSS JOIN cte c2
       CROSS JOIN cte c3
       CROSS JOIN cte c4
       CROSS JOIN cte c5
)

SELECT
    SUBSTRING(ZipStart || CAST(tt.Num AS VARCHAR(100)),1,5) ZipSTart
    ,t.zipend,t.State
FROM
    yourTable t
    INNER JOIN cteTally tt
    ON tt.Num <= CAST(t.ZipEnd AS INT)
    AND tt.Num >= CAST(t.ZipStart AS INT)

A: PostgreSQL
select  to_char(zip,'FM00000') as zip
       ,state

from    t,generate_series("Zip Start"::int,"Zip End"::int) gs(zip)
;

A: Here is a Sql server version that does work on PostgreSQL and several other platforms. that handles up to 100,000 numbers to expand simply add more cross join's in the cteTally definition.
IF OBJECT_ID('tempdb..#yourTable') IS NOT NULL
    BEGIN
        DROP TABLE #yourTable
    END

CREATE TABLE #yourTable (ZipStart VARCHAR(5), ZipEnd VARCHAR(5), State CHAR(2));
INSERT INTO #yourTable VALUES
('00501','06390','NY')
,('10001','10314','NY')
,('10451','11003','NY');

WITH cte AS (
    SELECT *
    FROM
       (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)

, cteTally AS (
    SELECT
       ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as Num
    FROM
       cte c1 --10
       CROSS JOIN cte c2 --100
       CROSS JOIN cte c3 --1,000
       CROSS JOIN cte c4 --10,000
       CROSS JOIN cte c5 --100,000
)

SELECT
    RIGHT('00000' || CAST(tt.Num AS VARCHAR(100)),5) as GeneratedZip
    ,t.ZipStart
    ,t.ZipEnd
    ,t.State
FROM
    #yourTable t
    INNER JOIN cteTally tt
    ON tt.Num <= CAST(t.ZipEnd AS INT)
    AND tt.Num >= CAST(t.ZipStart AS INT)

and for PostgreSQL specifically and the platforms that support generate_series check out Dudu's answer

A:
This is for Sql Server. I'll leave it here just because I took the time to write it.

This is pretty simple with a numbers table.
rextester: http://rextester.com/MEFE32862
numbers table stolen from @AaronBertrand's article on generating a set.
begin;
create table dbo.zip_ranges (id int ,StateName varchar(32) ,[State] char(2) ,Zip_Start int ,Zip_End int )
  insert into dbo.zip_ranges (id, StateName, [State], Zip_Start, Zip_End) values
    (1 ,'New York (Fishers Is)' ,'NY' ,501 ,6390) ,(2 ,'New York' ,'NY' ,10001 ,10314),(3 ,'New York' ,'NY' ,10001 ,10314) ,(4 ,'Ohio' ,'OH' ,43001 ,45999)
  create unique clustered index n on dbo.zip_ranges(Id)
end;
/* 100,000 number table - stolen from @AaronBertrand https://sqlperformance.com/2013/01/t-sql-queries/generate-a-set-1 */
begin;
  select top (100000) n = convert(int, row_number() over (order by s1.[object_id]))
    into dbo.numbers
    from sys.all_objects as s1
      cross join sys.all_objects as s2
    option (maxdop 1);
  create unique clustered index n on dbo.numbers(n)
end;

select
        --Zip=n.n
        --Zip=left('00000',5-len(n.n))+convert(varchar(5),n.n)
        Zip=right('00000'+convert(varchar(5),n.n),5) /* grabbed this conversion from @Matt instead of my clunky one */
      , z.[State]

from dbo.zip_ranges z
    inner join dbo.numbers n on n >= z.zip_start and n <= z.zip_end
    where z.[State]='NY'
    order by n


text:
Q: Why after storing data in variable I am getting undefined in typescript? I am writing a program in which I am trying to create a service and declare a variale in service and then creating a get() method in service to print the variable by calling the service method from component but I am getting undefined. Why?
AppComponent.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  }

}

AppComponent.html
<app-comp1></app-comp1>

Comp1Component.ts
import { Component, OnInit } from '@angular/core';
import { AService } from 'src/app/services/a.service';

@Component({
  selector: 'app-comp1',
  templateUrl: './comp1.component.html',
  styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {

  constructor(private aService:AService) { }

  ngOnInit() {
    this.aService.getFunc1();
  }

}

AService.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AService {

  private a;

  constructor() { }

  public func1():void
  {
    this.a=11;

  }

  public getFunc1()
  {
    console.log(this.a);
  }
}

A: From this code you never called func1() there for the variable held in the service never gets assigned. Before the getfunc() you would need to call the other function. So it would be
ngOnInit() {
    this.aService.func1()
    this.aService.getFunc1()
}

A: Make sure you include the service in your module. (Or you can add it as provider to the component. )
@NgModule({

  ...
  providers: [AService,...],
  ...
})

A: Assuming you are getting undefined on the service.
You have to provide the service as Injectable to the app. One way to do that will be tomar service like this:
@Injectable({
  providedIn: 'root'
})

export class AService {
//service body
}

If the service needs to be scope at the module level, you can change the providedIn: 'module'
Read more on the angular documentation: https://angular.io/guide/providers


text:
Q: Send text message to Google voice number using php I know you can send an SMS to a mobile phone using the recipients # and carrier suffix. Is it possible to send SMS to a Google Voice # using the same method?
If so, what is used for a carrier suffix? (5552125689@ ??? )
mail("5552125689@txt.att.net", "", "You have a new message", "test@mydomain.com");

Thanks

A: As far as I know, Google Voice does not support email to SMS.
You would most likely need to use an SMS gateway service like Twilio to be able to send to Google Voice.
Here's how to send an SMS with PHP and Twilio.


text:
Q: Does the use of styleSheets in a dynamic manner add a lot of computation I have about 40 buttons that are also indicators (On or Off) and once a second I refresh the color of these indicators depending on the state.  I do this by changing the stylesheet. Is it over kill to do this and if so should I only set a new stylesheet when it the indicator has changed state or should I use something like QBrush?

A: Yes. I found that with Qt 4.6.2 on Linux, setting a stylesheet to change the colour of the text on a QLabel is very slow.
The dynamic stylesheet looked like a great solution but for me, the necessary setStyle() was just as expensive as setStyleSheet()!
After much experimentation, I found this alternative to be at least twice as quick, and usually more than 50 times as quick:
QPalette palette = lbl->palette();
palette.setColor(QPalette::WindowText, Qt::gray);
lbl->setPalette(palette);

Depending on how your (static) stylesheet is set up, you'd have to replace QPalette::WindowText with QPalette::Window or QPalette::Button. See the QPalette documentation for details.

A: Do not dynamically set complete stylesheets. Instead, define an application wide stylesheet using dynamic stylesheet that you parse once at application startup. Then, in the stylesheet, define dynamic stylesheet properties as detailed in the documentation:

There are many situations where we need to present a form that has mandatory fields. To indicate to the user that the field is mandatory, one effective (albeit esthetically dubious) solution is to use yellow as the background color for those fields. It turns out this is very easy to implement using Qt Style Sheets. First, we would use the following application-wide style sheet:
*[mandatoryField="true"] { background-color: yellow }

In your case, you could probably do something like this:
QPushButton[state="on"] {
  background-color: green;
}

QPushButton[state="off"] {
  background-color: red;
}

Then update the button 'state' property:
pushButton->setProperty("state", "on");
pushButton->setStyle(QApplication::style());

Unfortunately, for Qt 4.6 you will need to force a recomputation of the stylesheet by resetting the style of the widget, hence the setStyle() call.
Using dynamic stylesheets in this way is very fast. I am working on an application that makes heavy use of dynamic stylesheet properties and have not noticed any performance degredation.

A: In my experience stylesheets consume too much resources, better to avoid them if you can.


text:
Q: Mobile compatible website template for masterpage I have been looking all over for templates that are mobile compatible.  I understand that people carry the web with them. My present website uses an old css template which does not work well in phones.  I found a template here at https://html5up.net/photon
I downloaded this, but I'm having problems integrating it into a masterpage. It is a html page with links to images that are not working.  Where can I get a basic masterpage for vb.net that is mobile compatible? It needs to have a nav bar. Thanks.


text:
Q: How to take the Limits of Logs How would you take the limit of
$$\frac{\log(n!)}{\log(n^n)}$$
as $n\rightarrow\infty$.
I believe you have to remove the log raising it to their base. Is this correct ?
Thanks.

A: Hint:
Use Sterling's approximation of $n!$:
$$n!\sim \left(\frac{n}{e}\right)^n \sqrt{2\pi n}$$
as $n\rightarrow\infty$.
Solution:
By Sterling's approximation:
$$\lim_{n\rightarrow\infty}\frac{\log(n!)}{\log(n^n)}=\lim_{n\rightarrow\infty} \frac{\log((n/e)^n\sqrt{2\pi n})}{\log n^n}$$
Use logarithm laws to see
$$\log((n/e)^n\sqrt{2\pi n})=n\log n-n+\log(\sqrt{2\pi n})$$
and $\log(n^n)=n\log(n)$.
Then
$$\frac{n\log n-n+\log(\sqrt{2\pi n})}{n\log n}=1-\frac{1}{\log n}+\frac{\log(\sqrt{2\pi n})}{n\log n}$$
The last two terms all go to $0$ as $n\rightarrow\infty$. Thus we conclude
$$\lim_{n\rightarrow\infty}\frac{\log(n!)}{\log(n^n)}=1$$

A: Hints:
1)

$$ \ln(n!) = \sum_{k=1}^{n}\ln(k) \sim \int_{1}^{n}\ln(x)dx = n\ln n - n +1. $$

2)

$$ \ln(n^n) = n\ln n. $$


text:
Q: Paypal Sandbox Subscription Webhook Renew Event Not Working We have setup webhook event for our paypal subscription, All the event working fine.
Currently we are in sandbox setup.
All the webhook events are working fine. But we are not getting the event for the RENEW.
Here is the key name.
BILLING.SUBSCRIPTION.RENEWED is not working.
It's already down in sandbox or any idea what is the case.
Thank you in advance.


text:
Q: How to solve such ordinary differential equations? Let $\{y_i\}_{i=0,...,d}$ be a sequences of functions depending on $x$ and satisfies $y'_i(x)=-\frac{(i+1)y_i(x)}{\sum_{i=0}^dy_i(x)}$ for $0\le i\le d$ with original conditions $y_d(0)=1$ and $y_i(0)=0$ for $i<d$ . And we assume $d\ge 3$. How can we solve such odes? Or an expression of $y_0+...+y_d$ only depends on $x$ is good enough for me.

A: Since $y_i(0) = 0$, and $y_i'$ is proportional to $y_i$, one concludes that $y_i(x) = $ for all $x$. Which leaves $y_d' = - \frac{(d+1)y_d}{y_d} = -(d+1)$.

For a general case, you may observe that (as long as neither $y_i$ nor the denominator vanish) that
$$\frac{y_i'}{y_i} = (i+1) \frac{y_0'}{y_0}$$ therefore
$$y_i = a_i|y_0|^{i+1}$$
where $a_i$ shall be determined from the initial conditions. Substituting it back to the first equation gives
$$y_0' = -\frac{1}{\sum_0^d a_i |y_0|^i}$$
and, as long as $y_0 > 0$, one has
$$\sum_0^d\frac{a_i}{i+1}y_0^{i+1}(x) = C - x$$


text:
Q: Logstash - Add fields from the log - Grok I'm learning logstash and I'm using Kibana to see the logs. I would like to know if is there anyway to add fields using data from message property.
For example, the log is like this:
@timestamp:December 21st 2016, 21:39:12.444 port:47,144
appid:%{[path]} host:172.18.0.5 levell:level message:
{"@timestamp":"2016-12-22T00:39:12.438+00:00","@version":1,"message":"Hello","logger_name":"com.empresa.miAlquiler.controllers.UserController","thread_name":"http-nio-7777-exec-1","level":"INFO","level_value":20000,
"HOSTNAME":"6f92ae402cb4","X-Span-Export":"false","X-B3-SpanId":"8f548829e9d18a8a","X-B3-TraceId":"8f548829e9d18a8a"}

My logstash conf is like:
filter {
grok {
match => {
  "message" =>
  "^%{TIMESTAMP_ISO8601:timestamp}\s+%{LOGLEVEL:level}\s+%{NUMBER:pid}\s+---\s+\[\s*%{USERNAME:thread}\s*\]\s+%{JAVAFILE:class}\s*:\s*%{DATA:themessage}(?:\n+(?<stacktrace>(?:.|\r|\n)+))?$"
}
}
 date {
match => [ "timestamp" , "yyyy-MM-dd HH:mm:ss.SSS" ]
}
mutate {
remove_field => ["@version"]
add_field => {
  "appid" => "%{[path]}"
}
add_field => {
  "levell" => "level"
}

}
}
I would like to take level (in the log is INFO), and message (in the log is  Hello) and add them as fields.
Is there anyway to do that?

A: What if you do something like this using mutate:
filter {
  mutate {
    add_field => ["newfield", "%{appid} %{levell}"] <-- this should concat both your appid and level to a new field
  }
}

You might have a look at this thread.


text:
Q: C++ using v typedef typename Instead of using typedef typename for the iterator is it possible to use using keyword?
I tried using schedulable_ops_t::iterator = schedulable_ops_iterator_t; but I get an error  is not a base type for type.

A: This record
using schedulable_ops_t::iterator = schedulable_ops_iterator_t;

is incorrect. It seems you mean
using schedulable_ops_iterator_t = typename schedulable_ops_t::iterator;


text:
Q: Multer and ImageMagick with Express.js: upload, resize, reorient I have an Express application that gets an image from a user via a form. There are several things I need to do with the image, and as it gets more complex, I'm not sure how to handle it. It is a message board post where there are some required text fields and an optional image upload. I need to:

*

*Find the orientation of the image from EXIF data and reorient it if needed

*Save a copy of the original image to the server (done)

*Create a thumbnail of the image and save it to the server (done)

*Save the record to the database, whether or not there's an uploaded image (done)

I'm concerned about the order in which I'm doing things, wondering if there's a more efficient way. I know I can call upload inside the route instead of passing it in, but I'd like to not repeat myself when I save the record to the database, since I need to save it whether there's an image or not.
I have code that's working for the final 3 steps, but am open to suggestions on how to improve it. For the first step, I'm stumped at how to go about getting the orientation of the original and rotating it if needed. Is this something I need to do client-side instead? And how do I work it into the existing code?
Here's the code:
Setup
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads');
  },
  filename: function (req, file, cb) {
    var fileExt = file.mimetype.split('/')[1];
    if (fileExt == 'jpeg'){ fileExt = 'jpg';}
    cb(null, req.user.username + '-' + Date.now() + '.' + fileExt);
  }
})

var restrictImgType = function(req, file, cb) {

    var allowedTypes = ['image/jpeg','image/gif','image/png'];
      if (allowedTypes.indexOf(req.file.mimetype) !== -1){
        // To accept the file pass `true`
        cb(null, true);
      } else {
        // To reject this file pass `false`
        cb(null, false);
       //cb(new Error('File type not allowed'));// How to pass an error?
      }
};

var upload = multer({ storage: storage, limits: {fileSize:3000000, fileFilter:restrictImgType} });

In Route
router.post('/new',upload.single('photo'),function(req,res){
    var photo = null;
    var allowedTypes = ['image/jpeg','image/gif','image/png'];
    if (req.file){
            photo = '/uploads/' + req.file.filename;
            // save thumbnail -- should this part go elsewhere?
            im.crop({
              srcPath: './public/uploads/'+ req.file.filename,
              dstPath: './public/uploads/thumbs/100x100/'+ req.file.filename,
              width: 100,
              height: 100
            }, function(err, stdout, stderr){
              if (err) throw err;
              console.log('100x100 thumbnail created');
            });

            // I can get orientation here,
            // but the image has already been saved
            im.readMetadata('./public/uploads/'+ req.file.filename, function(err, metadata){
              if (err) throw err;
              console.log("exif orientation: " + metadata.exif.orientation);
            });

    }

    // Save it
    new Post({
        username: req.user.username,
        title: req.body.title,
        body: req.body.messagebody,
        photo: photo
    }).save(function(err){
        if (err){ console.log(err); }
        res.redirect('/messageboard');
    });
});

Thanks for your help


text:
Q: Redirect all HTTP/HTTPS requests Apache to a specific website and then back What I want to do (ALL THIS IS PERFORMED ON ONLY ONE SERVER);
(I'm working with example.com for not making any advertisement).
Redirect all incoming HTTP/HTTPS requests (Port 80 and 443) to a specific website, for example, filter.example.com. There I've made my own mechanism to filter malicious requests. After that, the requests should get back to the requested website.
My problem is, that every request is getting redirected back to the filter, so there's an endless loop.
Do you know any solution to that or maybe an alternative (Nginx)?
Here's the problem showed by the packet flow;
"User - Request = https://example.com" -> "Apache redirects it to = https://filter.example.com" -> "After getting filtered = https://example.com" -> "Apache is redirecting it back again."
I really hope you understand my problem.
Thank you.
EDIT:
This are my settings for the filter.example.com ServerName;
<VirtualHost *:80>
    ServerName filter.example.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
    ServerName filter.example.com
    RewriteEngine On
    DocumentRoot /var/www/filter/
    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/filter.example.com/cert.pem
    SSLCertificateChainFile /etc/letsencrypt/live/filter.example.com/chain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/filter.example.com/privkey.pem
    ErrorDocument 404 /error404.html
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</VirtualHost>

And here for my "real" website;
<VirtualHost *:80>
    ServerName example.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</VirtualHost>

<VirtualHost *:443>
    ServerName example.com
    RewriteEngine On
    DocumentRoot /var/www/html/
    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
    SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
    ErrorDocument 404 /error404.html
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</VirtualHost>

So, David wrote;
You will really end up in a redirect loop because the request 1 to www.example.com will redirect to filter.example.com and again to www.example.com endlessly.
To avoid this add a cookie/header to the incoming request from www.example.com in filter.example.com(of course, after completing the filter process) something like Filter: true, so you know this is already a filtered request and doesn't need to go to filter.example.com.
server {
    server_name filter.example.com;
    //logic to filter
    add_header 'passed_filter' 'true';
}

If you redirect logic to add a check to verify if header Filter: true exists, if not redirect to filter.example.com, if yes - skip redirect and follow the normal execution procedure.
//If the header is not set, then we understand that this request should be redirected to filter.example.com
if($sent_passed_filter ~= 'true') {
   //logic to redirect to filter
}

Is that Nginx, because I'm using Apache. Is there also a solution like that but for Apache?

A: You will really end up in a redirect loop, because the request 1 to www.example.com will redirect to filter.example.com and again to www.example.com endlessly.
To avoid this add a cookie/header to the incoming request from www.example.com in filter.example.com(of course, after completing the filter process) something like Filter: true, so you know this is already a filtered request and doesnt needs to go to filter.example.com.
server {
  server_name filter.example.com;
  //logic to filter
  add_header 'passed_filter' 'true';
}

In you redirect logic add a check to verify if header Filter: true exists, if not redirect to filter.example.com, if yes - skip redirect and follow the normal execution procedure.
//If the header is not set, then we understand that this request should
be redirected to filter.example.com
if($sent_passed_filter ~= 'true') {
   //logic to redirect to filter
}


text:
Q: Initializing tooltip with JQueryUI HTML:
<input type='text' id='uname' />

JS:
$( "#uname" ).tooltip({ content: "gggg" });

Result: nothing. No tooltip, no errors; What is wrong here?
Demo: http://jsfiddle.net/w97FA/
These are the resources/plugins I used:

*

*http://jqueryui.com/tooltip/

*http://api.jqueryui.com/tooltip/#option-content

A: Tooltip is placed as a title:
<input type='text' id='uname' title="gggg" />

http://jsfiddle.net/samliew/w97FA/2/
Otherwise, you have to initialize the element with empty title, in order to set it dynamically:
<input type='text' id='uname' title='' />

http://jsfiddle.net/samliew/w97FA/8/

A: As the API documentation for tooltip states, if you use the "content"-option, you also need to use the items-option - so the following code works:
$('#uname').tooltip({ content: "Awesome title!", "items":"input" })

However, if you don't need specific logic for the displayed content, or some sophisticated selection, the usage of the title-attribute might be simpler.

A:

USE JQUERY TOOLTIP  WITH CSS IN ASP.NET WEB APPLICATION.here we can also use css for defining style of tooltip.for full Example [check here][1]

A: I know that this post is old but I figured that this may help someone with a similar problem. I have been going through some older code that uses tool tips and they were not rendering when you initially hovered over the specified element. I tried a lot of different solutions and could not get it to render properly. I finally found the solution which worked for me which was to simply add a space in the blank title attribute. Once I did that everything work as is was supposed to:

//get all elements with classname tooltip
var toolTipElements = document.getElementsByClassName('tooltip');

//initialize tool tips using classname
if(toolTipElements){
  [].forEach.call(toolTipElements, function(element){
    $(element).tooltip({
      items: 'input',
      show: false,
      hide: false,
      track: true,
    });

    //add mouseover event listener to element that is supposed to display tool tip
    element.addEventListener('mouseover', function(){
      renderToolTip(element, true);
    });
  });
}

//render tool tip with message
function renderToolTip(element, withTracking){
  $(element).tooltip({
        items: 'input',
        show: false,
        hide: false,
        track: withTracking,
        content: function(callback){
          var toolTipMessage = 'Hello From ' + element.id +' Tool Tip!';
          callback(toolTipMessage);
        }
    });
}

<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

  <input id="inputElementWithOutSpace" class="tooltip" title=""/>

  <input id="inputElementWithSpace" class="tooltip" title=" "/>


text:
Q: Cannot send email using Django and NGINX Server (DigitalOcean droplet) I'm trying to send emails using Django without success.
I configured the settings.py file as below:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = "xxx@gmail.com"
EMAIL_HOST_PASSWORD = "xxx"
EMAIL_PORT = 587
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

I wrote a very simple view to test email sending:
def send_email_test(request):
        from_email = "xxx@gmail.com"
        to = "yyy86@gmail.com"
        send_mail("test oggetto", "test messaggio", from_email, [to], fail_silently=False)
        print "email sent"
        return render_to_response('index.html', context_instance=RequestContext(request))

On my server console I can see this log:
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Subject: test oggetto
From: xxx@gmail.com
To: yyy@gmail.com
Date: Thu, 09 Jul 2015 09:18:47 -0000
Message-ID: <20150709091847.28525.42497@MyServer>

test messaggio
-------------------------------------------------------------------------------
email sent

Anyway, I do not receive the mail on my email account.
Any suggestion?

A: Well, you're using the ConsoleBackend, which as the name implies simply prints the email to the console, for testing.
I expect you want django.core.mail.backends.smtp.EmailBackend, as described in the documentation.

A: It was an issue related to the security settings of my Google account.
If some of you has the same problem,  you need to allow access to your Google account using external application.
Use the following link:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Then click on Continue button and access your Google account using your application within the next 30 seconds.


text:
Q: VMWare server host agent service won't start I'm using VMWare Server 2.0 on Windows Server 2003 R2. Sometimes after restarting the host machine, the VMWare host agent service won't start due to an error.
This is the error messages from Event Viewer:

[Service control manager] Timeout
  (30000 milliseconds) waiting for the
  VMware Host Agent service to connect.
[Service control manager] The VMware
  Host Agent service failed to start due
  to the following error:  The service
  did not respond to the start or
  control request in a timely fashion.

I've set the service to automatically restart after subsequent failure using services.msc (using a 10 min. delay), but it still won't start. Only starting the service manually seems to work.
Has anyone experienced this before? What workarounds or fixes are there?
-- updated --
Here's a small vbs script that i use to check whether a service is running or not, and automatically starts it if it's not running. I use the scheduler to run this script every 15min.
strComputer = "."
strSvcName = "VMWareHostd"

set objWMI = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

set objService = objWMI.Get("Win32_Service.Name='" & strSvcName & "'")

If objService.State= "Stopped" Then
    call SendEmail("servicescheck@pc.local","admin@pc.local","Service X stopped","")
    objService.StartService()
End If

Private function SendEmail(From, Destination, Subject, Textbody)

    sch = "http://schemas.microsoft.com/cdo/configuration/"

    Set objEmail = CreateObject("CDO.Message")
    Set objCdoConfig = CreateObject("CDO.Configuration")

    With objCdoConfig.Fields
        .Item(sch & "sendusing") = 2 ' cdoSendUsingPort
        .Item(sch & "smtpserver") = "127.0.0.1"
        .update
    End With

    with objEmail

        set .Configuration = objCdoConfig

        .From = From
        .To = Destination
        .Subject = Subject
        .Textbody = Textbody

    end with

    call objEmail.Send

end function

--

A: create a scheduled task to run on startup that does
sc start vmware-service etc, or schedule a task to run every minute and try and start the task.
VMware server 2.0 sucks.
VMware server 1.0 was and is great.


text:
Q: Backpropagation error : conceptual or programing? I wrote the following backpropagation algorithm to model the two input identity function
clc
% clear

nh = 3;              % neurons in hidden layer
ni = 2;              % neurons in input layer

eta = .001;          % the learning rate
traningSize =100;

for x=1:traningSize
    input   = rand(traningSize,ni);
    test    = input;
end

nk = size(test,2);    % neurons in output layer

b1 = rand(1,nh);%+ .5;
b2 = rand(1,nk);%- .5;
w1 = rand(nh,ni) + .5;
w2 = rand(nk,nh) - .5;

figure
hold on;

for iter = 1 :5000
    errSq = 0;
    for x = 1: traningSize

        a0      = input(x,:);
        ex      = test(x,:);

        [a1, a2]= feedForward(a0,w1,w2,b1,b2);

        del2    = (a2-ex) .* (1-a2) .* (a2);
        del1    = (del2 * w2) .* (1-a1) .* (a1);

        delB2   = del2;
        delB1   = del1;

        delW2   = zeros(nk,nh);
        for i = 1:nh
            for j = 1:nk
                delW2   = a1(i) * del2(j);
            end
        end
        for i = 1:ni
            for j = 1:nh
                delW1   = a0(i) * del1(j);
            end
        end

        b2 = b2 - eta * delB2;
        b1 = b1 - eta * delB1;

        w2 = w2 - eta * delW2;
        w1 = w1 - eta * delW1;

        errSq = errSq + sum(a2-ex) .* sum(a2-ex);

    end

cost = errSq /(2 * traningSize);
plot(iter,cost,'o');

if cost < 0.005
    cost
    break
end

end
cost

The feedForward function :
function [a1, a2]  = feedForward(a0,w1,w2,b1,b2)

    z1      = a0 * w1' + b1;
    a1      = sig(z1);
    z2      = a1 * w2' + b2;
    a2      = sig(z2);

end

The cost function plot

Now what am i messing up ?
Is it some programmatic error that have escaped my notice ?
or am I implementing the algorithm wrongly?
when I test the resulting weights the calculated cost is as trained
but the results are completely wrong
Blue > expected output ; red > output of neural network

also why does the cost value sometimes  rises before decreasing (like in figure 1)

A: As it turn out I needed to correct a programing bug;
    delW2   = zeros(nk,nh);
    for i = 1:nh
        for j = 1:nk
            delW2(j,i)   = a1(i) * del2(j);   % forgot the index for delW2
        end
    end
    delW1   = zeros(nh,ni);                   % initilize delWI1 (although this is optional)
    for i = 1:ni
        for j = 1:nh
            delW1(j,i)   = a0(i) * del1(j);   % forgot the index for delW1
        end
    end

And eliminate the sigmoid function from the output layer. ie make a linear output layer to get acceptable results.
I'm not sure why the linear output layer is strictly required though and would like comments on that.


text:
Q: How to copy a red-black tree, and what should its allocator be Q #2 is renewed. Please answer new Q #2!  --Dannyu NDos, 2017 Jan 17
I've been making an associative container named DRV, which represents a finite discrete random variable. It is a red-black tree. I got helps from standard std::map, but I also had confusion from it.
Q #1. How its copy ctor has O(n) time complexity? Shouldn't it be O(n log n)? My DRV's copy ctor has O(log n), using std::async, though.
Old Q #2. Why its default allocator is std::allocator<value_type>? Shoudn't it allocate the container's internal node type? In that case, the values won't need to be dynamically allocated individually.
New Q #2. Given that Alloc is the allocator type for the container, what allocator must the container hold, Alloc or typename std::allocator_traits<Alloc>::template rebind_alloc</*the type of the node*/>?

A: *

*Copy constructor does not need to sort, it just needs to copy N nodes thus O(N)

*std::allocator<value_type> is "rebound" (search for "rebind" here) inside to allocate map nodes (value + tree wiring data)

A: My own answer to question #1: I did this like this:
1. Copy the (container size / 2) elements at the beginning recursively, with color all black.
2. Copy the following element, which is the centermost element and will be the root element, with color black.
3. Copy the remaining element at the end recursively, with color all black.
4. Connect the element copied in 2. with the root element among the elements copied in 1.
5. Connect the element copied in 2. with the root element among the elements copied in 3.
6. Paint the deepest elements red.
For example: http://imgur.com/gallery/tUtoK
This will make a perfectly balanced red-black tree in O(n) time.
And even if I parallelize this using std::async, it still has O(n) time complexity, due to the Amdahl's Law.
Here is the implementation:
/* includes... */
template <class T, class Comp = std::less<T>, class Alloc = std::allocator<T>> class set { // A red-black tree, motivated from std::set
public:
    /* typedefs... */
protected:
    typedef RedBlackTreeNode<T> Nodev; // The node type
    typedef Nodev *pNodev; // The pointer to node type
    typedef typename std::allocator_traits<Alloc>::template rebind_alloc<Nodev> Rebounda; // Rebound allocator type
    typedef std::allocator_traits<Rebounda> Reboundat; // Rebound allocator traits
    mutable ListNode_e endn; // The past-the-end node
    size_type sz; // Size
    value_compare comp; // comparator
    Rebounda alloc; // allocator
    pNodev initp() const noexcept { // the pointer to the node at the end
        return static_cast<pNodev>(endn.pre);
    }
    void partial_clear(const_iterator i) noexcept { // Destructs the node at i and after
        while (cend() != i) {
            pNodev p = static_cast<pNodev>(i++.refer);
            Reboundat::destroy(alloc, p);
            Reboundat::deallocate(alloc, p, 1);
        }
    }
    /// partial_copy_Lvalue, partial_assign_Lvalue
    /// @steps
    ///    1. Copy the (container size / 2) elements at the beginning recursively, with color all black.
    ///    2. Copy the following element, which is the centermost element and will be the root element, with color black.
    ///    3. Copy the remaining element at the end recursively, with color all black.
    ///    4. Connect the element copied in 2. with the root element among the elements copied in 1.
    ///    5. Connect the element copied in 2. with the root element among the elements copied in 3.
    ///    6. Paint the deepest elements red.
    /// @param
    ///    size: the size of the container
    ///    other_i: the iterator refering the element to be copied in 2.
    /// @return
    ///    pNodev: the pointer to the root of the (partial) tree
    ///    size_type: the depth of the shallowest leaf node of the (partial) tree
    std::pair<pNodev, size_type> partial_copy_Lvalue(size_type size, const_iterator &&other_i) {
        if (size == 0)
            return std::make_pair(nullptr, 0);
        else {
            std::pair<pNodev, size_type> l = partial_copy_Lvalue(size >> 1, std::move(other_i)); /// 1.
            Reboundat::construct(alloc, Reboundat::allocate(alloc, 1), endn, Nodev::color_t::black, *other_i++); /// 2.
            pNodev resultp = initp();
            std::pair<pNodev, size_type> r = partial_copy_Lvalue(size - (size >> 1) - 1, std::move(other_i)); /// 3.
            resultp->left = l.first; /// 4.
            resultp->right = r.first; /// 5.
            if (resultp->left)
                resultp->left->parent = resultp; /// 4.
            if (resultp->right)
                resultp->right->parent = resultp; /// 5.
            if (l.second < r.second && resultp->right)
                resultp->right->colorleavesred(); /// 6, case 1
            else if (l.second > r.second && resultp->left)
                resultp->left->colorleavesred(); /// 6, case 2
            return std::make_pair(resultp, std::min(l.second, r.second) + 1);
        }
    }
    void copy(const set &other) { // Copies the nodes from other. Precondition : this is empty
        if (!other.empty())
            partial_copy_Lvalue(other.sz, other.cbegin());
    }
    std::pair<pNodev, size_type> partial_assign_Lvalue(size_type size, ListIt<T> &&this_i,
        const_iterator &&other_i, const const_iterator &other_cend) {
        if (size == 0) {
            if (other_i == other_cend)
                partial_clear(const_iterator(this_i.refer));
            return std::make_pair(nullptr, 0);
        } else {
            std::pair<pNodev, size_type> l = partial_assign_Lvalue(size >> 1, std::move(this_i), std::move(other_i), other_cend); /// 1.
            std::pair<pNodev, size_type> r;
            pNodev resultp;
            if (this_i.refer == cend().refer) {
                Reboundat::construct(alloc, Reboundat::allocate(alloc, 1), endn, Nodev::color_t::black, *other_i++); /// 2, case 1
                resultp = initp();
                r = partial_copy_Lvalue(size - (size >> 1) - 1, std::move(other_i)); /// 3, case 1
            } else {
                resultp = static_cast<pNodev>(this_i.refer);
                static_cast<pNodev>(this_i.refer)->parent = nullptr;
                static_cast<pNodev>(this_i.refer)->color = Nodev::color_t::black;
                *this_i++ = *other_i++; /// 2, case 2
                r = partial_assign_Lvalue(size - (size >> 1) - 1, std::move(this_i), std::move(other_i), other_cend); /// 3, case 2
            }
            resultp->left = l.first; /// 4.
            resultp->right = r.first; /// 5.
            if (resultp->left)
                resultp->left->parent = resultp; /// 4.
            if (resultp->right)
                resultp->right->parent = resultp; /// 5.
            if (l.second < r.second && resultp->right)
                resultp->right->colorleavesred(); /// 6, case 1
            else if (l.second > r.second && resultp->left)
                resultp->left->colorleavesred(); /// 6, case 2
            return std::make_pair(resultp, std::min(l.second, r.second) + 1);
        }
    }
public:
    /* constructors... */
    virtual ~set() {
        clear();
    }
    set &operator = (const set &other) {
        sz = other.sz;
        if (std::allocator_traits<Alloc>::propagate_on_container_copy_assignment::value && alloc != other.alloc) {
            clear();
            alloc = other.alloc;
            copy(other);
        } else
            partial_assign_Lvalue(other.sz, ListIt<T>(cbegin().refer), other.cbegin(), other.cend());
        return *this;
    }
    /* ... */
};

See also: How is allocator-aware container assignment implemented?


text:
Q: Using cURL, explode and foreach to check for 403 response code Okay so I'm making a script to check if given website(s) return a 403 or not. I joined some bits and pieces to get this working and it does work if I just check a single website at a time but it doesn't not work with multiple websites.
$url = $_POST['site'];

$many_urls = explode(",", $url);

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);

/* Check for 403 (forbidden). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

foreach ($many_urls as $urls)
{
    if($httpCode == 403) {
        echo "
$url is Forbidden.
";
    } else echo "
$url Works.
";
}

curl_close($handle);

So if I type in for example: google.com,youtube.com,forbiddenwebsite.com
It should return:
google.com Works youtube.com Works forbiddenwebsite.com is Forbidden (on different lines ofcourse)
I'm pretty sure there's a problem with foreach part.
Any help would be appreciated. Thanks.

A: if you're going to be checking each url independently when in list form, you'll need to have that curl in the loop. otherwise you're checking the headers for "google.com,youtube.com,forbiddenwebsite.com", which isn't a valid address. try this:
/* exploding the url list will give an array with 1 item in the case of only 1 url */
$urls = explode(',', $_POST['site']);

/* wrap the whole thing in the loop, check each url individually */
foreach($urls as $url){

    $handle = curl_init($url);
    curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

    /* Get the HTML or whatever is linked in $url. */
    $response = curl_exec($handle);

    /* Check for 403 (forbidden). */
    $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);

    if($httpCode == 403) {
        echo "
$url is Forbidden.
";
    } else echo "
$url Works.
";

    curl_close($handle);
}

You'll probably want to add some sort of check for the case of an empty string passed in the post vars too.


text:
Q: How to format output in R containing both integers and real numbers? The output of my code is following:
print(c(ax,bx,cx,dx))
>[1] 232.0000 2.0000 0.6578 1.2356

where in all the cases, the first two numbers are integers, and the rest are real. What should I include in the print statement, such that the output is:
>[1] 232 2 0.6578 1.2356

I know this must be very simple, but somehow I could not figure this out. Thanks for your help :)

A: Thanks to @user2554330, for mentioning using noquote like this:
ax = 232.0000
bx = 2.0000
cx = 0.6578
dx = 1.2356
print(noquote(as.character(c(ax,bx,cx,dx))))
#> [1] 232    2      0.6578 1.2356

Created on 2022-07-24 by the reprex package (v2.0.1)
You could use as.character to remove the trailing zeros like this:
ax = 232.0000
bx = 2.0000
cx = 0.6578
dx = 1.2356
print(as.character(c(ax,bx,cx,dx)))
#> [1] "232"    "2"      "0.6578" "1.2356"

Created on 2022-07-24 by the reprex package (v2.0.1)

A: While I like noquote, replacing all trailing zeros will have the same effect:
sub("0+$", "", as.character(c(ax,bx,cx,dx)))

[1] "232"    "2"      "0.6578" "1.2356"


text:
Q: Fully expanding header macros to get their numeric values for external use I have a complicated header file with lots of dependencies on other earlier-defined macros that layout the memory map of an embedded system. For example:
#define RAM_BASE           (0x40000000)
#define RAM_SIZE           (0x10000000)
#define SECURE_RAM_SIZE    (0x00200000)
#define SECURE_RAM_BASE    (RAM_BASE + RAM_SIZE - SECURE_RAM_SIZE)

For many reasons I need the result of SECURE_RAM_BASE outside of the compiled program. So, my thought was to use the C preprocessor to expand these macros and awk the result as needed. However, the macro expansion with cpp -dD <file> was exactly as shown above (less extra white space).
I was expecting something like this:
RAM_BASE           0x40000000
RAM_SIZE           0x10000000
SECURE_RAM_SIZE    0x00200000
SECURE_RAM_BASE    0x4fe00000

But it seems (at least as far as I interpret the man page) that such expansion may only be accessible when the macros are actually used in code. Even still, the following code-use:
printf("Base: 0x%x\n", SECURE_RAM_BASE);

Expands to:
printf("Base: 0x%x\n", ((0x40000000) + (0x10000000) - (0x00200000)));

Is there a way to produce a 'fully-computed' expansion result using the C preprocessor?

A: Is there a way to produce a 'fully-computed' expansion result using the C preprocessor?
Why, yes, there is.  (Incidentally, boost preprocessor solves a similar problem using its concept of slots; but the solution here is more tailored to this use case and hex outputs).  Comments to your question already lay the ground rules... C preprocessor macro expansion cannot evaluate expressions.  But C preprocessor conditional directives can.  Conditional directives don't reduce expressions, but with a bit of work you can get the CPP to coax the results out.  Since your goal is to simply get results out, you're not actually limited by macro evaluation.
High level approach
Given those constraints, you want a file devoted to evaluating and printing an expression (let's say it's called print_expression.h).  The evaluation should be performed by an include directive; i.e., #include "print_expression.h"; this way, we can use the one CPP tool capable of evaluating expressions (viz, conditional directives) to do so.  We can simply have this file evaluate the expression EXPRESSION; you can #define this before the include.  Since you're going to reuse this for multiple macros that expand to expressions, we may want to preface the evaluation result with EXPRESSION_LABEL, which you can define as something.  Since this is a preprocessor program rather than a "normal" header, it can helpfully clean up after itself and skip inclusion guards so you can immediately reuse it.
Driving the solution
So for now ignore the details, and assume this just works... to generate something akin to the outputs you want on your sample header, you would include the header, and then need to pump this utility as follows:
#define EXPRESSION_LABEL 8RAM_BASE
#define EXPRESSION RAM_BASE
#include "print_expression.h"
#define EXPRESSION_LABEL 8RAM_SIZE
#define EXPRESSION RAM_SIZE
#include "print_expression.h"

...and so on.  But you don't need this file (assuming your cpp takes stdin); you mentioned awk, so assuming you also have sed and bash (and maybe a gnu like -P flag to your cpp to strip #line directives and clutter):
(echo '#include "complicated_header.h"' ;
 echo RAM_BASE,RAM_SIZE,SECURE_RAM_BASE,SECURE_RAM_SIZE | \
sed -e 's/,/\n/g' -e 's/.*/#define EXPRESSION_LABEL 8&\n#define EXPRESSION &\n#include "print_expression.h"/g' ) | cpp -E -P

Something like this is probably what you want to do, since from your question it sounds like you're going to do more processing on the outputs as well given specific extracted evaluated values.  Note that I'm prepending a 8 to the expression labels; this in CPP-ese makes it a "pp-number" that can't possibly evaluate... you can strip it out on the output (maybe with a cut -c 2-).
The reusable calculator (by description)
To make print_expression.h isn't too complicated, but it's going to be a big file, so I'll just outline the concept rather than inline it here (but see below).  I'll assume you want your output to be an 8 nibble hex number in hex format.  What you want to do then is to define a macro for each nibble in this hex number, to be pasted together when producing the output; the definition of each nibble macro will be given by evaluating a #if/#elif/#else/#endif chain that specifically checks the value for that nibble.  To make this a bit easier and repetitive (so you can copy/paste/replace it into being), you can have a helper macro evaluate EXPRESSION and shift the nibble in.  So to get you started, your file looks something like this:
#define RESULT_NIBBLE(NDX_) (((EXPRESSION)>>(NDX_*4))&0xF)
#if   RESULT_NIBBLE(7)==0xF
#define RESULT_NIBBLE_7 F
#elif RESULT_NIBBLE(7)==0xE
#define RESULT_NIBBLE_7 E
#elif RESULT_NIBBLE(7)==0xD
#define RESULT_NIBBLE_7 D
...
#elif RESULT_NIBBLE(7)==0x1)
#define RESULT_NIBBLE_7 1
#else
#define RESULT_NIBBLE_7 0
#endif

Following this, create a chain to define RESULT_NIBBLE_6 down to RESULT_NIBBLE_0.  Once you finally get to the end, you just need to paste all of this onto 0x with an indirect paste, dump the results by invoking the macros, then clean up to make yourself ready for the next usage:
#define HEXRESULT(A,B,C,D,E,F,G,H) HEXRESULTI(A,B,C,D,E,F,G,H)
#define HEXRESULTI(A,B,C,D,E,F,G,H) 0x ## A ## B ## C ## D ## E ## F ## G ## H

EXPRESSION_LABEL HEXRESULT(RESULT_NIBBLE_7,RESULT_NIBBLE_6,RESULT_NIBBLE_5,RESULT_NIBBLE_4,RESULT_NIBBLE_3,RESULT_NIBBLE_2,RESULT_NIBBLE_1,RESULT_NIBBLE_0)

#undef HEXRESULTI
#undef HEXRESULT
#undef RESULT_NIBBLE_7
#undef RESULT_NIBBLE_6
#undef RESULT_NIBBLE_5
#undef RESULT_NIBBLE_4
#undef RESULT_NIBBLE_3
#undef RESULT_NIBBLE_2
#undef RESULT_NIBBLE_1
#undef RESULT_NIBBLE_0
#undef EXPRESSION
#undef EXPRESSION_LABEL

Brief demo
This demo emulates the solution good enough for single-file online demonstration.  Note that lines 27-317 effectively is a viable working print_expression.h in full.

A:
Is there a way to produce a 'fully-computed' expansion result using the C preprocessor?

No it is not possible. The C preprocessor only calculates anything in expressions after #if and #elif. In simple terms, the C preprocessor works in most cases as a string replacement. It sees SECURE_RAM_BASE it substitutes it for (RAM_BASE + RAM_SIZE - SECURE_RAM_SIZE) and the substitutes it for ((0x40000000) + (0x10000000) - (0x00200000)). No calculation is done except in #if and #endif, only string substitution.
That said..., obviously you can:
#define RAM_BASE           (0x40000000)
#define RAM_SIZE           (0x10000000)
#define SECURE_RAM_SIZE    (0x00200000)
#define SECURE_RAM_BASE_CALC    (RAM_BASE + RAM_SIZE - SECURE_RAM_SIZE)

#if SECURE_RAM_BASE_CALC == 1
#define SECURE_RAM_BASE 1
#elif SECURE_RAM_BASE_CALC == 2
#define SECURE_RAM_BASE 2
#elif SECURE_RAM_BASE_CALC == 3
#define SECURE_RAM_BASE 3
// ...
// ca. about 0x4fe00000 * 2 = 2680160256 =~ 2 bilion! more lines...
// ...
#elif SECURE_RAM_BASE_CALC == 0x4fe00000
#define SECURE_RAM_BASE 0x4fe00000
#endif

But this is way overkill.

A: *

*You could write a simple C program that includes that header(s) and prints the result.

*You could even let it print the linker command line(s).

*Finally you could let this tiny program execute the command(s).
Now it's up to you with what stage you'll be most happy.


text:
Q: A menu of Linux commands (e.g ls, ipconfig etc) that forks and uses execl to run the commands as a child process I have been given some code and I need to adapt this to show a menu of Linux commands and when a command is selected, the program should fork and use execl to run the commands as a child process and show its PID. I'm new to C so this I've been struggling so far :/
#include <unistd.h>
#include <stdio.h>
#include "sys/types.h"
#include <sys/wait.h>
int main(){

pid_t pid;
    int status = 0;
    int i;
    pid= fork() ;
        if(pid!=0) {
                wait(&status);
                printf ( " I am the parent my PID is %d, myPPID is %d, \n ",getpid(),getppid());
                printf( "Mychild process has finished. \n ");
        }else {
        printf ( " I am the child , my PID is %d , my PPID is %d \n",getpid(),getppid());
        sleep(2);
        execl ( "/bin/ls",".",(char*)0);
        printf( "Can you read this ?\n " ) ;
        }
return 0;
}

A: before calling
fork()

the code should display the menu, probably via some calls to printf(),
then input the users selection
then use that selection, probably via a switch() statement, to place the appropriate text into an
char *args[] variable

then use that args[] variable when calling execl()


text:
Q: MongoDB Not equal isn't the opposite of equal If I run the following:
db.restaurants.find({'grades.grade': 'A'}, {'grades.grade':1})

Then I return all the documents that have a grade with an 'A'.  That being, any document with at least one 'A' but there may be other grades.  e.g:
{
    "_id" : ObjectId("56c9a7038cc7f52917313091"),
    "grades" : [
        {
            "grade" : "A"
        },
        {
            "grade" : "B"
        },
        {
            "grade" : "A"
        },
        {
            "grade" : "A"
        }
    ]
}

If I use the $ne operator:
db.restaurants.find({'grades.grade': {$ne: 'A'}}, {'grades.grade':1})

Then I return all the documents that have all grades not equal to 'A'.
e.g.
{
    "_id" : ObjectId("56c9a7038cc7f52917313245"),
    "grades" : [
        {
            "grade" : "B"
        },
        {
            "grade" : "B"
        },
        {
            "grade" : "C"
        },
        {
            "grade" : "B"
        },
        {
            "grade" : "B"
        }
    ]
}

Why does $ne match all grades, but equal to match any grade?

NB: The same behaviour seems to be true in $in ans $nin.  $in matches any document whereas $nin matches all documents.
NB2: $not exhibits the behaviour too.

A: I understand your question, and I agree that from a functional perspective you are right: There should be a way to "negate" equals in a way that is logically "give me anything that contains something that is not A".
But I think the the way Mongo works here makes sense from a formal logic perspective. If you think about it logically, then the query db.restaurants.find({'grades.grade': 'A'}) returns
(grades[0].grade == 'A' || grades[1].grade == 'A' || grades[2].grade == 'A'|| grades[3].grade == 'A'...)

Basic formal logic says that the negation of the above statement is
(grades[0].grade != 'A' && grades[1].grade != 'A' && grades[2].grade != 'A'&& grades[3].grade != 'A'...)

Which is exactly what you got by using $ne.

A: This is a consequence of basic De Morgan logical negation.
NOT (A AND B) means (NOT A) OR (NOT B)
This can be directly translated to set theory, where disjunction (OR) means union and conjunction (AND) means intersection.
When you apply equals you're asking for ANY value that matches(disjunction). But when you negate that, you negate every single match as per De Morgan.


text:
Q: Displaying the names and times of the first and second winners of a marathon I would like your help here guys
/**
 * In this assignment I am supposed to display the names and times of the first and second winners (2 best times) of a marathon
 * But I am struggling with the second one
 */
public class MitAssignment3Chapter7 {
public static void main(String args[]){

    String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
    int[] timeInMinutes = {40,50,76,56,62};

    int index = 0;
    int a = 0;
    int first = timeInMinutes[1];

    for (a = 0 ; a < timeInMinutes.length; a++){
        if ( first > timeInMinutes[a]){
            index = a;
            first = timeInMinutes[index];
        }
       // if (first < timeInMinutes[a] && timeInMinutes[a])  Trying to do the second here
    }
    System.out.println("The winner of the marathon is: "+runners[index]+" with "+timeInMinutes[index]+" minutes");

}

}

A: using other collections would be easy.. but you can do it with simple arrays also.. not only second one, you can find all ranks of runners by sorting arrays.. check this code..
     public static void main(String args[]) {
        String runners[] = { "Gene", "Elvis", "Presley", "Felicity", "Welcome" };
        int[] timeInMinutes = { 40, 50, 76, 56, 62 };
        int a = 0;
        int tempTime = 0;
        String tempRunner = "";
        for (int i = 0; i < timeInMinutes.length; i++) {
            for (int j = i + 1; j < timeInMinutes.length; j++) {
                if (timeInMinutes[i] > timeInMinutes[j]) {
                    tempTime = timeInMinutes[i];
                    timeInMinutes[i] = timeInMinutes[j];
                    timeInMinutes[j] = tempTime;

                    tempRunner = runners[i];
                    runners[i] = runners[j];
                    runners[j] = tempRunner;
                }
            }
        }
        for (int index = 0; index < runners.length; index++)
            System.out.println("Rank " + (index+1) + ": " + runners[index] + " with " + timeInMinutes[index] + " minutes");
    }

A: You can find the winner first, after you had found out winner, take winner out of your time array and find the fastest people in your current array, it will be the second player.

A: You can create a new class to hold result time and the name. Implement compareTo method for this class. Populate new List with all the results and sort the one. Now it's possible to get any Nth result(time and name).
static class Result implements Comparable<Result> {
    private final int time;
    private final String name;

    Result(int time, String name) {
        this.time = time;
        this.name = name;
    }

    int getTime() { return time; }

    String getName() { return name; }

    @Override
    public int compareTo(Result o) {
        return Integer.compare(time, o.time);
    }
}

public static void main(String args[]){
    String runners[] = {"Gene","Elvis","Presley","Felicity","Welcome"};
    int[] timeInMinutes = {40,50,76,56,62};

    List<Result> results = new ArrayList<>(runners.length);
    for (int i = 0; i < runners.length; i++) {
        results.add(new Result(timeInMinutes[i], runners[i]));
    }

    Collections.sort(results);

    Result second = results.get(1);
    System.out.println("Second winner: " + second.getName() + "; Time: " + second.getTime());
}


text:
Q: Converting HTML page into image using URL I am doing one project on django-platform.
I have one question to ask which I am finding it for long time  :
Is there any method to convert html page like www.google.com  that convert into image directly and save in project directory.
I need to write code to do this.
Let's have a url (say :
/employee/{emp_code}/certificate/{id}/download

) . On hitting this URL , This should convert into image.
EDITED :
Simply I want to implement this : http://www.verypdf.com/online/url-to-image-converter.php
http://www.page2images.com/free_convert_website_url_to_images_in_batch


text:
Q: How to set up unique behaviours with Scriptable Objects (Skills/ability system) I want to create a complex Skill/Ability system on Unity, that may have some conditions to trigger unique behaviours, and other things. For example, I have a skill called Shatter, that does damage and have some conditions: If the enemy is currently bleeding, applies Armor Break. If the enemy armor is broke, applies Bleeding. If affected by both, apply more stacks of Bleeding. That's just an example of which type of behaviour/conditions i wish my skills to have.
I already created one and made it work with bunchs of prefabs, instantiation and monobehaviour/inheritance chaos, but it showed me some problems that I wasn't able to solve, so now I'm giving a try to Scriptable Objects and I decided to rewrite the game for now.
This is what I used to make Shatter (inherits from WarriorSkill, that inherits from Skill) works with monobehaviour/inheritance (Conditions are just debuffs in this example):
public class Shatter : WarriorSkill, IConditionable
{
    public GameObject armorBreakCondition, bleedingCondition, hemorrhageCondition, coagulationCondition;

    [SerializeField] double damage;

    public double Damage { get { return damage; } private set { damage = value;}

    public override void OnActivate()
    {
        base.OnActivate();
        target.TakeDamage(Damage);

        bool bleeding = false;
        bool armorBreak = false;

        foreach(Transform condition in target.conditionsPanel.transform)
        {
            if (condition.GetComponent<Condition>().GetType() == typeof(Bleeding))
                bleeding = true;

            if (condition.GetComponent<Condition>().GetType() == typeof(CArmorBreak))
                armorBreak = true;
        }

        if(bleeding && armorBreak)
        {
            FindObjectOfType<Bleeding>().AddStacks(4);
        }
        else if(armorBreak)
        {
            OnCondition(bleedingCondition);
        }
        else if(bleeding)
        {
            OnCondition2(armorBreakCondition);
        }
    }

    private void OnCondition(GameObject condition)
    {
        condition.GetComponent<Bleeding>().hemorrhageCondition = hemorrhageCondition;
        condition.GetComponent<Bleeding>().coagulationCondition = coagulationCondition;
        target.AddCondition(condition);
    }

    private void OnCondition2(GameObject condition)
    {
        condition.GetComponent<CArmorBreak>().armorBreak = 0.25f;
        condition.GetComponent<CArmorBreak>().duration = 50;
        target.AddCondition(condition);
    }
}

With that, I needed to adapt to some prefab instantiation/serialization limitations, like, I wasn't able to just drag n' drop the hemorrhage and coagulation prefabs to the Bleeding prefab, because when I instantiate it, it shows Empty. Those "bad solutions" I've got didn't make me satisfied, and more problems were showing up as I write the code. So, now I'm trying to fix and improve my code with scriptable objects. It's important to note that every skill has some really special features/conditions and unique behaviours like that Shatter ability. I may describe more examples if necessary.


text:
Q: Deducing formulas of analytic geometry The way I learned analytic geometry in highschool, I was given a lot of formulas and shown what they do and maybe, just maybe, why they are accurate. So, an ellipse was defined as being a curve that has the formula $\frac{x^2}{a^2} + \frac{y^2}{b^2} = c^2$ rather than a curve in the plane around two focal points such that the sum of the distances from the focal points to the curve is constant. The latter was presented as a property of the former.
I believe that to properly learn mathematics, you have to do what is done in later courses like real analysis and abstract algebra. That is, you start off with some definitions, and then you deduce the rest. So, in my quest to relearn mathematics in a rigorous way, I have to relearn analytic geometry as well.
I thus have to ask for recommendations for books about analytic geometry.

A: I'll suggest you a slogan : "Back to basic !"
You have to see Hilbert's axioms (1899) :

*

*David Hilbert, The Foundations of Geometry (Engl.transl.1902)

complemented with e.g.

*

*Robin Hartshorne, Geometry : Euclid and Beyond (2000).

The "ingredient" for a rigorous treatment of analytical geometry are :

*

*the axiomatization of euclidean geometry

*its model in term of the field of real numbers $\mathbb R$.


text:
Q: Converting and Subtracting Two Dates I'm trying to get the numeric difference between two dates.  (Ex:  11/30/2018 - 11/05/2018 = 25)
One of the dates (@EndOfMonth) represent the last day of the prior month and is being converted into a 'yyyymmdd' format
BEGIN
DECLARE @EndOfMonth AS VARCHAR(10)
SET @EndOfMonth = (SELECT CONVERT(VARCHAR, DATEADD(m, DATEDIFF(m, 0, DATEADD(m, 1, DATEADD(MM, -1, @maxDwdate))), -1), 112))

The second date that I'm looking to subtract from @EndOfMonth, is a field named "DUEDATE" and it's in a 'mm/dd/yyyy' format.

A: Assuming that you have a valid reason to convert the date to a string, and that you cannot change that logic: declare yourself a variable to store the intermediate results of the date arithmetic before you convert it to a string, then you can easily get the difference between the two dates:
DECLARE @eom DATE
      = DATEADD(m, DATEDIFF(m, 0, DATEADD(m, 1, DATEADD(MM, -1, @maxDwdate))), -1);
DECLARE @EndOfMonth AS VARCHAR(10)
    SET @EndOfMonth = (SELECT CONVERT(VARCHAR, @eom, 112))
 SELECT DATEDIFF(DAY, @eom, DUTEDATE) AS DAYS
   FROM t; -- replace with actual table name.

A: This is fairly simple to achieve, the below example code shows how to do this (replace the DueDate variable with your DUEDATE column from your table. Basically, you use DATEDIFF to get the start of the month for DUEDATE, add one month to this date then substract one day. This will always give you the EoM date for the DUEDATE month, regardless fo the number of days in that month.
You can then simply do a DATEDIFF to work out the number of days between the two dates. SQL Server will implicitly convert yyyymmdd into a DATETIME value for the calculation, but if its possible, you should avoid converting the EndOfMonth variable to a string for performance reasons.
DECLARE @EndOfMonth VARCHAR(10),
    @DueDate DATETIME = '12/14/2018'

SELECT @EndOfMonth = CONVERT(VARCHAR(10), DATEADD(d, -1, DATEADD(m, 1, DATEADD(m, DATEDIFF(m, 0, @DueDate), 0))), 112)

SELECT DATEDIFF(d, @DueDate, @EndOfMonth)


text:
Q: Creating interface with generic methods I am trying to design an interface, so that it has a generic type of id and a generic method that returns the type of the class that implements this interface. For example:
public interface IEntity <IDType, MethodReturnType>
{
     IDType ID {get; set;}
     MethodReturnType Get();
}

public class Model : IEntity<int, Model>
{
     int ID {get; set; }
     Model Get() { // do something }
}

My question is, it seems silly to put in Model as the second type parameter of IEntity, because I am already in a Model's class, it should be some intelligence way to figure out what type it is (although using generic type requires it to be determined before compile time).
Is it any other solution that can help me to get rid of the Model type while retain the Get method definition in the interface?

A: You can determine the inherited class type with this.GetType() but that will not allow you to create generic functions/parameters/etc as you are doing.
So to your answer, no, you can't unless you will not use that type in any way (you can still get the base type of the class and use it but cannot set it as return type/param type/etc).

A: In this context, there are two typical ways to go about designing your classes and interfaces. I'll stray slightly from your exact example to try to make the answer more general.
Which option to choose really depends on how you want your classes and interfaces to be used.
Option 1
Make your interface generic, so that the interface members have knowledge of the exact type.
public interface IEntity<TDescription>
{
    TDescription Get();
}

public class MyModel : IEntity<MyDescription>
{
     MyDescription Get() { ... }
}

public class MyDescription { ... }

This means that when you use your interface IEntity<TDescription> you need to know TDescription at the time of use. The benefit is that you get more compile-time type checking.
Option 2
Do not make your interface generic and instead have your interface members use interfaces as well.
public interface IEntity
{
    IDescription Get();
}

public interface IDescription { ... }

public class MyModel : IEntity
{
    MyDescription Get() { ... }
    IDescription IEntity.Get() { return this.Get(); }
}

public class MyDescription : IDescription { ... }

This is more flexible, but it also means less compile-time type checking.


text:
Q: Getting more detailed error info from Python lxml library I'm using lxml to validate XML files against XSDs. Works fine. However, when there's a missing element, it doesn't provide info on exactly which element is missing. I.e. starting with a valid XML that validates against an XSD, if you then remove one required element, it gives you an error as expected.
However, rather than pointing out that specific element as the missing element, it gives a generic "..Missing child element(s). Expected is one of [a list of candidate elements]". The error is somewhat useful, however, I don't understand why it can't tell exactly which required element is missing if it's given an XSD. Is there a way to make it smarter in this regard and provide this info?
The outline of my script is something like:
from lxml import etree
xmlschema_doc = etree.parse('c:/xmlvalidation/schema.xsd')
xmlschema = etree.XMLSchema(xmlschema_doc)
doc = etree.parse(''c:/xmlvalidation/test.xml')
try:
    xmlschema.assertValid(doc)
    print('XML valid, schema validation ok.')

except etree.DocumentInvalid as err:
    print(err)


text:
Q: Query database and check not equal to I have a data set in excel that I am querying info in a database using that data set. However, when checking against the database I get the "too few parameters. Expected 1" error.
Query:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Racf] = '" & sRacf & "') AND ([DateChecked] = #" & sDateChecked & "#) AND ([Overall] <> '" & sOverall & "') ;")

Literal:
SELECT * FROM [CallQuality] WHERE ([Racf] = 'SMITHJ') AND ([DateChecked] = #2017/05/17#) AND ([Overall] <> 'Development Required') ;

I have tried without the brackets and using != instead of <>. I am sure it is something simple I am missing.
Edit:
Error in this section:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Overall] <> '" & sOverall & "')")

Edit2:
The field name was wrong. Sorry guys! Not sure why it didnt give me the name error when it didnt find the field.
Thank you for your help.

A: use a + instead of & in the query.
So use this:
Set rex = db.OpenRecordset("SELECT * FROM [CallQuality] WHERE ([Racf] = '" + sRacf + "') AND ([DateChecked] = #" + sDateChecked + "#) AND ([Overall] <> '" + sOverall + "') ;");

If you look in the Error List you should get:

Error CS0019  Operator '&' cannot be applied to operands of type
  'string' and 'string'

I can see why you put the & instead. Simple mistake :-)

A: It was an issue with the field name in the query.


text:
Q: Application unable to connect to database on AppHarbor I have this application which I am developing for learning purpose. I have hosted the application on AppHarbor.
It is ASP.NET MVC and EF Code First.
I added the SQL server free add on for db purpose but come what may the db connectivity is failing.
Code is hosted on Github here :- https://github.com/BilalHasanKhan/BusinessFlow
Please advise or point where I am wrong.
By switching custom error off I found the error:

Model compatibility cannot be checked because the database does not
  contain model metadata. Ensure that IncludeMetadataConvention has been
  added to the DbModelBuilder conventions.

A: You might want to check the blog post we recently did on migrations with EF Code First. There's also example code to along with the post.


text:
Q: How do i not display element with price over ??? from container i would like the function to hide every element with the price over 150. i made script that makes an item in shop from a container. now i want to make Price categories so onclick it only shows items under 150 for example.
  var ItemCollection =

[
    {

        Name: 'IVY PA',
        Price: 160,
        Picture: 'some pic'
    },
    {

        Name: 'IVY P',
        Price: 100,
        Picture: 'some pic'
    },

  ];

 ItemCollection.forEach(generateItem);
$('#Collection').append(content);

 var content = "";

 function generateItem(item, index, arrays) {

content = content + '\n' +
    '
\n' +
    '
\n' +
    '                \n' +
    '\n' +
    '
\n' +
    '
\n' +
    '
' + item.Name + '
\n' +
    '
' + item.Price + '$
\n' +
    '
\n' +
    '            \n' +
    '
\n';

 }

 function under150() {
   var price = "";

var Shoe = document.getElementsByClassName("Shoe");

  price = ItemCollection.item.Price;
 console.log(ItemCollection.item.Price);

if (price > 150){

    Shoe.style.display = "none";

}
else {}

 }

there is my current try but i know it's completely wrong i need a little help, so if u have any ideas i'll be very thankful.

A: Iterate on each item and then check the price, if price is more than 150 then hide that particular item.
function under150() {
    var Shoe = document.getElementsByClassName("Shoe");
    for(var i=0;i<Shoe.length;i++)
    {
        price = ItemCollection[i].Price;
        if (price > 150){
            Shoe[i].style.display = "none";
        }
    }
}


text:
Q: replace text in textfield with colored text, jquery I have a textfield with filled value. It contains 'XXXX' and i would like to highlight only the 'XXXX' so the user can notice, that the XXXX must be replaced by a value. How can I get the value, take only the 'XXXX' and replaced it with the same value, but colored.

A: You can use Div Element :

    <title>This is test</title>

 I am XXXX.


text:
Q: Value not populated for given string in scala spark I am using property file to pass sql query in spark scala, my property file like this.
spark.query=select '$env' from table_name limit 5

In spark code
val env="dev"
val query=sparkContext.getConf.get("spark.query");

println(query);

spark.sql(s"""$query""");

But here it's not talking value for dev my output is like below:
select $env from table_name =>$env value not populating.


text:
Q: When and why should one use Applicative Functors in Scala I know that Monad can be expressed in Scala as follows:
trait Monad[F[_]] {
  def flatMap[A, B](f: A => F[B]): F[A] => F[B]
}

I see why it is useful. For example, given two functions:
getUserById(userId: Int): Option[User] = ...
getPhone(user: User): Option[Phone] = ...

I can easily write function getPhoneByUserId(userId: Int) since Option is a monad:
def getPhoneByUserId(userId: Int): Option[Phone] =
  getUserById(userId).flatMap(user => getPhone(user))

...
Now I see Applicative Functor in Scala:
trait Applicative[F[_]] {
  def apply[A, B](f: F[A => B]): F[A] => F[B]
}

I wonder when I should use it instead of monad . I guess both Option and List are Applicatives. Could you give simple examples of using apply with Option and List and explain why I should use it instead of flatMap ?

A: To quote myself:

So why bother with applicative functors at all, when we've got monads?
  First of all, it's simply not possible to provide monad instances for
  some of the abstractions we want to work with—Validation is the
  perfect example.
Second (and relatedly), it's just a solid development practice to use
  the least powerful abstraction that will get the job done. In
  principle this may allow optimizations that wouldn't otherwise be
  possible, but more importantly it makes the code we write more
  reusable.

To expand a bit on the first paragraph: sometimes you don't have a choice between monadic and applicative code. See the rest of that answer for a discussion of why you might want to use Scalaz's Validation (which doesn't and can't have a monad instance) to model
validation.
About the optimization point: it'll probably be a while before this is generally relevant in Scala or Scalaz, but see for example the documentation for Haskell's Data.Binary:

The applicative style can sometimes result in faster code, as binary
  will try to optimize the code by grouping the reads together.

Writing applicative code allows you to avoid making unnecessary claims about dependencies between computations—claims that similar monadic code would commit you to. A sufficiently smart library or compiler could in principle take advantage of this fact.
To make this idea a little more concrete, consider the following monadic code:
case class Foo(s: Symbol, n: Int)

val maybeFoo = for {
  s <- maybeComputeS(whatever)
  n <- maybeComputeN(whatever)
} yield Foo(s, n)

The for-comprehension desugars to something more or less like the following:
val maybeFoo = maybeComputeS(whatever).flatMap(
  s => maybeComputeN(whatever).map(n => Foo(s, n))
)

We know that maybeComputeN(whatever) doesn't depend on s (assuming these are well-behaved methods that aren't changing some mutable state behind the scenes), but the compiler doesn't—from its perspective it needs to know s before it can start computing n.
The applicative version (using Scalaz) looks like this:
val maybeFoo = (maybeComputeS(whatever) |@| maybeComputeN(whatever))(Foo(_, _))

Here we're explicitly stating that there's no dependency between the two computations.
(And yes, this |@| syntax is pretty horrible—see this blog post for some discussion and alternatives.)
The last point is really the most important, though. Picking the least powerful tool that will solve your problem is a tremendously powerful principle. Sometimes you really do need monadic composition—in your getPhoneByUserId method, for example—but often you don't.
It's a shame that both Haskell and Scala currently make working with monads so much more convenient (syntactically, etc.) than working with applicative functors, but this is mostly a matter of historical accident, and developments like idiom brackets are a step in the right direction.

A: Functor is for lifting computations to a category.
trait Functor[C[_]] {
  def map[A, B](f : A => B): C[A] => C[B]
}

And it works perfectly for a function of one variable.
val f = (x : Int) => x + 1

But for a function of 2 and more, after lifting to a category, we have the following signature:
val g = (x: Int) => (y: Int) => x + y
Option(5) map g // Option[Int => Int]

And it is the signature of a applicative functor. And to apply the following  value to a function g — an aplicative functor is needed.
trait Applicative[F[_]] {
  def apply[A, B](f: F[A => B]): F[A] => F[B]
}

And finally:
(Applicative[Option] apply (Functor[Option] map g)(Option(5)))(Option(10))

Applicative functor is a functor for applying a special value (value in category) to a lifted function.


text:
Q: Asus P5N-D Motherboard / NVIDIA nForce 750i SLI Southbridge: mix RAID1 and non-RAID? I have an Asus P5N-D motherboard which includes the NVIDIA nForce 750i SLI chipset.  The motherboard has 4 Serial ATA 3Gb/s slots and the chipset supports RAID 0, RAID 0+1, RAID 5, and JBOD.  I currently have a RAID 1 setup.  However, I'd like to add another hard drive (an SSD) which will become my primary drive while the RAID 1 drive becomes my data drive.  Is this configuration typically supported?

A: So far as I know this should be fine, on most raid controllers you should be able to set whether a disk is handled by the raid controller or the BIOS. Most probably this setting is in the bios, however check in both places.


text:
Q: How to say 'Thirty minutes away by foot'? Can I use: 'Thirty minutes away by foot'? Or how should I write this sentence properly? I want to say that: 'I will be living less than thirty minutes away, by bicycle or by (foot/walking), from the college'?

A: I think that "30 minutes away on foot" is more colloquially standard in American English. Otherwise, what you're saying sounds fine.

A: In descending order of usage and clarity... "30-minute walk from the college," "30 minutes by foot from the college," "30 minutes on foot from the college,"
"30-minute bike ride" or "30 minutes by bike."  I wouldn't say "30 minutes on bike."  You could use "30 minutes on a/the bike" but that seems to relate more to the time you spend on the bike vs. the trip. Like, "What did you do at the gym?"  "Oh, I spent 30 minutes on the bike and then did push ups."


text:
Q: Como hago esto con javascript creando calculadora personal estoy creando una calculadora que lo que hace es que yo meto el producto y la cantidad y me hace el calculo, pero no se que pasa que no me aparece el resultado, si me pueden ayudar.
Función para crear lista de compra y calcular
let natilla = 'Natilla'
natilla = 0.69
function CrearLista() {
        let alerta = prompt('Introduce el producto');
        let cantidad = prompt('Introduce la cantidad del producto');
        if( alerta == null || alerta == '' ) {

            alert('Debes introducir un valor');
        }
        if( cantidad == null || cantidad == '' ) {

            alert('Debes introducir un valor');
        }

        if (alerta == natilla) {
            let calculo = alerta * cantidad;
            console.log  = (` El precio final es: ${parseFloat(calculo)}`);
        }

Cuando lo ejecuto, la consola se queda en blanco no aparece el calculo.

A: El error esta en la lógica de como realizar el proceso.
el primer error que noto es igualar la función console.log.
console.log  = (` El precio final es: ${parseFloat(calculo)}`);

Después es crear la variable natilla y darle el valor "Natilla" y después sobrescribirla.
let natilla = 'Natilla'
natilla = 0.69

Esto ocasiona que al validar con lo que se introduce en el navegador nunca llegue al calculo
   if (alerta == natilla) {
     let calculo = alerta * cantidad;
     console.log  = (` El precio final es: ${parseFloat(calculo)}`);
   }

Ya con los errores corregidos el código quedaría de la siguiente forma:

let natilla = 'Natilla';
let valor_natilla = 0.69;
CrearLista();
function CrearLista() {
  let alerta = prompt('Introduce el nombre del producto');
  let cantidad = prompt('Introduce la cantidad del producto');
  if( alerta == null || alerta == '' ) {
      alert('Debes introducir un valor');
  }
  if( cantidad == null || cantidad == '' ) {
      alert('Debes introducir un valor');
  }

  if (alerta == natilla) {
      let calculo = valor_natilla * cantidad;
      console.log(` El precio final es: ${calculo}`);
  }else{
    console.log('no existe el producto');
  }
}

Creo que asi lo tenias planeado la funcionalidad, espero haberte ayudado.

A:

let natilla = 'Natilla'
natilla = 0.69
CrearLista();
function CrearLista() {
        let alerta = prompt('Introduce el producto');
        let cantidad = prompt('Introduce la cantidad del producto');
        if( alerta == null || alerta == '' ) {

            alert('Debes introducir un valor');
        }
        if( cantidad == null || cantidad == '' ) {

            alert('Debes introducir un valor');
        }

            var calculo = alerta * cantidad;
            alert("Resultado: " + calculo  );

    }

Ok, Entendí lo que querías decir a mi me salió el así pruébalo