text:
Q: Left joins --> aggregate function problem I have four different tables in my database:
thread:

*

*thread_id

*thread_content

*timestamp

thread_rating:

*

*thread_rating_id

*thread_id

*liked

*disliked

thread_report:

*

*thread_report_id

*thread_id

thread_impression:

*

*thread_impression_id

*thread_id

And I'm going to join on these tables with this SQL-Query
SELECT t.thread_id,
t.thread_content,
SUM(tra.liked) AS liked,
SUM(tra.disliked) AS disliked,
t.timestamp,
((100*(tra.liked + SUM(tra.liked))) / (tra.liked + SUM(tra.liked) + (tra.disliked + SUM(tra.disliked)))) AS liked_percent,
((100*(COUNT(DISTINCT tre.thread_report_id)) / ((COUNT(DISTINCT ti.thread_impression_id))))) AS reported_percent
FROM thread AS t
LEFT JOIN thread_rating AS tra ON t.thread_id = tra.thread_id
LEFT JOIN thread_report AS tre ON tra.thread_id = tre.thread_id
LEFT JOIN thread_impression AS ti ON tre.thread_id = ti.thread_id
GROUP BY t.thread_id
ORDER BY liked_percent

The Query should return all thread_ids with the calculated liked and disliked, the likes in percent, the timestamp, when the thread was inserted into the database and the reports in percent to the impressions (the times, the thread was shown to the user)...
Nearly all results are right, the only results which are not right are the likes and dislikes.
If I put a count(*) in front of the query, I can see, that the right results have a count of 1 and the wrong ones have sometimes a count of up to 60.
Seems like there are cross join-problems...
I think that this is an issue with the Grouping, or perhaps I should embrace the Joins.
I've seen solutions with subselects. But I don't think that this is a great solutions for this issue...
What am I doing wrong here?

A: The tra table has multiple records per thread_id. This caused double counts in the SUM function.
Do the summations in a subselect, grouped by the join field.
That way you will only have one thread_id in tra2 to join with and duplicate rows will be avoided.
SELECT t.thread_id,
  t.thread_content,
  tra2.liked
  tra2.disliked,
  t.timestamp,
  tra2.liked_percent,
  ((100*(COUNT(DISTINCT tre.thread_report_id)) / ((COUNT(DISTINCT ti.thread_impression_id))))) AS reported_percent
FROM thread AS t
LEFT JOIN (
     SELECT
       tra.thread_id
       , SUM(tra.liked) AS liked
       , SUM(tra.disliked) AS disliked
       , ((100*(tra.liked + SUM(tra.liked))) / (tra.liked + SUM(tra.liked) + (tra.disliked + SUM(tra.disliked)))) AS liked_percent
     FROM thread_rating AS tra
     GROUP BY tra.thread_id
) as tra2 ON t.thread_id = tra2.thread_id
LEFT JOIN thread_report AS tre ON tra.thread_id = tre.thread_id
LEFT JOIN thread_impression AS ti ON tre.thread_id = ti.thread_id
GROUP BY t.thread_id
ORDER BY liked_percent DESC


text:
Q: Accessing object details in PHP thru global variables I am new to PHP from the .net world and this is the code that i have,
 class A
    {
       Album $album; // In C# .net i could have done this and assigned the display       action album data to this

       public function displayAction()
    {
        $form = new ButtonForm();

        $id = (int)$this->params('id');
        if (!$id) {
            return $this->redirect()->toRoute('album', array('action'=>'add'));
        }
        $album = $this->getAlbumTable()->getAlbum($id);

        return array(
            'id' => $id,
            'album' => $album,
            'form' => $form
        );
    }

    }

How can i do this is PHP ?
Consider that i come a pure object oriented technology. So help will be highly appreciated.

A: I know you can do type hinting in function arguments, but I am thinking that you can't with field variables of a class.  Instead of Album $album; use public $album;.  Then you can access it freely outside the object.  e.g.
$obj = new A();
echo $obj->album;

Keep in mind though your var must be declared public to access it this way.  private and protected will not allow access in the global scope.  You will need to create accessor functions in that case.
EDIT
Also, whenever accessing field variables within your class use the $this keyword.  So again, instead of $album you use $this->album.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert unicode character to its escaped ascii equivalent in c# i am beginning with a string containing an encoded unicode character "& #xfc;". I pass the string to an object that performs some logic and returns another string. That string is converting the original encoded character to its unicode equivalent "ü".
I need to get the original encoded character back but so far am not able.
I have tried using the HttpUtility.HtmlEncode() method but that is returning "& #252;" which is not the same.
Can anyone help?

A: They are pretty much the same, at least for display purposes. HttpUtility.HtmlEncode is using decimal encoding, which is in the format &#DECIMAL; while your original version is in hexadecimal encoding, i.e. in the format &#xHEX;. Since fc in hex is 252 in decimal, the two are equivalent.
If you really need to get the hex-encoded version, then consider parsing out the decimal and converting it to hex before stuffing it back in to the &#xHEX; format. Something like
string unicode = "ü";
string decimalEncoded = HttpUtility.HtmlEncode(unicode);
int decimal = int.Parse(decimalEncoded.Substring(2, decimalEncoded.Length - 3);
string hexEncoded = string.Format("&#x{0:X};", decimal);

A: Or you can try this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using System.Globalization;

namespace SimpleCGIEXE
{
    class Program
    {
        static string Uni2Html(string src)
        {
            string temp1 = HttpUtility.UrlEncodeUnicode(src);
            string temp2 = temp1.Replace('+', ' ');
            string res = string.Empty;
            int pos1 = 0, pos2 = 0;
            while (true){
                pos2=temp2.IndexOf("%",pos1);
                if (pos2 < 0) break;
                if (temp2[pos2 + 1] == 'u')
                {
                    res += temp2.Substring(pos1, pos2 - pos1);
                    res += "&#x";
                    res += temp2.Substring(pos2 + 2, 4);
                    res += ";";
                    pos1 = pos2 + 6;
                }
                else
                {
                    res += temp2.Substring(pos1, pos2 - pos1);
                    string stASCII = temp2.Substring(pos2 + 1, 2);
                    byte[] pdASCII = new byte[1];
                    pdASCII[0] = byte.Parse(stASCII, System.Globalization.NumberStyles.AllowHexSpecifier);
                    res += Encoding.ASCII.GetString(pdASCII);
                    pos1 = pos2 + 3;
                }
            }
            res += temp2.Substring(pos1);
            return res;
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Content-type: text/html;charset=utf-8\r\n");
            String st = "Vietnamese string: Thử một xâu unicode @@ # ~ .^ % !";
            Console.WriteLine(Uni2Html(st) + "
");
            st = "A chinese string: 我爱你 (I love you)";
            Console.WriteLine(Uni2Html(st) + "
");
        }
    }
}

A: I just had to sort this out yester day.
It's a bit more complicated than just looking at a single character. You need to roll your own HtmlEncode() method. Strings in the .Net world are UTF-16 encoded. Unicode codepoints (what an HTML numeric character reference identifies) are a 32-bit unsigned integer value. This is mostly an issue is you have to deal with characters outside Unicodes "basic multi-lingual plane".
This code should do what you want
using System;
using System.Configuration ;
using System.Globalization ;
using System.Collections.Generic ;
using System.Text;

namespace TestDrive
{
    class Program
    {
        static void Main()
        {
            string src = "foo \uABC123 bar" ;
            string converted = HtmlEncode(src) ;

            return ;
        }

        static string HtmlEncode( string s )
        {
            //
            // In the .Net world, strings are UTF-16 encoded. That means that Unicode codepoints greater than 0x007F
            // are encoded in the string as 2-character digraphs. So to properly turn them into HTML numeric
            // characeter references (decimal or hex), we first need to get the UTF-32 encoding.
            //
            uint[]        utf32Chars = StringToArrayOfUtf32Chars( s ) ;
            StringBuilder sb         = new StringBuilder( 2000 ) ; // set a reasonable initial size for the buffer

            // iterate over the utf-32 encoded characters
            foreach ( uint codePoint in utf32Chars )
            {

                if ( codePoint > 0x0000007F )
                {
                    // if the code point is greater than 0x7F, it gets turned into an HTML numerica character reference
                    sb.AppendFormat( "&#x{0:X};" , codePoint ) ; // hex escape sequence
                  //sb.AppendFormat( "&#{0};"    , codePoint ) ; // decimal escape sequence
                }
                else
                {
                    // if less than or equal to 0x7F, it goes into the string as-is,
                    // except for the 5 SGML/XML/HTML reserved characters. You might
                    // want to also escape all the ASCII control characters (those chars
                    // in the range 0x00 - 0x1F).

                    // convert the unit to an UTF-16 character
                    char ch = Convert.ToChar( codePoint ) ;

                    // do the needful.
                    switch ( ch )
                    {
                    case '"'  : sb.Append( """      ) ; break ;
                    case '\'' : sb.Append( "'"      ) ; break ;
                    case '&'  : sb.Append( "&"       ) ; break ;
                    case '<'  : sb.Append( "<"        ) ; break ;
                    case '>'  : sb.Append( ">"        ) ; break ;
                    default   : sb.Append( ch.ToString() ) ; break ;
                    }
                }
            }

            // return the escaped, utf-16 string back to the caller.
            string encoded = sb.ToString() ;
            return encoded ;
        }

        ///
        /// Convert a UTF-16 encoded .Net string into an array of UTF-32 encoding Unicode chars
        ///
        /// <param name="s"></param>
        /// <returns></returns>
        private static uint[] StringToArrayOfUtf32Chars( string s )
        {
            Byte[] bytes      = Encoding.UTF32.GetBytes( s ) ;
            uint[] utf32Chars = (uint[]) Array.CreateInstance( typeof(uint) , bytes.Length / sizeof(uint) ) ;

            for ( int i = 0 , j = 0 ; i < bytes.Length ; i += 4 , ++j )
            {
                utf32Chars[ j ] = BitConverter.ToUInt32( bytes , i ) ;
            }

            return utf32Chars ;
        }

    }

}

Hope this helps!


text:
Q: create stripe invoice with specific invoice items, excluding pending invoice items I am trying to create manual stripe invoices but don't want it to create the invoice from pending invoice items. For example, I have 3 pending invoice items that I do not want include on this manual invoice.
Pending Line Items:
Item 1
Item 2

New Invoice:
Item 3

How do I create a blank invoice, then manually assign Item 3 to it, with out adding 1 and 2?

A: For anyone looking, I am using Stripe's API to delete all pending invoice items from the customer before creating the new invoice items and creating the invoice. Best solution I could think of.

A: I am not sure when it was added, but Invoices now can set the pending_invoice_items_behavior to define the behavior.

How to handle pending invoice items on invoice creation. One of
include, exclude, or include_and_require. include will include any
pending invoice items, and will create an empty draft invoice if no
pending invoice items exist. include_and_require will include any
pending invoice items, if no pending invoice items exist then the
request will fail. exclude will always create an empty invoice draft
regardless if there are pending invoice items or not. Defaults to
include_and_require if the parameter is omitted.


text:
Q: Analysing a network distance to two or more points using GRASS I am doing a piece of analysis work looking at distances along a network in GRASS. Most of the analysis involves finding which parts of the network are within 600m of a series of points. GRASS does this very well using the v.net functions.
I've got stuck on trying to identify which parts of a network are within 600m of more than two points in the series.
Does anyone have any ideas how I could do this within GRASS?
I'm using the GRASS plugin in QGIS.

A: *

*Take line layer , go Vector-> geoprosessing tools -> buffer (600m) -> save results layer

*Go Vector-> geoprosessing tools -> Intersects buffer layer and points layer -> save results
take results , and count points per series in one buffer. (3. not 100% about this)

OR replace 2. with

*

*Go Vector-> count points in polygon (this probably wont give you answer ) Open attribute table and select by expression and make query from count + series id + point count

OR

*

*Go Vector-> count points in polygon (this probably wont give you answer ) Open attribute table and select by expression and make query from count + series id + point count
OR

*Use Vector Spatial Query tool ( this might be plugin , not 100 %)


text:
Q: How to convert datetime into GMT +7 in Python? I have a dataframe that looks like that:

   conversation__created_at
0  2020-10-15T03:39:42.766773+00:00
1  2020-10-14T11:24:33.831177+00:00
2  2020-10-14T08:29:44.192258+00:00
3  2020-10-14T01:42:06.674313+00:00
4  2020-10-13T12:57:04.218184+00:00

How to convert it into GMT +7?

A: I assume you have a pandas series because the data you posted looks like one.
Then you can use tz_convert, i.e.
import pandas as pd
pd.to_datetime('2020-10-15T03:39:42.766773+00:00').tz_convert('Etc/GMT+7')

As pointed out in the comments, since the datetime carries a T in it, it is of string format, thus we need to convert to datetime first and then convert to the correct timezone.
pd.to_datetime(series).dt.tz_convert('Etc/GMT+7')

A: You can use datetime library only.
from datetime import datetime, timedelta, timezone

d = datetime.fromisoformat("2020-10-15T03:39:42.766773+00:00")
tz = timezone(timedelta(hours=7))
new_time = d.astimezone(tz)

A: you can use pytz to set timezone for your datetime instance
for example:
from pytz import timezone
from datetime import datetime

date = datetime.now()

print(date)
tz = timezone("Etc/GMT+7")
date = date.replace(tzinfo=tz)
print(date)

out put:
2020-10-26 10:33:25.934699
2020-10-26 10:33:25.934699-07:00

A: You can apply pytz.timezone on the df
from pytz import timezone
from datetime import datetime

def myDate(x):
  tz = timezone("Etc/GMT+7")
  dt = x.replace(tzinfo=tz)
  return dt

df['conversation__created_at'] = df.apply(lambda row: myDate(row['conversation__created_at'].to_pydatetime()))


text:
Q: Issue while getting the json data using context.request I'm developing a web based application using bootstrap.
I'm trying to implement inline editing in my grid on page load but im facing some issue while handling json data.
Here is my code :
  $(document).ready(function () {
    var GetUrl = Web_Path + '/Test/TestHandler/GetTestData/' + AjaxHandlerName;

                jQuery("#jqGrid-container").jqGrid({
                    url: GetUrl,
                    datatype: 'json',
                    mtype: 'POST',
                    postData: { SearchInfo: function () { return getSearchPostData() } },
                    colNames: [' ', 'ID', 'Name', 'ContactNo', 'EmpId', 'MailId', 'RoleName'],
                    colModel: [
                    { name: 'myac', index: '', width: 80, fixed: true, sortable: false, resize: false,
                        formatter: 'actions',
                        formatoptions: {
                            keys: true,
                            delOptions: { recreateForm: true, beforeShowForm: beforeDeleteCallback }
                        }
                    },
                                { name: 'Id', index: 'Id', hidden: true, editable: true },
                                { name: 'Name', index: 'Name', validation: { required: true }, sortable: true, editable: true, editoptions: { size: "40", maxlength: "50"} },
                                { name: 'ContactNo', index: 'ContactNo', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
                                { name: 'EmpId', index: 'EmpId', sortable: false, editable: true, editoptions: { size: "20", maxlength: "30"} },
                                { name: 'MailId', index: 'MailId', sortable: false, editable: true, editoptions: { size: "40", maxlength: "50"} },
 {name: 'RoleName', index: 'RoleName', sortable: false }
  ],

                    editurl: ISM_Web_Path + '/Test/TestHandler/UpdateTestContacts/' + ISMAjaxHandlerName,

                    ajaxRowOptions: {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                    },
                    serializeRowData: function (postdata) {
                    return { ContactInfo: JSON.stringify(postdata) };
                    },
                    jsonReader: {
                        id: 'Id',
                        repeatitems: false
                    },
                    height: "100%",
                    pager: '#jqGrid-pager',
                    rowNum: 10,
                    rowList: [10, 20, 30],
                    sortname: 'Id',
                    sortorder: 'desc',
                    viewrecords: true,
                    caption: "JQ grid data",
                    loadComplete: function () {
                        var table = this;
                        updatePagerIcons(table);
                    }
                });
});

 function getSearchPostData() {
            var searchData = {};
            searchData.Id=1;

            return JSON.stringify(searchData);
        }
 function updatePagerIcons(table) {
            var replacement =
                    {
                        'ui-icon-seek-first': 'icon-double-angle-left bigger-140',
                        'ui-icon-seek-prev': 'icon-angle-left bigger-140',
                        'ui-icon-seek-next': 'icon-angle-right bigger-140',
                        'ui-icon-seek-end': 'icon-double-angle-right bigger-140'
                    };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
}

Handler function
 public void UpdateTestContacts(HttpContext context)
        {
            TestContact contactInfo =new TestContact();
            string jsonData = context.Request.Params["ContactInfo"];
            MemoryStream TestContactMs = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TestContact));
            contactInfo = (RelationshipContact)serializer.ReadObject(TestContactMs );
            //call manger function
        }

TestContact.cs
 public class TestContact
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string ContactNo { get; set; }

        public string EmpId { get; set; }

        public int RelId { get; set; }

        public int TypeId { get; set; }

        public string MailId { get; set; }

        public string RoleName { get; set; }
    }

I have used jquery.jqGrid.min.js.
I'm getting and error ArgumentNullException was handled by User Code.String reference not set to an instance of a String.
Parameter name: s in string jsonData = context.Request.Params["ContactInfo"];
Please help me out.

A: Already it is in JSon type, so i have removed the below lines from my code.
 ajaxRowOptions: {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json"
                    }

It works fine..


text:
Q: Setting up Grid Engine As I'm working on setting up grid engine... I'm stuck with an issue. As I check what are the running deamons using the following command.... The result I get is (as listed):
ps aux | grep sge

sgeadmin  1069  0.0  0.0  68896  3372 ?        Sl   10:04   0:00 /usr/lib/gridengine/sge_execd
sayantan  9545  0.0  0.0  21292   968 pts/5    S+   10:56   0:00 grep --color=auto sge

Now, if I log into root and use the following commands:
(i.e. after sudo su)
sge_qmaster

This doesn't give any output.
But then, as I try to start the exec:
sge_execd

The error I get is:
error: communication error for "localhost/execd/1" running on port 6445: "can't bind socket"
error: commlib error: can't bind socket (no additional information available)

I'm stuck for quite some time now. Request some help.

A: The error you get from sge_execd points to that the sge_execd process is running already and has allocated port 6445 already and therefore a second instance cannot use the port again.
Since sge_execd and sge_qmaster are services, they shouldn't be started directly on the commandline but rather through the init-scripts that are shipped with the packages. Additionally, the init-scripts will pick up some SGE related environment variables to make the services work correctly.
From Ubuntu 16.04 and onwards, systemd is normally used to manage startup scripts. In case of the gridengine scripts, the systemd way seems not to work. You should enable the SGE parts to start automatically on boot as follows.
$ sudo update-rc.d gridengine-master enable
$ sudo update-rc.d gridengine-exec enable

To start the services correctly for now, you could first stop the instances and the start them through systemd.
$ sudo killall sge_qmaster
$ sudo killall sge_execd

Then check if the processes went away.
$ sudo ps aux | grep sge | grep -v grep

After that try to start the services.
$ sudo systemctl restart gridengine-master.service
$ sudo systemctl restart gridengine-exec.service


text:
Q: SQL: Get count of distinct values of the table I am trying to get the count of distinct value of the table for example
I have below records in a table :
PK  Value
1       A
2       A
3       A
4       B
5       C
6       C
7       D
8       D
9       D
10      D
11      E
12      F

Looking above there are primary key(PK) and values, I want result like below :
Value   Count
A        3
B        1
C        2
D        4
E        1
F        1

Which should do a count each of the values.
I am trying the count(value) function but not getting the expected result, is there any other function can be used?

A: select value, count(*)
from the_table
group by value
order by value;

A: SELECT Value, count(Value) AS Count,
FROM table
Group BY Value


text:
Q: Make a table horizontal scrollable I'm looking for a way to show a table with a horizontal scrollbar.
I thought it was as simple as put a div around the table with the following properties:
.table-wrapper {
    overflow-x: scroll;
    width: 100%;
}

But unfortunately, this doesn't work. The table-wrapper goes offscreen:
https://codepen.io/studiojw/pen/MWrXGdw

A: Can you please check this
add an overflow-x: hidden; to .content

*,
*::before,
*::after{
    box-sizing: border-box;
}

body {
    font-family: sans-serif;
    min-height: 100vh;
    margin: 0;
}

.wrapper {
    display: flex;
    height: 100vh;
    width: 100vw;
}

.content {
    flex-grow: 1;
    border: 2px solid blue;
    overflow-x: hidden;
}

.table-wrapper {
    overflow-x: scroll;
    width: 100%;
    border: 2px solid green;
}

table {
    border: 2px solid red;
}

.nav {
    background: #eee;
    height: 100%;
    flex: 0 0 300px;
}

td {
    padding: 0.5rem;
    min-width: 25rem;
}

              First
              Second
              Third
              Third
              Third
              Third
              Third

              First
              Second
              Third
              Third
              Third
              Third
              Third


text:
Q: Visual studio меняет время, пришедшее от сервиса Уважаемые форумчане, подскажите, пожалуйста, с таким вопросом.
Есть удаленный Soap сервис. От этого сервиса по запросу получаем некую информацию, в состав информации входит дата и время (важный параметр).
При обращении к сервису через программку SOAPSonar мы получаем дату, к примеру, 2014-08-19 20:00 +6:00.
А при обращении через программу при дебаге в VS 2013 я наблюдаю дату 014-08-19 18:00,
причем я никакого приведения по времени не делаю и погрешность в часах недопустима.
При изменении часового пояса на локальном компе до часового пояса сервера, где расположен сервис, время приходит нормальное (2014-08-19 20:00).
Подскажите, что делать, чтобы избежать искажения такого времени.
A: Все очень просто, и студия тут ни при чем. Время, которое DateTime, может храниться в одном из двух форматов - местном (я так понимаю, я вас это UTC+4) или UTC. Когда приходит время с указанием часового пояса UTC+6, лучшее, что может сделать десериализатор - это сконвертировать его в местный пояс UTC+4.
Вариантов решения вашей проблемы аж четыре.
Вариант первый. Забить. Данное преобразование, совершаемое десериализатором, совершенно корректно и обратимо.
Вариант второй. Использовать тип данных DateTimeOffset вместо DateTime - он может хранить дату-время в любом часовом поясе.
Вариант третий. Перевести как клиент, так и сервер на использование UTC времени.
Вариант четвертый. Изменить сервер так, чтобы он передавал время в Unspecified формате (т.е. без указания часового пояса). Не знаю, зачем это нужно - но преобразовываться такое время также не будет.

A: Не передавать время клиента на сервер, а на сервере фиксить время в которое был запрошен конкретный метод... И сама ситуция при которой возникает такой эффект неясна... Это я применил навык телапатии...

A: Скорее всего, происходит перевод времени из указанного часового пояся (+6) в часовой пояс сервера, на котором запущена программа.
Варианты:

*

*Пересылать время с учётом часового пояса.

*Пересылать без часового пояса.

*Пересылать строку и самому её парсить.


text:
Q: ¿Como puedo guardar resultados de node-fetch en una variable? Ya he hecho bots antes, pero en este caso, quiero usar una api de servidores de minecraft para que cambie su estado cada 5 segundos con informacion obtenida de la API, tambien, un simple comando de embed que envia información.
Aquí esta el código:

const Discord = require("discord.js");
const client = new Discord.Client();
const datos = require("./datos.json");
const fetch = require('node-fetch');
let prefix = datos.prefix

client.on('ready', () => {
  fetch(`https://api.mcsrvstat.us/2/mc.bouncegaming.es`).then(res => res.json()).then(json => {
    let bgip = json.ip
    let bgport = json.port
    let bgplayersonline = json.players.online
    let bgplayersmax = json.players.max
    let bgmotd = json.motd.clean
    let bgversion = json.version
  })
  const estados = [
    " ",
    "mc.bouncegaming.es",
    "Hay "+bgplayersonline+"/"+bgplayersmax+" conectados.",
    "Version: "+bgversion+"."
    ];

  console.log("Bot encendido.")
  setInterval(() => {
      const index = Math.floor(Math.random() * (estados.length - 1) + 1);
      client.user.setActivity(estados[index]);
  }, 5000);

           client.on("message", (message)  => {
            let member = message.member;
            const args = message.content.slice(prefix.length).split(' ');
            const command = args.shift().toLowerCase();

            if(message.content.toLowerCase().startsWith(prefix+"statusmc")) {
                  const embedbg1 = new Discord.RichEmbed()
                  .setColor(0x1A85CC)
                  .setTitle('BounceGaming')
                  .setThumbnail("https://bouncegaming.es/files/logo512.png")
                  .setDescription('https://discord.gg/FzkuFJg')
                  .addField('Usuarios conectados:', bgplayersonline+"/"+bgplayersmax, true)
                  .addField('IP:', bgip+":"+bgport, true)
                  .addBlankField()
                  .addField('MOTD:', bgmotd, true)
                  .addField('Version:', bgversion, true)
                message.channel.send(embedbg1)
            }

        })
});

client.login(datos.token);

Peeero consigo este error:
C:\botBounceGaming\discordapimc\index.js:20
    "Hay "+bgplayersonline+"/"+bgplayersmax+" conectados.",
           ^
ReferenceError: bgplayersonline is not defined
    at Client. (C:\botBounceGaming\discordapimc\index.js:20:12)
[90m    at Client.emit (events.js:215:7)[39m
    at WebSocketConnection.triggerReady (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\WebSocketConnection.js:125:17)
    at WebSocketConnection.checkIfReady (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\WebSocketConnection.js:141:61)
    at GuildCreateHandler.handle (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\packets\handlers\GuildCreate.js:13:31)
    at WebSocketPacketManager.handle (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\packets\WebSocketPacketManager.js:105:65)
    at WebSocketConnection.onPacket (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\botBounceGaming\discordapimc\node_modules\[4mdiscord.js[24m\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\botBounceGaming\discordapimc\node_modules\[4mws[24m\lib\event-target.js:120:16)
[90m    at WebSocket.emit (events.js:210:5)[39m
Agradezco toda ayuda para conseguir guardar la informacion en una variable para usar la informacion fuera del .then(json => {
//Blah Blah Blah})

A: Es bastante simple, lo que dices es lo que necesitas. Para poder aplicarlo seria de la siguiente manera:
const delay = ms => new Promise(res => setTimeout(res, ms));
let bgData = {};
fetch(`https://api.mcsrvstat.us/2/mc.bouncegaming.es`)
  .then(res => res.json())
  .then(json => {
    bgData = {
      bgip: json.ip,
      bgport: json.port,
      bgplayersonline: json.players.online,
      bgplayersmax: json.players.max,
      bgmotd: json.motd.clean,
      bgversion: json.version
    };
  });
await delay(5000);
console.log(bgData); // Solo estará completa cuando se resuelva la promesa (fetch)

El problema que estas teniendo es que dentro de then() estas declarando las variables con let y eso hace que esas variables definidas esten solo accesibles en el scope de esa función. La limitación del scope de las variables declaradas con let es por bloque, en tu caso no tenes ningún bloque dentro de esa función por lo que esta accesible dentro de esa función completa.
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Sentencias/let


text:
Q: Basic understanding of the heap I want to learn more about what happens on the heap. So I look at the following C code. It basically just allocates memory on the heap for two variables:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    char *char_ptr;
    int *int_ptr;
    int mem_size;

    if(argc < 2)
        mem_size = 50;
    else
        mem_size = atoi(argv[1]);

    printf("\t[+] allocating %d bytes of memory on the heap for char_ptr\n", mem_size);
    char_ptr = (char *) malloc(mem_size);
    if(char_ptr == NULL)
    {
        fprintf(stderr, "Error: could not allocate heap memory. \n");
        exit(-1);
    }

    strcpy(char_ptr, "This is memory located on the heap.");
    printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);

    printf("\t[+] allocating 12 bytes of memory on the heap for int_ptr\n");
    int_ptr = (int * ) malloc(12);
    if(int_ptr == NULL)
    {
        fprintf(stderr, "Error: could not allocate heap memory.");
        exit(-1);
    }

    *int_ptr = 31337;
    printf("int_ptr  (%p) --> %d\n", int_ptr, *int_ptr);

    printf("\t[-] freeing char_ptr's heap memory...\n");
    free(char_ptr);

    printf("\t[+] allocating another 15 bytes for char_ptr\n");
    char_ptr = (char *) malloc(15);
    if(char_ptr == NULL)
    {
        fprintf(stderr,"Error: could not allocate heap memory.\n");
        exit(-1);
    }

   strcpy(char_ptr, "new memory");
   printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr);

   free(int_ptr);
   free(char_ptr);
}

The output for this code looks like this:

    [+] allocating 50 bytes of memory on the heap for char_ptr
char_ptr (0x8827008) --> 'This is memory located on the heap.'
    [+] allocating 12 bytes of memory on the heap for int_ptr
int_ptr  (0x8827040) --> 31337
    [-] freeing char_ptr's heap memory...
    [+] allocating another 15 bytes for char_ptr
char_ptr (0x8827050) --> 'new memory'

So I'm guessing char_ptr is pointing to the beginning of the allocated memory (0x8827008), right?
Since 50 bytes are allocated, the end of this memory should point at address 0x882702A. The next memory allocation is beginning at address 0x8827040. My question is: why is int_ptr NOT pointing to 0x882702B (the very next address after the first memory allocation)? Or in other terms: what is happening with memory in between 0x772702A and 0x8827040 ?

A: The specifics depend on your C library (in turn depending on your operating system). There are two factors contributing to the phenomenon you are seeing:

*

*Each memory block you get from malloc is prefixed with a header (often 16 bytes). However, malloc only returns a pointer point to after the header.

*Each memory block must be aligned, to a multiple of the maximum alignment unit. Typically (depending on the microprocessor), the maximum alignment is 8 bytes. The bytes that are used to achieve the alignment are called padding.

As a consequence, the block that ends in ...2A gets padded up to ...30, then 16 bytes malloc header get added, and your next block starts at ...40.

A: malloc() doesn't necessarily allocate at the very next memory address. Here are some reasons why not:

*

*malloc() is only guaranteed to return some allocated memory. How it works is up to malloc() - from an interface definition perspective, it's a black box. Working out what goes on inside may be interesting, but isn't part of the standard.

*malloc() will align the allocations to convenient boundaries (normally 64 bit boundaries on a 64 bit platform).

*Other library calls may have free()'d blocks before, so you get an allocation within a hole - i.e. within a previously free()'d block of memory.

*The internal data structures that describe the heap immediately precede the allocate data structures. In a simple implementation, they would be a linked list.

*malloc() gets its memory from multiple places; yes, it uses the heap (and brk/sbrk), but for larger allocations it will use mmap() with MAP_ANON.
All these factors may lead to the allocation not being at the 'very next memory address'.

A: Probably because the control information for the heap is stored inline.
In other words, each block may have a 'hidden' section just before it that contains the control information like block size, link to the next block, markers to detect corruption and so on.
It may also give you more memory than requested, such as ensuring it's a multiple of sixteen bytes (though you're still only allowed to use what you asked for).
Bottom line is, however, you can't rely on any of that. It may change for a different implementation, different version or the day on which your code is running :-)
All you can be sure of is what it states in the standards - it will give you NULL or a usable address which could be anywhere.

A: Thank you everyone for your answer! They help a lot! I've had a fundamental missunderstandig of the heap's concept.
To summarize what have been said:

*

*Besides the actual values there are "hidden" informations for each memory block

*The heap doesn't necessary "string together" the individual memory blocks

Unfortunately I can't give anyone of you a vote up, since I'm not having 15 reputation. I hope you forgive me ;-)


text:
Q: String Index Out Of Range: -1 error String Index Out Of Range: -1 is the error I get when I execute this code in my mapper in hadoop MR.
    String line = value.toString();
    String[] longLatArray = line.split(",");
    double lat = Double.parseDouble((longLatArray[0]).substring(1));

line looks like this: "(-21.24132363125682,-175.14134768396616,1)"
My aim is to remove the first "(" and get just -21.2873623 into my lat variable.
edit:
When I tried to debug in the hadoop interface, this is what I got:
attempt_201406251613_0002_m_000000_0: line: (-21.24132363125682,-175.14134768396616,1)
attempt_201406251613_0002_m_000000_0: index 0
attempt_201406251613_0002_m_000000_0: (-21.24132363125682
attempt_201406251613_0002_m_000000_0: index 1
attempt_201406251613_0002_m_000000_0: -175.14134768396616
attempt_201406251613_0002_m_000000_0: index 2
attempt_201406251613_0002_m_000000_0: 1)

When I executed very similar code just locally, I did not get any errors
Also, what is the significance of the -1 here?
Any help would be greatly appreciated!

A: public static void main(String[] args) throws Exception {

    String value="(-21.2873623,160.2323,1)";
    String line = value.toString();
    String[] longLatArray = line.split(",");
    double lat = Double.parseDouble((longLatArray[0]).substring(1));
    System.out.println(lat);
}

That is working as intended for me, giving me the lat from the coords in value. This leads me to believe that there is an issue with whatever is in value. Are you sure that value contains what you are expecting it to? You can debug by doing a:
System.out.println(value); // or use a logging library

And verify that. The -1 leads me to believe that you have passed the end of the string, but I'm not 100% positive on that.

A:  indexOf() returns -1 when the argument can't be found. It Might be the root Cause.

 Reproducible code
String value="";
String line = value.toString();
String[] longLatArray = line.split(",");
double lat = Double.parseDouble((longLatArray[0]).substring(1));
System.out.println(lat);


text:
Q: Laravel, seemingly complex eloquent relationships I am really having some issues getting my head around this, but, I'll try to explain what it is that I want to achieve and hopefully one of you can point me in the right direction.
I have a Role entity, nothing crazy here just a name field.
I also have a RoleField entity, this is used to basically build forms and will contain information like, field_type.
A user can assign themselves a Role so I have a table user_roles, but a user can also have answers to the form that was built using the RoleField entity. This is the bit that is giving me headaches.
Some of this might be a matter of opinion and I know that this place isn't meant for opinions but there is also some hard answers in there somewhere.
So firstly, what is the optimal database structure for a scenario that a user has the ability to save answers to their role. What would these relationships look like? Should I structure my endpoints to be user/1/role/1/field/1/answer seems rather long winded?


text:
Q: how to add font-size toolbar in tinyMCE? this way i initialize tinyMCE to a textarea. font, bold italic is working but font size select is not working .
tinymce.init({
    selector: "textarea#content",
    theme: "modern",
    width: 586,
    height: 300,
    menubar:false,
    font_size_classes : "fontSize1, fontSize2, fontSize3, fontSize4, fontSize5, fontSize6",//i used this line for font sizes
    content_css: "css/content.css",
    toolbar: "sizeselect | bold italic | fontselect | fontsize",//used font size for showing font size toolbar
style_formats: [

    {title: 'Bold text', inline: 'b'},
            {title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
            {title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
            {title: 'Example 1', inline: 'span', classes: 'example1'},
            {title: 'Example 2', inline: 'span', classes: 'example2'},
            {title: 'Table styles'},
            {title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
    ],
});**

A: theme_modern_font_sizes: "10px,12px,13px,14px,16px,18px,20px",
font_size_style_values: "12px,13px,14px,16px,18px,20px",

toolbar: "insertfile undo redo | fontsizeselect |

A: I'm really annoyed at how wordpress seems to endeavour to make people wanna dig into the background and play with the codes, even for supposedly basic functions like changing fonts.
Luckily, I found a way to enable the font size menu without doing any real coding.
Just -

*

*Use the plugin 'TinyMCE Advanced'

*Activate it in settings.

More detailed instructions here.

A: All you need to do is to add fontsizeselect to your toolbar config param:
toolbar: "sizeselect | bold italic | fontselect |  fontsizeselect",

Update:
tinymce.init({
  fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt"
});

A: This may be of use for perspective. Below is my TinyMCE init JS code which includes the option for font type and size.
tinymce.init({
    selector: '#articletextarea',
    plugins: [
        'advlist autolink lists link image charmap preview hr anchor pagebreak',
        'searchreplace wordcount visualblocks visualchars code',
        'insertdatetime media nonbreaking table contextmenu directionality',
        'emoticons template paste textcolor colorpicker textpattern imagetools codesample'
    ],
    toolbar: 'codesample | bold italic sizeselect fontselect fontsizeselect | hr alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | insertfile undo redo | forecolor backcolor emoticons | code',
    fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt",
    height: "350",
    menubar: false
});


text:
Q: when i run the python file on startup using crontab i got the following error i installed the following packages,already
sudo pip3 install pyautogui.
and done the following settings in crontab,
@reboot XAUTHORITY=/home/pi/.Xauthority DISPLAY=:0  sh /home/pi/ICUmedical/launcher.sh >/home/pi/logs/cronlog 2>&1;
Traceback (most recent call last):
File "main.py", line 5, in <module>
import pyautogui as ui
File "/usr/local/lib/python3.7/dist-packages/pyautogui/__init__.py", line 241, in <module>
import mouseinfo
File "/usr/local/lib/python3.7/dist-packages/mouseinfo/__init__.py", line 223, in <module>
_display = Display(os.environ['DISPLAY'])
File "/usr/local/lib/python3.7/dist-packages/Xlib/display.py", line 80, in __init__
self.display = _BaseDisplay(display)
File "/usr/local/lib/python3.7/dist-packages/Xlib/display.py", line 62, in __init__
display.Display.__init__(*(self, ) + args, **keys)
File "/usr/local/lib/python3.7/dist-packages/Xlib/protocol/display.py", line 129, in
__init__
raise error.DisplayConnectionError(self.display_name, r.reason)
Xlib.error.DisplayConnectionError: Can't connect to display ":0": b'Invalid MIT-MAGIC-
COOKIE-1 key'


text:
Q: ADF: linkedService template function not defined I am currently trying to add some parameterised linked services. I have two services currently: a key vault, and a data lake. The configuration are:
// Key vault
{
  "name": "Logical Key Vault",
  "properties": {
    "parameters": {
      "environment": {
        "type": "String"
      }
    },
    "annotations": [],
    "type": "AzureKeyVault",
    "typeProperties": {
      "baseUrl": "https://kv-@{linkedService().environment}.vault.azure.net"
    }
  }
}
// Data lake
{
  "name": "Logical Data Lake",
  "properties": {
    "type": "AzureBlobFS",
    "parameters": {
      "environment": {
        "type": "String"
      }
    },
    "annotations": [],
    "typeProperties": {
      "url": "https://sa@{replace(linkedService().environment, '-', '')}.dfs.core.windows.net",
      "accountKey": {
        "type": "AzureKeyVaultSecret",
        "secretName": "storageAccountKey",
        "store": {
          "referenceName": "Logical Key Vault",
          "type": "LinkedServiceReference",
          "parameters": {
            "environment": {
              "value": "@linkedService().environment",
              "type": "Expression"
            }
          }
        }
      }
    }
  }
}

Both linked services are parameterised by an environment parameter, and I have confirmed that the Key Vault works fine and is able to correctly retrieve secrets. The problem happens when I attempt to retrieve the storage key from the key vault. I get the following error:

Error code
FailToResolveParametersInExploratoryController
Details
The parameters and expression cannot be resolved for schema operations.
Error Message: {
"message": "ErrorCode=InvalidTemplate, ErrorMessage=The template function 'linkedService' is not defined or not valid."
}

My attempts at debugging this has identified the use of @linkedService on line 38 to be the issue, which is when the Data Lake is trying to pass its own environment parameter to the Key Vault so that it may obtain the storage key. If I remove this use of @linkedService.environment and replace it with a hard coded value, the linked service successfully connects to the data lake.
The expression is trivially simple, and the web interface itself offers the option:

As a result, I am unsure why the use of @linkedService fails here. The web interface and ability to use expressions would suggest it should work, but then @linkedService is undefined for some reason.
While debugging this, I did find that using the expression
@string(linkedService.environment)

Does indeed work, but this seems rather odd as the environment is itself a string and thus its conversion into a string should be a no-op. I have also looked into removing the @ entirely and trying
linkedService.environment

and while this does correctly resolve to the environment, it still results in an error as it resulting parameter contains the surrounding quotation and thus the linked service fails to connect to the key vault https://kv-'foobar'.vault.azure.net as it is clearly invalid (assuming my environment was foobar).


text:
Q: Same field but different contents I'm building a database for a divination system. Just to make it easy, I'll explain it in terms of the i ching.
Every element of a hexagram is a different table. There's one for yin and yang, one for the 3 positions in a trigram, one for the trigrams, one for the hexagrams. There's also a table for the correspondences, which is linked to each of the other tables - correspondences for yin or yang, for the 3 positions, the trigrams, and the hexagrams. There is also a table with commentary, which also links to each of the other tables (except for the correspondence table).
So, the table for the trigrams, for example, might be structured like this:
TriID
TriName
Line1                    -FK (YinYangID)
Line2                    -FK (YinYangID)
Line3                    -FK (YinYangID)
TrigramMeaning
Correspondence           -FK (CorrespondencesID)
Commentary               -FK (CommentariesID)

With data like:
 TriID  TriName Line1 Line2 Line3 TriMeaning Correspondence  Commentary
 1      Qian    Yin   Yin   Yin   Receptive  1               1
 2      Kun     Yang  Yang  Yang  Generation 2               2

The Correspondence table looks something like this
 CorrID    Person    Season     Color     Animal    Number     Element
 1         Father    Winter     Blue      Bear      3          Metal
 2         Mother    Summer     Red       Deer      6          Earth

(I know that all my I Ching data's wrong...)
The idea is that the same correspondences are required for every table, so the correspondence table would have an entry for each of the other tables. CorrespondencesIDs 1 through 4 might apply to the YinYang table, for example (Old and New Yin, old and new Yang), and then 5 through 13 to each of the trigrams, and so on.
It seems like this would work just right. On the other hand, it feels intuitively like I'm doing something wrong and breaking some rules. Since every entry on the correspondence table will be different, it seems like there should maybe just be similar entries on every table:
TrigramPerson
TrigramSeason
TrigramColor
TrigramAnimal

and then
HexagramPerson
HexagramSeason
HexagramColor

and so on.
What is the smart / best way to structure the database? Apologies if this is a dumb question - I'm new to database design, and some of these concepts still confuse the heck out of me.

A: I had to re-read your question a few times to get the sense of what you are trying to do.  What I suggest is something I call a class-based multi-multi join.  In some db's like PostgreSQL, you can then do some advanced referential integrity checks on the joins, but that's outside my answer.
suppose you have a table:
CREATE TABLE correspondence_class (
     id int not null unique, -- hand-assigned
     label text primary key, -- hand-assigned, don't want duplicate labels
);

Then we can:
INSERT INTO correspondence_class (id, label)
VALUES ('1', 'person'), (2, 'color'), (3, 'season'), -- and so forth

From there we can then have two more tables:
CREATE TABLE trigram_assoc (
   trigram_id int references trigram(id),
   c_class_id int references correspondence_class(id),
   correspondence text not null,
   PRIMARY KEY (trigram_id, c_class_id)
 );

you would then do the same for hexagrams, lines, etc.  In PostgreSQL, you could change your primary key to include correspondence too, and uniquely index only those correspondences attached to some correspondence classes.  You could also have deferrable constraint triggers that could be used to ensure that all relevant associations were populated, but how exactly to do this on other dbs is a good question.


text:
Q: VREPRINT doesn't seem to have any effect According to the GNU docs, there is a character VREPRINT, or rprnt, which is supposed to re-print the shell's line-editor's input buffer. This can be helpful if something like a background process has written to the PTY
while you're typing another command and there is output interspersed with your input. However, I tried actually using it, and it seems to have no effect. I did the following:

*

*Run a sh session on the latest alpine image from Dockerhub.

*Use stty to bind the rprnt character to ^N.

*Type some input

*From a separate session, write to the first session's PTY.

*Try pressing ctrl-N to reprint my input

I expected it to refresh my input and remove the output that was written. However, there was no effect. There is still output cluttering my line editor. I verified that icanon and iexten are set on this PTY.

A: I assume your shell is bash or some other shell with full-featured line editing capabilities.
These shells, while waiting for you to type the command, set the tty mode to raw rather than canonical, hence the rprnt setting doesn't apply to them.
The command line tool stty doesn't report it back since these shells toggle the settings back and forth for the duration of line editing vs. running the requested external program (such as stty itself). You can confirm this by running stty -a < /dev/pts/[this-terminal's-number] from another terminal while this one is at the prompt.
Pick a program that does not have full-blown line editing capabilities, such as cat, dash or alike. You'll find that issuing stty rprnt ^N upfront, and pressing ^N does indeed reprint the given line. At least I've verified and it works for me.
For shells with powerful line editing capabilities, you'll have to consult the given shell's documentation (or in case of bash it's the readline library) to see how to reprint the prompt or how to configure its hotkey.


text:
Q: Win32 Application calling C code For my engineering project we are programming robots and our team decided to program a gui in Win32 to direct the robot how to move, rotate, etc. So far I haven't found anything on the web about how to encapsulate the code and call functions using buttons and other inputs. Anyone know of a good guide or any tips on how to do this?

A: If you really want to program in the raw C/Win32 API, I'd get a copy of Petzold.  Buy a used copy ;)
If you want to program something more contemporary, I'd consider using C# and .Net.
IMHO...
PS:
You might also wish to consider Linux.  Linux can make it really easy to get close to the hardware, and you've got lots of choices in both languages (C, C++, Python, Java, etc etc) and UIs (SDL, Qt, GTK+, etc, etc)

A: Check out Qt.
This will allow you to easily create guis, connect click/mouse/any event to the underlying api call easily. Also allows you to trivially multi thread the application so that your calls to the underlying robot api will not lock up your front-end... all within one very easy to use and adaptable framework.
Imho, starting off with win32 is just asking for more pain than it's worth


text:
Q: What are best tools for creating web layout? I use Firebug to see the HTML source of the Google Translate (http://translate.google.com.vn/) whether is simple (in content).
But it has a very complex layout (so many layout divs). I guess that these pages are designed layout based on a number of softwares support.
I know photoshop, but in general, it's very difficult to create layout in photoshop, I want to find an easier tool.

A: I think you should use photoshop Sitegrinder 3.5
Site Grinder 3.5 is a good tool for generating Html and CSS of any .psd file. But in my observation it is good for small and static site, it is not good for dynamic site. No doubt it is helpful for develop a web site but it require skilled person who work in Adobe Photoshop with site grinder tool. I mean it is useful for designer not for developer. Site Grinder 3.5 is support these following features:
1.  Rounded corner
2.  Shadow
3.  Borders
4.  Cross-Paging
5.  Menus and Sub-Menus
6.  Hide and show
7.  One design for many pages.
8.  More Powerful Hover And Click Behaviors
9.  Smooth Scrolling to Targeted Page Areas
10. Create Powerful Animated Accordions Using Only Hints
11. Attach Elements to The Browser Window(using –fixed hint)

Note: But some of these features like rounded-corner, shadow etc. are not run in IE7 and IE8 browser. It means site grinder has browser dependency.
There are some limitation of Site Grinder 3.5:

*

*Gradient color is not allowed.

*Generate more than one css for each page.

*Layer name with hint must be correct.

*It is still buggy. Some persons, who already used it says it is generate buggy code. But I was not found any bug while using it.

Keep in mind these following lines while designing web pages using site grinder 3.5:

*

*There are two phase for designing:

*

*Create a draft PSD and save it. Then Build Site Grinder 3.5

*After build PSD file use Design Manager Tool for complete design and effects then save it form build window.

*Background colors, shadow, rounded corner can be set in the design manager after the PSD is built using the style editing tools.

*Hints are correct.

A: I think Website Layout Maker is what you look for.

A: You can quickly create mockups with a software like Balsamic. This is a solid and rapid way to get an idea of the layout. Otherwise there is always pen&paper. I use sketch paper from  raincreativelab. It's free to download and has different browser-viewports marked.
After the sketching/mockup you can stay with photoshop and design the details.

A: Maybe you will be interested in ForeUI, it can generate HTML5 simulation for your layout (and interaction).


text:
Q: Can the terms "jingoism" and "ethnocentrism" be used interchangeably?
Maniacal belief that "your" race, gender, culture, religion, language, country, group, beliefs are better than everyone else's.

Which term would be more suitable: "jingoism" or "ethnocentrism"?
Can they be used interchangeably?

A: Neither one is really accurate, but jingoism is clearly closer.
Jingoism is an extreme patriotism, so it would only apply directly to the aspect country, then perhaps indirectly to the other aspects.
Ethnocentrism is the tendency to see ones own culture as the center, and measure everything against it. There is however nothing manical about it, rather that it's the natural starting point of viewing everything, so there is an inability to see it otherwise until you have gained perspective.

A: Use "ethnocentrism" to gently highlight that the subject in question is overly focused on itself. It generally means "to a fault," but not in an overly critical way.
Use "jingoism" to deliver a stronger rebuke. So it would apply to your quote above.
Jingo

"mindless, gung-ho patriot," 1878,
  picked up from the refrain of a music
  hall song written by G.W. Hunt
  supporting aggressive British policy
  toward Russia at a time of
  international tension. ("We don't want
  to fight, But by Jingo! if we do,
  We've got the ships, we've got the
  men, We've got the money too.")

(Online Etymology Dictionary)


text:
Q: Translating Javascript regex to Python I got a Javascript regex to repair broken JSON-Objects (my backend removes all quotes from the JSON string, the regex adds them again).
var src = '[{ key: any text with spaces, emptykey: ,  foo: 0}, { key2: other text with spaces, emptykey2: ,  foo2: 2},]';

console.log(src.replace(/(\w+):(\s*)(.*?)(,|})/g, '"$1":$2"$3"$4'));
// outputs [{ "key" : "any text with spaces", emptykey: "", "foo": "0"},...]

I need to translate this regex replace to python but I don't know how to include the part with named back references. Here is my starting point
    import json
    import re

    invalid_json = '[{ key: any text with spaces, emptykey: ,  foo: 0}, { key2: other text with spaces, emptykey2: ,  foo2: 2}]'
    result = re.sub('/(\w+):(\s*)(.*?)(,|})/g', what to do here in python?, invalid_json)
    print result

A: import json
import re

invalid_json = '[{ key: any text with spaces, emptykey: ,  foo: 0}, { key2: other text with spaces, emptykey2: ,  foo2: 2}]'
result = re.sub('(\w+):(\s*)(.*?)(,|})', r'"\1":\2"\3"\4', invalid_json)
print result
print json.loads(result)

Output:
[{ "key": "any text with spaces", "emptykey": "",  "foo": "0"}, { "key2": "other text with spaces", "emptykey2": "",  "foo2": "2"}]
[{u'emptykey': u'', u'foo': u'0', u'key': u'any text with spaces'}, {u'key2': u'other text with spaces', u'emptykey2': u'', u'foo2': u'2'}]


text:
Q: How to find closed form of a binomial series. When working on a problem, I needed to find the closed form of the infinite sequence:
$$1 - 2x + 3x^2 - 4x^3 + \cdots$$
I struggled with this for a while and eventually found, through the Internet, that it is equal to $(1+x)^{-2}$.
How could I have approached this in such a way that I would have arrived at the answer myself?

A: There are many ways to get the function from this series. One is to use negative binomial coefficients:
$$
\begin{align}
\sum_{k=0}^\infty(-1)^k\binom{k+1}{1}x^k
&=\sum_{k=0}^\infty(-1)^k\binom{k+1}{k}x^k\\
&=\sum_{k=0}^\infty\binom{-2}{k}x^k\\[4pt]
&=(1+x)^{-2}
\end{align}
$$

Another method would be to subtract the geometric series
$$
\frac1{1+x}=1-x+x^2-x^3+x^4-x^5+\dots
$$
to get
$$
\begin{align}
f(x)-\frac1{1+x}
&=-x+2x^2-3x^3+4x^4-\dots\\
&=-xf(x)
\end{align}
$$
Solving for $f(x)$ gives
$$
f(x)=\frac1{(1+x)^2}
$$

A: Method 1.  Differentiate
$$1-x+x^2-x^3+\cdots=\frac1{1+x}\ .$$
Method 2.  Write the sum out this way:
$$\eqalign{
  1-x+x^2-x^3+x^4-\cdots&\cr
  {}-x+x^2-x^3+x^4-\cdots&\cr
  {}+x^2-x^3+x^4-\cdots&\cr
  {}-x^3+x^4-\cdots&\ .\cr}$$
Adding up the first row, then the second and so on by geometric series gives
$$\frac1{1+x}-\frac{x}{1+x}+\frac{x^2}{1+x}-\frac{x^3}{1+x}+\cdots$$
which is another geometric series.

A: Let's kick it old school, like Euler - by which I mean blindly manipulate infinite series to reach correct solutions.
Okay, we have the series:
$$A=1-2x+3x^2-4x^3+\ldots.$$
then we think, hey, all those increasing terms are annoying. Notice that $Ax$ is basically shifts the coefficients of $A$, and, since the signs alternate, adding each coefficient to the one after it is going eliminate that annoying increasing-nature of that sum and leave just some residue about the common differences.
So, let's set:
$$B=A+Ax=1-x+x^2-x^3+x^4+\ldots.$$
We see that we have an alternating pattern of coefficients of $1$ and $-1$ - and hey, doing the same thing as before, we can get rid of all the coefficients by adding each coefficient to the next! So, let's do the same thing:
$$B+Bx = 1-0x+0x^2+\ldots = 1.$$
That's a constant! We can work with a constant! So, how did we get there? Well,
$$B=(1+x)A$$
$$1=(1+x)B$$
so
$$1=(1+x)^2 A$$
implying$$\frac{1}{(1+x)^2}=A.$$
What's the takeaway? Well, if you have some funky series, you can try to reduce it by looking at patterns and trying to simplify them (esp. by taking differences between terms - we can use similar methods to relate this to more general generating functions). And if you have an identity you want to prove, think about what defines that number - $\frac{1}{(1+x)^2}$ is the number which, when multiplied by $(1+x)^2$, yields one.
(Okay, all these manipulations are pretty easy to justify as we're working with absolutely convergent series, so it's not real old-school math...)

A: Hint
Integrate term by term to obtain a geometric series (this is allowed inside of the convergence radius of the series).

A: We can try to find the Taylor Series expansion (http://mathworld.wolfram.com/TaylorSeries.html) about $0$ (also known as a Maclaurin Series (http://mathworld.wolfram.com/MaclaurinSeries.html)) of $(1+x)^{-2}$:
$$\frac{d}{dx} (1+x)^{-2}=-2(1+x)^{-3}\;\;\;\;\;\;\;\;\frac{d^2}{dx^2}(1+x)^{-2}=6(1+x)^{-4}$$
In general:
$$\frac{d^n}{dx^n}(1+x)^{-2}=(-1)^n(n+1)!(1+x)^{-(n+2)}$$
Hence
$$\frac{d^n}{dx^n}(1+x)^{-2}\Big|_{x=0}=(-1)^n(n+1)!$$
Now:
$$(1+x)^{-2}=\sum_{n=0}^{\infty}\frac{d^n}{dx^n}(1+x)^{-2}\Big|_{x=0}\frac{x^n}{n!}=\sum_{n=0}^{\infty}(-1)^n\frac{(n+1)!}{n!}x^n=\sum_{n=0}^{\infty}(-1)^n (n+1)x^n$$
$$=1-2x+3x^2-4x^3+\cdots$$
As we wanted.

A: $\begin{aligned} \displaystyle \sum_{k=0}^{\infty} (-1)^{k}(k+1)x^{k} & =\sum_{k=0}^{\infty} \sum_{j=0}^{k}(-1)^{k}x^{k} \\& = \sum_{k=0}^{\infty} \sum_{j=0}^{k}(-1)^{k-j}(-1)^jx^{j}x^{k-j} \\& = \bigg(\sum_{k=0}^{\infty}(-1)^kx^k\bigg)\bigg(\sum_{k=0}^{\infty}(-1)^kx^k\bigg) \\& = \bigg(\frac{1}{1+x}\bigg)\bigg(\frac{1}{1+x}\bigg) \\& = \frac{1}{(1+x)^2}.\end{aligned} $


text:
Q: MySQL insert query failing when data gets large I have already followed the question:Data Limit on MySQL DB Insert I was unable to solve it with the limited info.
I am using WAMP.
I have numerous Rich Text editors and 4 images which are being sent over to another page by a POST request. After a certain threshold limit, the query is failing. Is there a way around?
EDIT: while displaying the query string it seems that I am able to retrieve every bit of data that was sent via POST. I am quite sure that it is DB related.
Images are being stored as a BLOB.
EDIT #2: Error showing is "MySQL server has gone away".

A: You may be violating the max_allowed_packet setting. See here for more data.
Quote,

If you are using the mysql client program, its default
  max_allowed_packet variable is 16MB.

If you are uploading uncompressed images, this value is fairly easy to reach.
Also, it would be great if you could name the specific database interface class that you use (PDO? mysql_? mysqli_?), as different classes handle errors differently. It could just as well not handle an oversized packet situation at all.
P.S.: You should really be checking your logs for the specific error you encounter. The first place to look for would be /var/log/mysql/error.log (could vary depending on your env)
Update:
mysql_error() returned "MySQL server has gone away"

From the manual pages for the error: "You can also get these errors if
  you send a query to the server that is incorrect or too large. If
  mysqld receives a packet that is too large or out of order, it assumes
  that something has gone wrong with the client and closes the
  connection. If you need big queries (for example, if you are working
  with big BLOB columns), you can increase the query limit by setting
  the server's max_allowed_packet variable, which has a default value of
  1MB. You may also need to increase the maximum packet size on the
  client end..."

(quote courtesy of @Colin Morelli)

A: sometimes, php tends to reach the memory limit if the file uploaded is too large. depending on your config, this might help:
set_time_limit(0);
ini_set('memory_limit', '-1');

A: EDIT:
if it is not the memory allocation thing we all rushed to answer
then it could be a memory engine tidbit so you could probably check that,
comment:
in my experience, it is most likely a memory issue, since it only occurs when you try bigger imports
(happens to my application when i try to return a 20MB result set from a single query)


text:
Q: How to perform Ajax Call using backbone js in MVC I have the following JavaScript code:
App.Views.AddPerson = Backbone.View.extend({
        el: '#addPerson',

        events: {
            'submit': 'submit',
        },

        submit: function (e) {
            e.preventDefault();
            var newPersonName = $(e.currentTarget).find('input[type=text]').val();
            var person = new App.Models.Person({ name: newPersonName, age: newAge, occupation: newOccupation });
            this.collection.add(person);
            this.$('#todo-title').val('');

            $.ajax({
              type: 'POST',
              url: '@Url.Action("InsertRecord", "Home")',
              data: newPersonName ,
              success: function(data) {
                alert(data);
              },
              error: function(){
                alert("error");
              }
            });
        }
    });

In the controller I have following method:
[HttpPost]
    public ActionResult InsertRecord(string str)
    {

        return View();
    }

But it is not perform the ajax call and raise the error.

A: Use this
$.ajax({
            type: 'POST',
            url: '@Url.Action("InsertRecord", "Home")',
            data: {str:newPersonName} ,  // use the same paramtre name as in Controller
            success: function(data) {
            alert(data);
              },
              error: function(){
              alert("error");
              }
           });

Hope it helps

A:   $.ajax({
            type: 'POST',
            url: window.location + "Home/InsertRecord",
            data: {ID : newPersonName,
                  Name:newAge,
                  DeptID:newOccupation },
            success: function(data) {
            alert(data);
              },
              error: function(){
              alert("error");
              }
           });

A: Try this:
 submit: function (e) {
        e.preventDefault();
        var newPersonName = $(e.currentTarget).find('input[type=text]').val();
        var person = new App.Models.Person({ name: newPersonName, age: newAge, occupation: newOccupation });
        this.collection.add(person);
        this.$('#todo-title').val('');

       $.ajax({
        type: 'POST',
        url: window.location + "Home/InsertRecord",
        data: {ID : newPersonName},
        success: function(data) {
        // Code after success },
          error: function(){
          alert("error");
          }
       });


text:
Q: ECS migration from EC2 to Fargate I am trying to migrate from Amazon ECS EC2 to Fargate. Here I have made some changes as per recommendation from https://aws.amazon.com/blogs/compute/migrating-your-amazon-ecs-containers-to-aws-fargate/. I am using amazon cloudformation to create/update the resources.
ECSTaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
        Family : !Join ["_", [!Ref "AppName", !Ref "ComponentName", !Ref "TargetEnv" ]]
        NetworkMode: "awsvpc"
        ExecutionRoleArn: arn:aws:iam::${AWS::AccountId}:role/ecsTaskExecutionRole
        TaskRoleArn:
            Fn::Sub:
                [
                    "arn:aws:iam::${AWS::AccountId}:role/exec_dp_${TargetEnv}",
                    {
                        TargetEnv: !Ref "TargetEnv"
                    }
                ]
        RequiresCompatibilities:
          - "FARGATE"
        Memory: "512"
        Cpu: '256'
        ContainerDefinitions:

Here the problem is when I try to create the stack it gives me error as below:

Unable to assume the service linked role. Please verify that the ECS service linked role exists

I have also tried creating service linked role something like below:
AwsEcsTaskExecutionRole:
     Type: AWS::IAM::Role
     Properties:
        Path: /
        AssumeRolePolicyDocument:
             Version: 2012-10-17
             Statement:
                     - Effect: Allow
             Principal:
             Service: ecs.amazonaws.com
             Action: sts:AssumeRole
        ManagedPolicyArns:
             - arn:aws:iam::aws:policy/aws-service-role/AmazonECSServiceRolePolicy

and then specified it as
ExecutionRoleArn: !GetAtt AwsEcsTaskExecutionRole.Arn
Its not working. Any direction regarding would really help.

A: Short answer:
Run this command: aws iam create-service-linked-role --aws-service-name ecs.amazonaws.com
Long answer:
AWS introduced Service-Linked Roles. For old AWS accounts or if you never created an ECS cluster by hand in the console, you have to run the command above to have the role created.


text:
Q: Power BI custom theme .json - multiple series customization I've been tinkering with .json file to create my own custom theme, however I am stuck on multiple choice setting. Example:
Area chart -> Format -> Data labels - > here I can customize the general setting for data labels, but what I would like to set up, is the "CUSTOMIZE SERIES" for each of the series. That is, I would like to have black text label color for the first serie, yellow for the second etc.
Below is the image from power bi for the category I am trying to customize:
Customize series in Power BI
Code for these labels:
"labels": [{
                    "show": true,
                    "color": {
                        "solid": {
                            "color": "#333333"
                        }
                    },
                    "labelPosition": "Under",
                    "fontSize": 14,
                    "fontFamily": "Arial",
                    "labelDensity": 30,
                    "showAll": true,
                            "enableBackground": true,
                    "backgroundTransparency": 70

What this .json code achieves, is that it sets up only the general settings for all the series. That is all series will have font size 14, font Arial, background transparency 70% etc. I would like to somehow index these series, so when this .json theme gets imported into power bi the first serie would have the customized settings that I've set up, second the same etc. E.g.:
                "labelPosition": "Under",
                "fontSize": 14,
                "fontFamily": "Arial",
                "labelDensity": 30,
                "showAll": true,
                "enableBackground": true,

                 Above are the general settings for all of the series, below would be the customized series
                 1. serie --->>>
                "backgroundTransparency": 70
                 2. serie ---->>>
                "backgroundTransparency": 60
                 3. series etc..


text:
Q: Strange IText 7 Behavior - Bug I am using ITextPdf 7.1.1 Java Library to create a report for a project. The problem is that the pdf generated inside the browser looks fine. However, when I save it as pdf and open it with a pdf reader (Preview) it generates borders in div element. Bellow are images of the problem.
Maybe the problem is at PDFCanvas Rectancle I use to generate the Headers.
PDF Generated Inside Browser:

PDF Opened In Preview After Saved To Disk:

The Code that Generates The Header is below:
 @Override
    public void handleEvent(Event event) {
        System.out.println("THIS IS ME: HEADER EVENT HANDLER STARTED.....");

        PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = documentEvent.getDocument();
        PdfPage page = documentEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        int pageNumber = pdfDoc.getPageNumber(page);

        String logoImagePath = null;

        ClassLoader classLoader = getClass().getClassLoader();
        logoImagePath = classLoader.getResource("/Images/logo.png").getPath();

        System.out.println("Page size: " + pageSize.getHeight());

        Rectangle rectangle = new Rectangle(pageSize.getLeft() + 30, pageSize.getHeight() - 114, pageSize.getWidth() - 60, 80);
        PdfCanvas pdfCanvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        pdfCanvas.rectangle(rectangle);
        pdfCanvas.setFontAndSize(FontsAndStyles.getRegularFont(), 10);
        Canvas canvas = new Canvas(pdfCanvas, pdfDoc, rectangle);

        Div header = new Div();
        header.setBorder(Border.NO_BORDER);

        try {
            Image logoImage = new Image(ImageDataFactory.create(logoImagePath));
            logoImage.setFixedPosition(15, 740);
            logoImage.scale(.15f, .15f);

            header.add(logoImage);
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
            System.err.println(ex.getMessage());
        }

        Paragraph paragraph = new Paragraph();
        Text text = new Text("\n\n\n");
        paragraph.add(text);
        paragraph.setFont(FontsAndStyles.getRegularFont());
        paragraph.setFontSize(8);
        text = new Text("http://www.histopath.gr\n");
        paragraph.setTextAlignment(TextAlignment.RIGHT);
        paragraph.add(text);
        header.add(paragraph);
        paragraph = new Paragraph();
        text = new Text("Αποκορώνου 66, ΧΑΝΙΑ, Τηλ: 2821002827, Κιν: 6948571893, 6976800330, email: histologypathology@gmail.com");
        text.setFont(FontsAndStyles.getRegularFont());
        text.setFontSize(8);
        paragraph.add(text);
        paragraph.setTextAlignment(TextAlignment.JUSTIFIED_ALL);
        header.add(paragraph);

        header.setTextAlignment(TextAlignment.CENTER);
        canvas.add(header);
        canvas.setBorder(Border.NO_BORDER);
        canvas.close();

    }

Changed Vestion to 7.1.5 but i still get the same behavior. Any Suggestions?? Hasn't anybody else faced this issue in the past??

A: Please remove this instruction:
pdfCanvas.rectangle(rectangle);

This creates a path in the content. After a path definition (and optionally a path clipping instruction) there must immediately follow a path painting instruction, cf. the copy of "Figure 9 – Graphics Objects" from ISO 32000-1 below. Instead in your case you do
pdfCanvas.setFontAndSize(FontsAndStyles.getRegularFont(), 10);

I.e. instead of the required path painting instruction, you add an instruction to set font and size.
Thus, the resulting page content stream is invalid.
Now PDF viewers usually try to make sense out of broken content. In your case they have to decide:

*

*They can simply ignore the path definition. (This is what your browser appears to do.)

*They can assume you forgot the drawing instruction and simply draw the path. (This is what your PDF reader Preview appears to do.)

Allowed instructions in different states

(ISO 32000-1 Figure 9 – Graphics Objects)


text:
Q: SSIS tasks executing in the wrong order I have a package with 4 Execute SQL tasks and a data flow task.

The sequence is defined using precedence constraints and should be:

*

*(SQL) Create table (if not exists)

*(SQL) Create backup table

*(SQL) backup and clear

*(DF) Import teams data

*(SQL) Remove stale data

However, it runs in the order 3, 2, 1, 5, 4.
I read on the net that this can be solved by deleting the tasks and adding again in the order of execution, so I did this but the result is exactly the same!
What else can I do to fix it?
[Edit]
SQL version is:
Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)   Apr  2 2010 15:48:46   Copyright (c) Microsoft Corporation  Developer Edition (64-bit) on Windows NT 6.1  (Build 7601: Service Pack 1) (Hypervisor)
[/Edit]
[Update]
SSIS package "SERVICEAREATEAMS.dtsx" starting.
Information: 0x4004300A at Data Flow Task 1, SSIS.Pipeline: Validation phase is beginning.
Error: 0xC0209303 at New Package, Connection manager "SourceConnectionOLEDB": SSIS Error Code DTS_E_OLEDB_NOPROVIDER_64BIT_ERROR.  The requested OLE DB provider OraOLEDB.Oracle.1 is not registered -- perhaps no 64-bit provider is available.  Error code: 0x00000000.
An OLE DB record is available.  Source: "Microsoft OLE DB Service Components"  Hresult: 0x80040154  Description: "Class not registered".
Error: 0xC020801C at Data Flow Task 1, Source - Query 1: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "SourceConnectionOLEDB" failed with error code 0xC0209303.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.
Error: 0xC0047017 at Data Flow Task 1, SSIS.Pipeline: component "Source - Query" (1) failed validation and returned error code 0xC020801C.
Error: 0xC004700C at Data Flow Task 1, SSIS.Pipeline: One or more component failed validation.
Error: 0xC0024107 at Data Flow Task 1: There were errors during task validation.
SSIS package "SERVICEAREATEAMS.dtsx" finished: Failure.
[/Update]
[Update 2]

[/Update 2]

A: why would yo usay it runs on that order? I can assure you that, based on your print screen, thre is no way task 3 is runnig before task 1.
If you think that because the way you see the output (your last screen), you are looking at it the wrong way. It doesnt show the order the tasks are executed, it shows each task individually (I even think they are ordered alfabetically). Also be aware on the type of task, you have the PREPARE of sql task 1 finishing at 13:57:04 and the EXECUTE of the pacakge at 13:57:06, whihc seems to be on the right order to me


text:
Q: Magento 2 CMS Page URL redirect 2.3.5 I want to redirect a custom URL and change the URL path ONLY.
If my URL is www.domain.com/about-company or www.domain.com/product-a-faq
I want these to be shown in different URL
examples -> www.domain.com/about-company I want this to be shown as www.domain.com/my-compnay/about.
second URL -> www.domain.com/product-a-faq I want this to be shown as www.domain.com/product-a/product-faq
is this possible if it is please can someone help me to write a module or guide me?
I want to do this programmatically because I have added an attribute if that is enabled the URL should redirect.

A: You can use an observer
Declare the event
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_load_before">
        <observer name="redirectcustomer" instance="Vendor\CheckUrl\Observer\RedirectCustom" />
    </event>
</config>

Then in the Oberserver catch the Url with this :
/**
 * @var Magento\Framework\UrlInterface
 */
protected $_urlInterface;

$currentUrl = $this->_urlInterface->getCurrentUrl();

Then you just have to check if this url match the one you want domin.com/about-company and if it does you make the redirection you want.
$redirectUrl = XXX;
$resultRedirect = $this->responseFactory->create();
$resultRedirect->setRedirect($redirectUrl)->sendResponse('200');


text:
Q: Proving the existence of a supremum $A=\{(1+(1/n))^n \mid n\text{ is taken from positive integers}\}$
How can I prove that the set above has a supremum? I've started with an assumption that
$(1+(1/n))^n < 3$ for every positive integer n
but I could not find a way to prove it too. Could you please give me a hint?

A: Outline: Using the Binomial Theorem, we find that
$$\left(1+\frac{1}{n}\right)^n \le 1+\frac{1}{1!}+\frac{1}{2!}+\cdots+\frac{1}{n!}.$$
The term $\frac{1}{3!}$ is less than $\frac{1}{2^2}$. Continue.


text:
Q: exception thrown in the pointer of singly linked list ok, I created a linked list using the Node class and List class. But whenever I run it using the List object, it throws an exception when I return the head in the getHead() function in Node.cpp
these are the files that I created please if anyone could know why this exception is coming it would be a blessing
//**NODE.h**
#include<iostream>
using namespace std;

class Node{
private:
    Node* head;
    int data;
public:
    Node();
    Node(int);   //insert data
    void setHead(Node*);
    Node* getHead();
    void setData(int);
    int getData();
    void printData(Node*);
};

//**Node.cpp**
#include"Node.h"

Node::Node(){
    //Node* head = new Node();
    head = NULL;
    data = 0;
}

Node::Node(int DATA){
    //Node* head = new Node();
    head = nullptr;
    data = DATA;
}

int Node::getData(){            //DATA SETTER
    return this->data;
}
void Node::setData(int DATA){   //DATA GETTER
    this->data = DATA;
}

Node* Node::getHead(){
    return head;
}
void Node::setHead(Node* NextAddress){
    this->head = NextAddress;
}

void Node::printData(Node* node){
    while(node != nullptr){
        cout<< this->data <<"\n";
        node = node->head;
    }
}

//**List.h**
#include"Node.h"

class List : public Node{
private:
   Node* head;
   Node* current;
   Node* prevcurrent;
public:
   List();
   //void setList(int);
   void insertAtBack(Node* , int);
   void insertAtFront(Node* , int);
   bool search(int);
   void print();
   ~List();
};

//**List.cpp**
#include"List.h"

List::List(){
    head=nullptr;
    current=nullptr;
    prevcurrent=nullptr;
}

void List::insertAtBack(Node* head , int Data){
Node* newNode = new Node();
newNode->setData(Data);

newNode->setHead(head);     //sets the address of the next node into the newly added node
head = newNode;
}

void List::insertAtFront(Node* head, int Data) {
    Node* temp = new Node();

}

bool List::search(int num){
Node* temp = head;
    while (temp->getHead()!=nullptr)
    {
        if (temp->getData() == num)
        {
            return true;
        }
        temp->setHead(temp->getHead());     //itereates the adress in the emp node to store the address of the next node fro the while loop
    }

}

void List::print(){
    Node* temp=head;
    while (temp->getHead() != nullptr)
    {
        cout<<temp->getData()<<" ";
    }

}

List::~List() {
    Node* temp = head;
    while (temp->getHead() != nullptr)
    {
        Node* temp2 = temp;
        temp = temp->getHead();
        delete temp2;
    }
}

//**main.cpp**
#include"List.h"
int main(){
// cout<<"running\n";
// Node box(5);         this works
// cout<<box.getData();
List obj;
Node node;              //this will throw an exception
obj.insertAtBack(&node,5);
obj.print();
}

A: Exception is thrown due to print:
void List::print() {
    Node *temp = head;
    while (temp->getHead() != nullptr) {
        cout << temp->getData() << " ";
    }
}

Here, a check is missing if temp (or equally head) is a nullptr before you dereference it in temp->getHead()
Same on List::~List


text:
Q: How to send Email in Rails for real I want to send email from my app to Gmail with real account
My code base on this website https://guides.rubyonrails.org/action_mailer_basics.html, but when I run source, the email was shown on terminal, but it was not sent to my Gmail account. What should I do to send the email to my Gmail account, so I can view it in https://mail.google.com/mail/u/0/#inbox?
Here is my code:
user_mailer.rb
class UserMailer < ApplicationMailer
  default from: 'xuanle.khtn@gmail.com'

  def sample_email
    mail to: 'leanhxuan_t59@hus.edu.vn', subject: 'Test Mail Rails'
  end
end

user_controller.rb
def index
    UserMailer.sample_email.deliver_now
end

production.rb
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.smtp_settings = {
  :address              => "mail.google.com",
  :port                 => 587,
  :user_name            => 'xuanle.khtn@gmail.com',
  :password             => '********',
  :authentication       => "plain",
  :enable_starttls_auto => true
}

A: To add email functionality to a rails project:
First run
rails g mailer <mailername>

This will give you this (you can append function names but lets keep it simple)
  create  app/mailers/mailername_mailer.rb
  invoke  erb
  create    app/views/mailername_mailer
  invoke  test_unit
  create    test/mailers/mailername_mailer_test.rb
  create    test/mailers/previews/mailername_mailer_preview.rb

Next go to app/mailers and alter the default from:
class ApplicationMailer < ActionMailer::Base
  default from: 'example@gmail.com'
  layout 'mailer'
end

This is going to tell your application that you're sending FROM this email (you will have to provide credentials later...)
Next head into your created mailers file app/mailers/mailername_mailer.rb
NOTICE: It inherits from ApplicationMailer so you'll get the 'default from' that we declared above.
class MailernameMailer < ApplicationMailer
  def request(arg)
    @arg = arg
    mail(to: "example@gmail.com", subject: @arg)
  end
end

This mailer is essentially a class, but the instantiating works a bit differently.
 It creates an instance when you call it statically...like you would a model.  The mail(to: x) is the account you're going to mail this to. You can use this in your controller.  Like this:
ExampleController.rb
def index
     MailernameMailer.request("Hi I'm paul").deliver_later
end

For the view:
A cool feature for emails is the previews built into rails.
 The test action can be called in your mailername_mailer_preview.rb file found in test/mailers/previews.
Here is what it should look like:
def request(args)
    @name = args
    MailernameMailer.request(@name)
  end

Just like above in the controller, you're going to add the instantiation and call the function..then use that data in your view found at: app/views/mailername_mailer/request.html.erb
and preview it at:
http://localhost:3000/rails/mailers/mailername_mailer
Your mailer action is going to route to a view with the same name as the function automatically...
Now for the validation of the sender account... (Gmail needs a valid account in order to send an email). Change your production.rb file to look like this..although you should probably get this working on development before moving to production, considering you don't always have to have best practices until you push to production.
  config.action_mailer.delivery_method = :smtp
  config.action_mailer.smtp_settings = {
      address: "smtp.gmail.com",
      port: 587,
      domain: "gmail.com",
      user_name: ENV["username"],
      password: ENV["password"],
      authentication: "plain"
  }
  config.action_mailer.default_url_options = {host: domain_name}

domain_name should just be localhost:3000 for development.

A: Try turning this setting for your receiving email on:
https://myaccount.google.com/lesssecureapps


text:
Q: Can't make a proper gradient fade effect I'm trying to make a gradient overlay in my images, that makes this effect:

As you can see, gradient will be darker at the bottom, BUT, the top WONT be affected by the darkness.
I've tried this:
@include linear-gradient(to top, rgba(0,0,0,0.4) 0%, rgba(255,255,255,1));

But this will make a whitish effect at the top. I want the gradient to darken only the bottom part of the image, and DON'T do anything to the upper part of the image.
Has anyone know how to do this?
Thanks

A: You can use the following CSS, http://jsfiddle.net/3sxd82nf/5/

x

    #test {
        position:absolute;
        top: 10px;
        left: 0px;
        width: 200px;
        height: 200px;
        background-image: url('http://images2.layoutsparks.com/1/198321/50s-diner-chick-squares.jpg');

    }
#gradient {
     position:absolute;
    top: 10px;
    left: 0px;
    width: 200px;
    height: 200px;

background: -moz-linear-gradient(top,  rgba(0,0,0,0) 50%, rgba(0,0,0,1) 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(50%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top,  rgba(0,0,0,0) 50%,rgba(0,0,0,1) 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top,  rgba(0,0,0,0) 50%,rgba(0,0,0,1) 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top,  rgba(0,0,0,0) 50%,rgba(0,0,0,1) 100%); /* IE10+ */
background: linear-gradient(to bottom,  rgba(0,0,0,0) 50%,rgba(0,0,0,1) 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00000000', endColorstr='#000000',GradientType=0 ); /* IE6-9 */

}


text:
Q: My code (php/js) confuses when I use a variable followed by a number that is bigger than 9 Hello my problem is with my php/javascript code. My variables start from extra1 and ends at extra 12.
The problem is that extra10 , extra11 and extra12 that have two digits confuses the script like there is nothing more than 9.
My code consists of many forms and with this javascript I create a nicer url. Instead of mydomain.com/?extra1=&extra2=abs&extra3=def&extra4= it creates this mydomain.com/?extra2=abs&extra3=def for the php script to get from the url and continue.
Everything works great for variables until extra9.
This is my javascript
<script type="text/javascript">
function formSubmit() {
    var extra1 = document.getElementById('extra1');
    var extra2 = document.getElementById('extra2');
    var extra3 = document.getElementById('extra3');
    var extra4 = document.getElementById('extra4');
    var extra5 = document.getElementById('extra5');
    var extra6 = document.getElementById('extra6');
    var extra7 = document.getElementById('extra7');
    var extra8 = document.getElementById('extra8');
    var extra9 = document.getElementById('extra9');
    var extra10 = document.getElementById('extra10');
    var extra11 = document.getElementById('extra11');
    var extra12 = document.getElementById('extra12');
    if (extra1.value == '') {
        extra1.parentNode.removeChild(extra1);
    }
    if (extra2.value == '') {
        extra2.parentNode.removeChild(extra2);
    }
    if (extra3.value == '') {
        extra3.parentNode.removeChild(extra3);
    }
    if (extra4.value == '') {
        extra4.parentNode.removeChild(extra4);
    }
    if (extra5.value == '') {
        extra5.parentNode.removeChild(extra5);
    }
    if (extra6.value == '') {
        extra6.parentNode.removeChild(extra6);
    }
    if (extra7.value == '') {
        extra7.parentNode.removeChild(extra7);
    }
    if (extra8.value == '') {
        extra8.parentNode.removeChild(extra8);
    }
    if (extra9.value == '') {
        extra9.parentNode.removeChild(extra9);
    }
    if (extra10.value == '') {
        extra10.parentNode.removeChild(extra10);
    }
    if (extra11.value == '') {
        extra11.parentNode.removeChild(extra11);
    }
    if (extra12.value == '') {
        extra12.parentNode.removeChild(extra12);
    }
    return true;
}
</script>

and this is the code from the submitted php that gets the data from the url. it's used on wordpress but is a general php programming
for ($i = 1; array_key_exists('extra'. $i, $_GET); $i++) {
    $args['meta_query'][] = array(
        'key' => 'extra'. $i,
        'value' => $_GET['extra'. $i],
        'compare' => '=',
    );
}

$query = new WP_Query( $args );

As I said everything works fine for variables < 10.
Thank you for your info

A: In your code, any extraXX which is blank would cause your for loop on the server-side to exit.  This means that any extraXX field after the blank one, would not get processed.  In order to get around this, you should really be using input arrays (name your fields as extra[] in your html) but if you want to keep all the code you have currently, you can do this:
<?php
foreach ($_GET as $key => $value)
{
    if (substr($key, 0, 5) == 'extra')
    {
        $args['meta_query'][] = array(
            'key' => $key,
            'value' => $value,
            'compare' => '='
        );
    }
}

This will loop through every $_GET parameter and check to see if it beings with extra, and if it does, add it to your array.

A: It fails because in alphabetic order, extra10 comes right after extra1. When it finds out that there's no value for extra10, it stops checking for other fields.
Although there are nicer solutions for this problem, using always 2 digitas may work (for instance, extra01, extra02, etc).

A: To solve your PHP problem, you could do this:
foreach ($_GET as $key=>$value)
{
    if (preg_match("@extra(\d+)@", $key))
    {
        $args["meta_query"][] = array
        (   "key" => $key
        ,   "value" => $value
        ,   "compare" => "="
        )
    }
}

$query = new WP_Query( $args );

Your previous code didn't work, because the first non-existing key would cause the for loop to break. For instance, if the 9th field was removed with JavaScript, the loop would have exited at the 8th, leaving all the other ones.
The script above scans all $_GET variables, and only treats those corresponding to the given RegExp pattern (extra followed by any number of digits).
Also, your JavaScript could be a lot shorter and easier to understand like this:
function formSubmit() {
    for (var i=1 ; i<13 ; i++)
    {
        var extra = document.getElementById('extra' + i);
        if (extra.value == '')
        {
            extra.parentNode.removeChild(extra);
        }
    }
    return true;
}

A: I don't think this is a good idea, it does nothing of any value unless you are expecting your users to read the URL. Anyway, you can just cycle through the form controls and disable any whose value is '', e.g.:
<script type="text/javascript">

function disableEmpties(form) {
  var el, elements = form.elements;
  var i = elements.length;
  var dontDisableTypes = {
    submit: 'submit',
    reset: 'reset'
  };

  while (i--) {
    el = elements[i];
    alert(el.name + ': ' + el.value);

    if ((!el.value || el.value == '') && !(el.type in dontDisableTypes)) {
      el.disabled = true;
    }
  }
}

</script>

<form action="#" onsubmit="disableEmpties(this)">
  <input name="foo">
  <input name="bar">
  <input name="glum">
  <input type="submit">
</form>


text:
Q: JQUERY: identify submit button from  How can I determine which submit button was clicked?
I do not want to use <form>, because the page refreshes. By clicking the submit button, a PHP-file gives back a response that is shown on the current page.
HTML in index.html:

        [...]

                    First name

                  <input type="text" class="form-control" name="registerFirstname" id="firstname">

                    Last name

                  <input type="text" class="form-control" name="registerLastname" id="lastname">

                  <button type="submit" class="btn btn-primary" id="sublogreg">  Register</button>
                  <button type="submit" class="btn btn-primary" id="subloginfo">  Request information</button>

             [...]

jQuery script in index.html:


text:
Q: Text Extraction based on defined format?
*

*I have to work on a task where there is a log file provided to me.

*This logfile is generated from CISCO ASA Firewall.

*The log lines look like this:
2013-05-09 11:04:32     Local4.Debug    172.24.100.111
%ASA-7-710005: TCP request discarded from 172.17.38.35/63867 to
inside:172.24.100.111/443 2013-05-09 11:04:32     Local4.Debug
172.24.100.111  %ASA-7-609002: Teardown local-host outside:207.46.15.252 duration 0:00:00 2013-05-09 11:04:32
Local4.Debug    172.24.100.111  %ASA-7-609001: Built local-host
outside:64.145.75.27 2013-05-09 11:04:32     Local4.Debug
172.24.100.111  %ASA-7-609002: Teardown local-host outside:64.145.75.27 duration 0:00:00 2013-05-09 11:04:32
Local4.Debug    172.24.100.111  %ASA-7-609001: Built local-host
outside:216.156.147.26 2013-05-09 11:04:32     Local4.Debug
172.24.100.111  %ASA-7-609002: Teardown local-host outside:216.156.147.26 duration 0:00:00 2013-05-09 11:04:33
Local4.Debug    172.24.100.111  %ASA-7-609001: Built local-host
outside:74.125.224.220 2013-05-09 11:04:33     Local4.Debug
172.24.100.111  %ASA-7-609002: Teardown local-host outside:74.125.224.220 duration 0:00:00 2013-05-09 11:04:34
Local4.Debug    172.24.100.111  %ASA-7-710005: UDP request discarded
from 172.24.6.11/68 to inside:255.255.255.255/67

I looked around and found that these rules are well defined in their handbook
Questions

*

*What the the best way to extract each piece of information based on the rules mentioned in the handbook, rather than running regular expressions and taking value out? I mean can we generate rule based parsing?

*Given that this is one of the logs, I am sure there would be many log formats supported by many firewalls and they will have their own guidelines as how to read, is there a generic framework that can be built? What framework/library helps you with that?

I am looking for guidance since I don't know much in this area.
Thank you


text:
Q: Converting 3D Max Model to XAML? Are there any free tools for converting a 3D Max model to WPF XAML?
Thank you.

A: Check out the Xaml exporter for 3D Max!
http://max2xaml.codeplex.com/
Microsoft blog article explaining it more:
http://blogs.microsoft.co.il/blogs/maxim/archive/2009/03/31/daily-tip-how-to-import-3d-model-to-wpf-from-3d-max.aspx

A: U can use blender and max2xaml. Both can help u.